2 * Copyright (c) 2010-2022 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.novafinedust.internal.sds011protocol.messages;
15 import java.io.ByteArrayOutputStream;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.openhab.core.util.HexUtils;
21 * Message to be send to the device
23 * @author Stefan Triller - Initial contribution
27 public class CommandMessage {
28 private static final byte HEAD = -86; // AA
29 private static final byte COMMAND_ID = -76; // B4
30 private static final byte TAIL = -85; // AB
32 private static final int DATA_BYTES_AFTER_FIRST_DATA_BYTE = 12;
34 private final byte firstDataByte;
35 private byte[] payLoad = new byte[DATA_BYTES_AFTER_FIRST_DATA_BYTE];
36 private byte[] targetDevice = new byte[] { -1, -1 }; // FF FF = all devices
38 public CommandMessage(byte command, byte[] payLoad) {
39 this.firstDataByte = command;
40 this.payLoad = payLoad;
43 public CommandMessage(byte command, byte[] payLoad, byte[] targetDevice) {
44 this.firstDataByte = command;
45 this.payLoad = payLoad;
46 this.targetDevice = targetDevice;
50 * Get the raw bytes to be send out to the device
52 * @return ByteArray containing the bytes for a message to the device
54 public byte[] getBytes() {
55 ByteArrayOutputStream message = new ByteArrayOutputStream(19);
58 message.write(COMMAND_ID);
59 message.write(firstDataByte);
61 for (byte b : payLoad) {
64 int padding = DATA_BYTES_AFTER_FIRST_DATA_BYTE - payLoad.length;
65 for (int i = 0; i < padding; i++) {
69 for (byte b : targetDevice) {
72 message.write(calculateCheckSum(message.toByteArray()));
75 return message.toByteArray();
78 private byte calculateCheckSum(byte[] data) {
80 for (int i = 2; i <= 14; i++) {
83 checksum = (checksum - 2) % 256;
85 return (byte) checksum;
89 public String toString() {
90 StringBuilder sb = new StringBuilder();
91 sb.append("Message: ");
92 sb.append("Command=" + firstDataByte);
93 sb.append(" Target Device=" + HexUtils.bytesToHex(targetDevice));
94 sb.append(" Payload=" + HexUtils.bytesToHex(payLoad));