]> git.basschouten.com Git - openhab-addons.git/blob
4b6848c46a3c81ee1dd238be7ca2432751689c26
[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.DecimalType;
19
20 /**
21  * CosemInteger represents a decimal value
22  *
23  * @author M. Volaart - Initial contribution
24  * @author Hilbrand Bouwkamp - Combined Integer and Double because {@link DecimalType} handles both
25  */
26 @NonNullByDefault
27 class CosemDecimal extends CosemValueDescriptor<DecimalType> {
28
29     public static final CosemDecimal INSTANCE = new CosemDecimal(false);
30     public static final CosemDecimal INSTANCE_WITH_UNITS = new CosemDecimal(true);
31
32     /**
33      * If true it can be the input contains a unit. In that case the unit will be stripped before parsing.
34      */
35     private final boolean expectUnit;
36
37     private CosemDecimal(boolean expectUnit) {
38         this.expectUnit = expectUnit;
39     }
40
41     public CosemDecimal(String ohChannelId) {
42         super(ohChannelId);
43         this.expectUnit = false;
44     }
45
46     /**
47      * Parses a String value (that represents a decimal) to a {@link DecimalType} object.
48      *
49      * @param cosemValue the value to parse
50      * @return {@link DecimalType} representing the value of the cosem value
51      * @throws ParseException if parsing failed
52      */
53     @Override
54     protected DecimalType getStateValue(String cosemValue) throws ParseException {
55         try {
56             final String value;
57
58             if (expectUnit) {
59                 final int sep = cosemValue.indexOf('*');
60                 value = sep > 0 ? cosemValue.substring(0, sep) : cosemValue;
61             } else {
62                 value = cosemValue;
63             }
64             return new DecimalType(value);
65         } catch (NumberFormatException nfe) {
66             throw new ParseException("Failed to parse value '" + cosemValue + "' as integer", 0);
67         }
68     }
69 }