]> git.basschouten.com Git - openhab-addons.git/blob
e8340fd29e40686a65de6422c6c60d471a67ec56
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.regoheatpump.internal.rego6xx;
14
15 import org.openhab.core.util.HexUtils;
16
17 /**
18  * The {@link AbstractResponseParser} is responsible for parsing responses coming from
19  * rego6xx controllers.
20  *
21  * @author Boris Krivonog - Initial contribution
22  */
23 abstract class AbstractResponseParser<T> implements ResponseParser<T> {
24     private static final byte COMPUTER_ADDRESS = (byte) 0x01;
25
26     @Override
27     public abstract int responseLength();
28
29     protected abstract T convert(byte[] responseBytes);
30
31     @Override
32     public T parse(byte[] buffer) throws Rego6xxProtocolException {
33         if (buffer.length != responseLength()) {
34             throw new Rego6xxProtocolException(
35                     "Expected size does not match: " + buffer.length + " != " + responseLength());
36         }
37
38         if (buffer[0] != COMPUTER_ADDRESS) {
39             throw new Rego6xxProtocolException("Invalid header " + HexUtils.bytesToHex(buffer));
40         }
41
42         if (responseLength() > 1
43                 && Checksum.calculate(buffer, 1, responseLength() - 2) != buffer[responseLength() - 1]) {
44             throw new Rego6xxProtocolException("Invalid crc - " + HexUtils.bytesToHex(buffer));
45         }
46
47         return convert(buffer);
48     }
49 }