]> git.basschouten.com Git - openhab-addons.git/blob
c36f52070aa7e88b770b1ffef3b51748dbf9a405
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.IOException;
16 import java.net.Socket;
17 import java.nio.ByteBuffer;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20
21 /**
22  *
23  * @author Hans van den Bogert - Initial Contribution
24  *
25  */
26 @NonNullByDefault
27 public class OmnikInverter {
28
29     private final int serialNumber;
30     private final String host;
31     private final int port;
32     private final byte[] magicPacket;
33
34     public OmnikInverter(String host, int port, int serialNumber) {
35         this.host = host;
36         this.port = port;
37         this.serialNumber = serialNumber;
38         this.magicPacket = generateMagicPacket();
39     }
40
41     public OmnikInverterMessage pullCurrentStats() throws IOException {
42         byte[] magicPacket = this.magicPacket;
43         byte[] returnMessage = new byte[1024];
44
45         try (Socket socket = new Socket(host, port)) {
46             socket.setSoTimeout(5000);
47             socket.getOutputStream().write(magicPacket);
48             socket.getInputStream().read(returnMessage);
49
50             return new OmnikInverterMessage(returnMessage);
51         }
52     }
53
54     private byte[] generateMagicPacket() {
55         ByteBuffer serialByteBuffer = ByteBuffer.allocate(8).putInt(serialNumber).putInt(serialNumber);
56         byte[] serialBytes = serialByteBuffer.array();
57
58         // reverse array
59         for (int i = 0; i < serialBytes.length / 2; i++) {
60             byte temp = serialBytes[i];
61             serialBytes[i] = serialBytes[serialBytes.length - i - 1];
62             serialBytes[serialBytes.length - i - 1] = temp;
63         }
64
65         byte checksumCount = 115;
66         for (byte b : serialBytes) {
67             checksumCount += (char) b;
68         }
69
70         byte[] result = new byte[16];
71         System.arraycopy(new byte[] { 0x68, 0x02, 0x40, 0x30 }, 0, result, 0, 4);
72         System.arraycopy(serialBytes, 0, result, 4, 8);
73         System.arraycopy(new byte[] { 0x01, 0x00, checksumCount, 0x16 }, 0, result, 12, 4);
74
75         return result;
76     }
77 }