2 * Copyright (c) 2010-2020 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.apache.commons.lang.StringUtils;
16 import org.openhab.core.util.HexUtils;
19 * The {@link CRCUtil} class defines utility functions to calculate CRC used by the Nikobus communication protocol.
21 * @author Davy Vanherbergen - Initial contribution
22 * @author Boris Krivonog - Removed dependency to javax.xml.bind.DatatypeConverter
24 public class CRCUtil {
26 private static final int CRC_INIT = 0xFFFF;
28 private static final int POLYNOMIAL = 0x1021;
31 * Calculate the CRC16-CCITT checksum on the input string and return the
32 * input string with the checksum appended.
35 * String representing hex numbers.
36 * @return input string + CRC.
38 public static String appendCRC(String input) {
45 for (byte b : HexUtils.hexToBytes(input)) {
46 for (int i = 0; i < 8; i++) {
47 if (((b >> (7 - i) & 1) == 1) ^ ((check >> 15 & 1) == 1)) {
49 check = check ^ POLYNOMIAL;
56 check = check & CRC_INIT;
57 String checksum = StringUtils.leftPad(Integer.toHexString(check), 4, "0");
58 return (input + checksum).toUpperCase();
62 * Calculate the second checksum on the input string and return the
63 * input string with the checksum appended.
66 * String representing a nikobus command.
67 * @return input string + CRC.
69 public static String appendCRC2(String input) {
72 for (byte b : input.getBytes()) {
76 for (int i = 0; i < 8; i++) {
78 if (((check & 0xff) >> 7) != 0) {
88 return input + StringUtils.leftPad(Integer.toHexString(check), 2, "0").toUpperCase();