2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.omnikinverter.internal;
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;
21 import org.apache.commons.lang.ArrayUtils;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
26 * @author Hans van den Bogert - Initial Contribution
30 public class OmnikInverter {
32 private int serialNumber;
35 private byte[] magicPacket;
37 public OmnikInverter(String host, int port, int serialNumber) throws IOException {
40 this.serialNumber = serialNumber;
41 this.magicPacket = generateMagicPacket();
44 public OmnikInverterMessage pullCurrentStats() throws UnknownHostException, IOException {
45 byte[] magicPacket = this.magicPacket;
46 byte[] returnMessage = new byte[1024];
48 try (Socket socket = new Socket(host, port)) {
49 socket.setSoTimeout(5000);
50 socket.getOutputStream().write(magicPacket);
51 socket.getInputStream().read(returnMessage);
53 return new OmnikInverterMessage(returnMessage);
57 private byte[] generateMagicPacket() throws IOException {
58 byte[] magic = { 0x68, 0x02, 0x40, 0x30 };
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);
65 byte checksumCount = 115;
66 for (byte b : serialBytes) {
67 checksumCount += (char) b;
70 byte[] checksum = ByteBuffer.allocate(1).put(checksumCount).array();
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);
80 return outputStream.toByteArray();