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