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.nikobus.internal.utils;
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.openhab.core.util.HexUtils;
20 * The {@link CRCUtil} class defines utility functions to calculate CRC used by the Nikobus communication protocol.
22 * @author Davy Vanherbergen - Initial contribution
23 * @author Boris Krivonog - Removed dependency to javax.xml.bind.DatatypeConverter
26 public class CRCUtil {
28 private static final int CRC_INIT = 0xFFFF;
30 private static final int POLYNOMIAL = 0x1021;
33 * Calculate the CRC16-CCITT checksum on the input string and return the
34 * input string with the checksum appended.
37 * String representing hex numbers.
38 * @return input string + CRC.
40 public static @Nullable String appendCRC(@Nullable String input) {
47 for (byte b : HexUtils.hexToBytes(input)) {
48 for (int i = 0; i < 8; i++) {
49 if (((b >> (7 - i) & 1) == 1) ^ ((check >> 15 & 1) == 1)) {
51 check = check ^ POLYNOMIAL;
58 check = check & CRC_INIT;
59 String checksum = Utils.leftPadWithZeros(Integer.toHexString(check), 4);
60 return (input + checksum).toUpperCase();
64 * Calculate the second checksum on the input string and return the
65 * input string with the checksum appended.
68 * String representing a nikobus command.
69 * @return input string + CRC.
71 public static String appendCRC2(String input) {
74 for (byte b : input.getBytes()) {
78 for (int i = 0; i < 8; i++) {
80 if (((check & 0xff) >> 7) != 0) {
90 return input + Utils.leftPadWithZeros(Integer.toHexString(check), 2).toUpperCase();