2 * Copyright (c) 2010-2022 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.dsmr.internal.device.cosem;
15 import java.text.ParseException;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.openhab.core.library.types.StringType;
21 * {@link CosemHexString} represents a string value stored as Hexadecimal values.
23 * @author M. Volaart - Initial contribution
24 * @author Hilbrand Bouwkamp - Class now a factory instead of data containing class
27 class CosemHexString extends CosemValueDescriptor<StringType> {
29 public static final CosemHexString INSTANCE = new CosemHexString();
31 private static final String NO_VALUE = "00";
34 * Parses a String representing the hex value to a {@link StringType}.
36 * @param cosemValue the value to parse
37 * @return {@link StringType} representing the value the cosem hex value
38 * @throws ParseException if parsing failed
41 protected StringType getStateValue(String cosemValue) throws ParseException {
42 final String cosemHexValue = cosemValue.replaceAll("\\r\\n", "").trim();
44 if (cosemHexValue.length() % 2 != 0) {
45 throw new ParseException(cosemHexValue + " is not a valid hexadecimal string", 0);
47 final StringBuilder sb = new StringBuilder();
49 for (int i = 0; i < cosemHexValue.length(); i += 2) {
50 final String hexValue = cosemHexValue.substring(i, i + 2);
52 if (!NO_VALUE.equals(hexValue)) {
54 sb.append((char) Integer.parseInt(hexValue, 16));
55 } catch (NumberFormatException e) {
56 throw new ParseException("Failed to parse hex value from '" + cosemValue + "' as char", i);
60 return new StringType(sb.toString());