]> git.basschouten.com Git - openhab-addons.git/blob
27a98bc825aa8656fdcba30809d89ca720386242
[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.dsmr.internal.device.cosem;
14
15 import java.text.ParseException;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.openhab.core.library.types.StringType;
19
20 /**
21  * {@link CosemHexString} represents a string value stored as Hexadecimal values.
22  *
23  * @author M. Volaart - Initial contribution
24  * @author Hilbrand Bouwkamp - Class now a factory instead of data containing class
25  */
26 @NonNullByDefault
27 class CosemHexString extends CosemValueDescriptor<StringType> {
28
29     public static final CosemHexString INSTANCE = new CosemHexString();
30
31     private static final String NO_VALUE = "00";
32
33     /**
34      * Parses a String representing the hex value to a {@link StringType}.
35      *
36      * @param cosemValue the value to parse
37      * @return {@link StringType} representing the value the cosem hex value
38      * @throws ParseException if parsing failed
39      */
40     @Override
41     protected StringType getStateValue(String cosemValue) throws ParseException {
42         final String cosemHexValue = cosemValue.replaceAll("\\r\\n", "").trim();
43
44         if (cosemHexValue.length() % 2 != 0) {
45             throw new ParseException(cosemHexValue + " is not a valid hexadecimal string", 0);
46         } else {
47             final StringBuilder sb = new StringBuilder();
48
49             for (int i = 0; i < cosemHexValue.length(); i += 2) {
50                 final String hexValue = cosemHexValue.substring(i, i + 2);
51
52                 if (!NO_VALUE.equals(hexValue)) {
53                     try {
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);
57                     }
58                 }
59             }
60             return new StringType(sb.toString());
61         }
62     }
63 }