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