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.proteusecometer.internal.ecometers;
15 import java.util.Optional;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.openhab.core.util.HexUtils;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
23 * Parse the bytes from the device
25 * @author Matthias Herrmann - Initial contribution
29 class ProteusEcoMeterSParser {
31 private final Logger logger = LoggerFactory.getLogger(ProteusEcoMeterSParser.class);
34 * @param bytes Raw bytes send from the device
35 * @return A structured version of the bytes, if possible
37 public Optional<ProteusEcoMeterSReply> parseFromBytes(final byte[] bytes) {
38 return Optional.ofNullable(bytes).flatMap(b -> {
39 final String hexString = HexUtils.bytesToHex(b);
40 logger.trace("Received hex string: {}", hexString);
42 if (hexString.length() < 4) {
43 return Optional.empty();
45 final String marker = hexString.substring(0, 4);
46 if (!"5349".equals(marker)) {
47 logger.trace("Marker is not {} but {}", "5349", marker);
48 return Optional.empty();
49 } else if (hexString.length() < 40) {
50 logger.trace("hexString is of length {}, expected >= 40", hexString.length());
51 return Optional.empty();
55 .of(new ProteusEcoMeterSReply(parseInt(hexString.substring(26, 28), "tempInFahrenheit"),
56 parseInt(hexString.substring(28, 32), "sensorLevelInCm"),
57 parseInt(hexString.substring(32, 36), "usableLevelInLiter"),
58 parseInt(hexString.substring(36, 40), "totalCapacityInLiter")));
59 } catch (final NumberFormatException e) {
60 logger.debug("Error while parsing numbers", e);
61 return Optional.empty();
68 private Integer parseInt(final String toParse, final String fieldName) throws NumberFormatException {
70 return Integer.parseInt(toParse, 16);
71 } catch (final NumberFormatException e) {
72 logger.trace("Unable to parse field {}", fieldName, e);