]> git.basschouten.com Git - openhab-addons.git/blob
1c3e52ace54cb0fd3ddd30cb20efd837caf2abbe
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.satel.internal.command;
14
15 import org.apache.commons.lang.StringUtils;
16 import org.eclipse.jdt.annotation.NonNullByDefault;
17 import org.openhab.binding.satel.internal.protocol.SatelMessage;
18
19 /**
20  * Base class for all commands that return result code in the response.
21  *
22  * @author Krzysztof Goworek - Initial contribution
23  */
24 @NonNullByDefault
25 public abstract class ControlCommand extends SatelCommandBase {
26
27     /**
28      * Creates new command class instance.
29      *
30      * @param commandCode command code
31      * @param payload command bytes
32      */
33     public ControlCommand(byte commandCode, byte[] payload) {
34         super(commandCode, payload);
35     }
36
37     @Override
38     protected boolean isResponseValid(SatelMessage response) {
39         return true;
40     }
41
42     protected static byte[] userCodeToBytes(String userCode) {
43         if (StringUtils.isEmpty(userCode)) {
44             throw new IllegalArgumentException("User code is empty");
45         }
46         if (userCode.length() > 8) {
47             throw new IllegalArgumentException("User code too long");
48         }
49         byte[] bytes = new byte[8];
50         int digitsNbr = 2 * bytes.length;
51         for (int i = 0; i < digitsNbr; ++i) {
52             if (i < userCode.length()) {
53                 char digit = userCode.charAt(i);
54                 if (!Character.isDigit(digit)) {
55                     throw new IllegalArgumentException("User code must contain digits only");
56                 }
57                 if (i % 2 == 0) {
58                     bytes[i / 2] = (byte) ((digit - '0') << 4);
59                 } else {
60                     bytes[i / 2] |= (byte) (digit - '0');
61                 }
62             } else if (i % 2 == 0) {
63                 bytes[i / 2] = (byte) 0xff;
64             } else if (i == userCode.length()) {
65                 bytes[i / 2] |= 0x0f;
66             }
67         }
68
69         return bytes;
70     }
71 }