]> git.basschouten.com Git - openhab-addons.git/blob
4b87326b347160a841a38d77ed5d9a7082ad372f
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.paradoxalarm.internal.communication.messages;
14
15 import java.nio.ByteBuffer;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18
19 /**
20  * The {@link CommandPayload} Class that structures the payload for partition commands.
21  *
22  * @author Konstantin Polihronov - Initial contribution
23  */
24 @NonNullByDefault
25 public class CommandPayload implements IPayload {
26
27     private static final int BYTES_LENGTH = 15;
28
29     private final byte MESSAGE_START = 0x40;
30     private final byte PAYLOAD_SIZE = 0x0f;
31     private final byte[] EMPTY_FOUR_BYTES = { 0, 0, 0, 0 };
32     private final byte CHECKSUM = 0;
33
34     private final int partitionNumber;
35     private final PartitionCommand command;
36
37     public CommandPayload(int partitionNumber, PartitionCommand command) {
38         this.partitionNumber = partitionNumber;
39         this.command = command;
40     }
41
42     @Override
43     public byte[] getBytes() {
44         byte[] bufferArray = new byte[BYTES_LENGTH];
45         ByteBuffer buf = ByteBuffer.wrap(bufferArray);
46         buf.put(MESSAGE_START);
47         buf.put(PAYLOAD_SIZE);
48         buf.put(EMPTY_FOUR_BYTES);
49         buf.put(calculateMessageBytes());
50         buf.put(EMPTY_FOUR_BYTES);
51         buf.put(CHECKSUM);
52         return bufferArray;
53     }
54
55     /*
56      * The message bytes contain nibbles of command information. First byte, first nibble is partition 1, first byte,
57      * second nibble is partition 2, second byte, first nibble is partition 3, etc...
58      *
59      * For command values that are set in byte nibbles, see PartitionCommand enum
60      */
61     private byte[] calculateMessageBytes() {
62         byte[] result = { 0, 0, 0, 0 };
63         int index = (partitionNumber - 1) / 2;
64         result[index] = (byte) (calculateNibbleToSet() & 0xff);
65         return result;
66     }
67
68     private int calculateNibbleToSet() {
69         if ((partitionNumber - 1) % 2 == 0) {
70             return (command.getCommand() << 4) & 0xF0;
71         } else {
72             return command.getCommand() & 0x0F;
73         }
74     }
75 }