]> git.basschouten.com Git - openhab-addons.git/blob
397beebd5efb6eda7d98182fd2bd64380199645c
[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.homematic.internal.converter.type;
14
15 import java.math.BigDecimal;
16
17 import org.openhab.binding.homematic.internal.converter.ConverterException;
18 import org.openhab.binding.homematic.internal.model.HmDatapoint;
19 import org.openhab.core.library.types.DecimalType;
20 import org.openhab.core.types.Type;
21
22 /**
23  * Converts between a Homematic datapoint value and an openHAB DecimalType.
24  *
25  * @author Gerhard Riegler - Initial contribution
26  */
27 public class DecimalTypeConverter extends AbstractTypeConverter<DecimalType> {
28     @Override
29     protected boolean toBindingValidation(HmDatapoint dp, Class<? extends Type> typeClass) {
30         return dp.isNumberType() && typeClass.isAssignableFrom(DecimalType.class);
31     }
32
33     @Override
34     protected Object toBinding(DecimalType type, HmDatapoint dp) throws ConverterException {
35         if (dp.isIntegerType()) {
36             return type.intValue();
37         }
38         return round(type.doubleValue()).doubleValue();
39     }
40
41     @Override
42     protected boolean fromBindingValidation(HmDatapoint dp) {
43         return dp.isNumberType() && dp.getValue() instanceof Number;
44     }
45
46     @Override
47     protected DecimalType fromBinding(HmDatapoint dp) throws ConverterException {
48         Number number = ((Number) dp.getValue()).doubleValue();
49         if (dp.isIntegerType()) {
50             return new DecimalType(new BigDecimal(number.intValue()));
51         }
52         return new DecimalType(round(number.doubleValue()));
53     }
54 }