2 * Copyright (c) 2010-2023 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.satel.internal.command;
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16 import org.openhab.binding.satel.internal.protocol.SatelMessage;
19 * Base class for all commands that return result code in the response.
21 * @author Krzysztof Goworek - Initial contribution
24 public abstract class ControlCommand extends SatelCommandBase {
27 * Creates new command class instance.
29 * @param commandCode command code
30 * @param payload command bytes
32 public ControlCommand(byte commandCode, byte[] payload) {
33 super(commandCode, payload);
37 * Creates new command class instance.
39 * @param commandCode command code
40 * @param payload command bytes
41 * @param userCode user code
43 public ControlCommand(byte commandCode, byte[] payload, String userCode) {
44 super(commandCode, appendUserCode(payload, userCode));
48 protected boolean isResponseValid(SatelMessage response) {
52 protected static byte[] appendUserCode(byte[] payload, String userCode) {
53 byte[] userCodeBytes = userCodeToBytes(userCode);
54 byte[] result = new byte[userCodeBytes.length + payload.length];
55 System.arraycopy(userCodeBytes, 0, result, 0, userCodeBytes.length);
56 System.arraycopy(payload, 0, result, userCodeBytes.length, payload.length);
60 protected static byte[] userCodeToBytes(String userCode) {
61 if (userCode.isEmpty()) {
62 throw new IllegalArgumentException("User code is empty");
64 if (userCode.length() > 8) {
65 throw new IllegalArgumentException("User code too long");
67 byte[] bytes = new byte[8];
68 int digitsNbr = 2 * bytes.length;
69 for (int i = 0; i < digitsNbr; ++i) {
70 if (i < userCode.length()) {
71 char digit = userCode.charAt(i);
72 if (!Character.isDigit(digit)) {
73 throw new IllegalArgumentException("User code must contain digits only");
76 bytes[i / 2] = (byte) ((digit - '0') << 4);
78 bytes[i / 2] |= (byte) (digit - '0');
80 } else if (i % 2 == 0) {
81 bytes[i / 2] = (byte) 0xff;
82 } else if (i == userCode.length()) {