]> git.basschouten.com Git - openhab-addons.git/blob
7281c69ebea72ce41050ddc1a672e9b56270e1bc
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.omnikinverter.internal;
14
15 import java.io.ByteArrayOutputStream;
16 import java.io.IOException;
17 import java.net.Socket;
18 import java.net.UnknownHostException;
19 import java.nio.ByteBuffer;
20
21 import org.apache.commons.lang.ArrayUtils;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23
24 /**
25  *
26  * @author Hans van den Bogert - Initial Contribution
27  *
28  */
29 @NonNullByDefault
30 public class OmnikInverter {
31
32     private int serialNumber;
33     private String host;
34     private int port;
35     private byte[] magicPacket;
36
37     public OmnikInverter(String host, int port, int serialNumber) throws IOException {
38         this.host = host;
39         this.port = port;
40         this.serialNumber = serialNumber;
41         this.magicPacket = generateMagicPacket();
42     }
43
44     public OmnikInverterMessage pullCurrentStats() throws UnknownHostException, IOException {
45         byte[] magicPacket = this.magicPacket;
46         byte[] returnMessage = new byte[1024];
47
48         try (Socket socket = new Socket(host, port)) {
49             socket.setSoTimeout(5000);
50             socket.getOutputStream().write(magicPacket);
51             socket.getInputStream().read(returnMessage);
52
53             return new OmnikInverterMessage(returnMessage);
54         }
55     }
56
57     private byte[] generateMagicPacket() throws IOException {
58         byte[] magic = { 0x68, 0x02, 0x40, 0x30 };
59
60         ByteBuffer serialByteBuffer = ByteBuffer.allocate(8).putInt(serialNumber).putInt(serialNumber);
61         byte[] serialBytes = serialByteBuffer.array();
62         // Reverse serialBytes in a very mutable way.
63         ArrayUtils.reverse(serialBytes);
64
65         byte checksumCount = 115;
66         for (byte b : serialBytes) {
67             checksumCount += (char) b;
68         }
69
70         byte[] checksum = ByteBuffer.allocate(1).put(checksumCount).array();
71
72         try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
73             outputStream.write(magic);
74             outputStream.write(serialBytes);
75             outputStream.write(0x01);
76             outputStream.write(0x00);
77             outputStream.write(checksum);
78             outputStream.write(0x16);
79
80             return outputStream.toByteArray();
81         }
82     }
83 }