2 * Copyright (c) 2010-2022 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.elroconnects.internal.util;
15 import java.nio.charset.StandardCharsets;
16 import java.util.Arrays;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.core.util.HexUtils;
23 * The {@link ElroConnectsUtil} contains a few utility methods for the ELRO Connects binding.
25 * @author Mark Herwege - Initial contribution
28 public final class ElroConnectsUtil {
30 private static final int POLYNOMIAL = 0x0000a001; // polynomial for CRC calculation
32 public static int encode(int value) {
33 return (((value ^ 0xFFFFFFFF) + 0x10000) ^ 0x123) ^ 0x1234;
36 public static int decode(int value, int msgId) {
37 return (byte) (0xFFFF + ~((value ^ 0x1234) ^ msgId));
41 * Encode input string into hex
44 * @param length byte length for input string in UTF-8 encoding, further characters will be cut
45 * @return encoded hex string cut to length
47 public static String encode(String input, int length) {
48 byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
49 String content = "@".repeat(length - bytes.length) + new String(bytes, StandardCharsets.UTF_8) + "$";
50 bytes = content.getBytes(StandardCharsets.UTF_8);
51 return HexUtils.bytesToHex(bytes);
55 * Decode hex string using UTF-8 encoding and drop leading @ characters and trailing $
57 * @param input hex string
58 * @return string contained in input
60 public static String decode(String input) {
61 return (new String(HexUtils.hexToBytes(input), StandardCharsets.UTF_8)).replaceAll("[@$]*", "");
65 * Compare first bytes of byte representation of input strings in UTF-8 encoding
69 * @param length number of bytes to compare
70 * @return true if equal
72 public static boolean equals(String string1, String string2, int length) {
73 byte[] bytes1 = Arrays.copyOf(string1.getBytes(StandardCharsets.UTF_8), length);
74 byte[] bytes2 = Arrays.copyOf(string2.getBytes(StandardCharsets.UTF_8), length);
75 return Arrays.equals(bytes1, bytes2);
79 * Calculate CRC-16 for input string. The input string should be treated as ASCII characters. The calculation is
80 * based on the MODBUS CRC-16 calculation.
83 * @return crc hex format
85 public static String crc16(String input) {
86 byte[] bytes = input.getBytes(StandardCharsets.US_ASCII);
88 for (byte curByte : bytes) {
90 for (int i = 0; i < 8; i++) {
91 if ((crc & 0x00000001) == 1) {
99 return Integer.toHexString(crc);
102 public static String stringOrEmpty(@Nullable String data) {
103 return (data == null ? "" : data);
106 public static int intOrZero(@Nullable Integer data) {
107 return (data == null ? 0 : data);