]> git.basschouten.com Git - openhab-addons.git/blob
b76bc5ebac217f30b0e42b3e42eb5cbff6d9ff0c
[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.velbus.internal.packets;
14
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16
17 /**
18  * The {@link VelbusPacket} represents a base class for a Velbus packet and contains
19  * functionality that is applicable to all Velbus packets.
20  *
21  * @author Cedric Boon - Initial contribution
22  */
23 @NonNullByDefault
24 public abstract class VelbusPacket {
25     public static final byte STX = 0x0F;
26     public static final byte PRIO_HI = (byte) 0xF8;
27     public static final byte PRIO_LOW = (byte) 0xFB;
28     public static final byte ETX = 0x04;
29
30     private byte address;
31     private byte priority;
32     private byte rtr;
33
34     protected VelbusPacket(byte address, byte priority) {
35         this(address, priority, false);
36     }
37
38     protected VelbusPacket(byte address, byte priority, boolean rtr) {
39         this.address = address;
40         this.priority = priority;
41         this.rtr = rtr ? (byte) 0x40 : (byte) 0x00;
42     }
43
44     public byte[] getBytes() {
45         byte[] dataBytes = getDataBytes();
46         int dataBytesLength = dataBytes.length;
47         byte[] packetBytes = new byte[6 + dataBytesLength];
48
49         packetBytes[0] = STX;
50         packetBytes[1] = priority;
51         packetBytes[2] = address;
52         packetBytes[3] = (byte) (rtr | dataBytesLength);
53
54         System.arraycopy(dataBytes, 0, packetBytes, 4, dataBytes.length);
55
56         packetBytes[4 + dataBytesLength] = computeCRCByte(packetBytes);
57         packetBytes[5 + dataBytesLength] = ETX;
58
59         return packetBytes;
60     }
61
62     protected abstract byte[] getDataBytes();
63
64     public static byte computeCRCByte(byte[] packetBytes) {
65         int crc = 0;
66
67         for (int i = 0; i < packetBytes.length - 2; i++) {
68             crc = (crc + (packetBytes[i] & 0xFF)) & 0xFF;
69         }
70
71         return (byte) (0x100 - crc);
72     }
73 }