]> git.basschouten.com Git - openhab-addons.git/blob
11e7cde2d1fac41ab190f2c01cace98817fb1933
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.dali.internal.protocol;
14
15 import java.util.ArrayList;
16 import java.util.List;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.openhab.binding.dali.internal.handler.DaliException;
20
21 /**
22  * The {@link DaliFrame} represents a message on the DALI bus.
23  *
24  * @author Robert Schmid - Initial contribution
25  */
26 @NonNullByDefault
27 public class DaliFrame {
28     int bits;
29     int data;
30
31     public DaliFrame(int bits, byte[] data) throws DaliException {
32         if (bits < 1) {
33             throw new DaliException("Frames must contain at least 1 data bit");
34         }
35
36         this.bits = bits;
37
38         int d = 0;
39         for (byte b : data) {
40             d = (d << 8) | Byte.toUnsignedInt(b);
41         }
42
43         this.data = d;
44
45         if (this.data < 0) {
46             throw new DaliException("Initial data must not be negative");
47         }
48
49         if (Math.abs(this.data) >= (1 << this.bits)) {
50             throw new DaliException("Initial data will not fit in the specified number of bits");
51         }
52     }
53
54     public int length() {
55         return this.bits;
56     }
57
58     public byte[] pack() {
59         int remaining = length();
60         List<Byte> bytesList = new ArrayList<Byte>();
61         int tmp = this.data;
62         while (remaining > 0) {
63             bytesList.add((byte) (tmp & 0xff));
64             tmp = tmp >> 8;
65             remaining = remaining - 8;
66         }
67         byte[] result = new byte[bytesList.size()];
68         int i = 0;
69         for (byte b : bytesList) {
70             result[bytesList.size() - ++i] = b;
71         }
72         return result;
73     }
74 }