2 * Copyright (c) 2010-2021 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;
17 import org.openhab.binding.satel.internal.util.StringUtils;
20 * Base class for all commands that return result code in the response.
22 * @author Krzysztof Goworek - Initial contribution
25 public abstract class ControlCommand extends SatelCommandBase {
28 * Creates new command class instance.
30 * @param commandCode command code
31 * @param payload command bytes
33 public ControlCommand(byte commandCode, byte[] payload) {
34 super(commandCode, payload);
38 * Creates new command class instance.
40 * @param commandCode command code
41 * @param payload command bytes
42 * @param userCode user code
44 public ControlCommand(byte commandCode, byte[] payload, String userCode) {
45 super(commandCode, appendUserCode(payload, userCode));
49 protected boolean isResponseValid(SatelMessage response) {
53 protected static byte[] appendUserCode(byte[] payload, String userCode) {
54 byte[] userCodeBytes = userCodeToBytes(userCode);
55 byte[] result = new byte[userCodeBytes.length + payload.length];
56 System.arraycopy(userCodeBytes, 0, result, 0, userCodeBytes.length);
57 System.arraycopy(payload, 0, result, userCodeBytes.length, payload.length);
61 protected static byte[] userCodeToBytes(String userCode) {
62 if (StringUtils.isEmpty(userCode)) {
63 throw new IllegalArgumentException("User code is empty");
65 if (userCode.length() > 8) {
66 throw new IllegalArgumentException("User code too long");
68 byte[] bytes = new byte[8];
69 int digitsNbr = 2 * bytes.length;
70 for (int i = 0; i < digitsNbr; ++i) {
71 if (i < userCode.length()) {
72 char digit = userCode.charAt(i);
73 if (!Character.isDigit(digit)) {
74 throw new IllegalArgumentException("User code must contain digits only");
77 bytes[i / 2] = (byte) ((digit - '0') << 4);
79 bytes[i / 2] |= (byte) (digit - '0');
81 } else if (i % 2 == 0) {
82 bytes[i / 2] = (byte) 0xff;
83 } else if (i == userCode.length()) {