]> git.basschouten.com Git - openhab-addons.git/blob
b6be16df14b4e66e368831315890cd37efbfa5c5
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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 org.openhab.binding.homematic.internal.converter.ConverterException;
16 import org.openhab.binding.homematic.internal.model.HmDatapoint;
17 import org.openhab.binding.homematic.internal.model.HmDatapointInfo;
18 import org.openhab.core.library.types.StringType;
19 import org.openhab.core.types.Type;
20
21 /**
22  * Converts between a Homematic datapoint value and an openHAB StringType.
23  *
24  * @author Gerhard Riegler - Initial contribution
25  */
26 public class StringTypeConverter extends AbstractTypeConverter<StringType> {
27     @Override
28     protected boolean toBindingValidation(HmDatapoint dp, Class<? extends Type> typeClass) {
29         return (dp.isStringType() || dp.isEnumType()) && typeClass.isAssignableFrom(StringType.class);
30     }
31
32     @Override
33     protected Object toBinding(StringType type, HmDatapoint dp) throws ConverterException {
34         if (dp.isStringType()) {
35             return type.toString();
36         } else {
37             int idx = dp.getOptionIndex(type.toString());
38             if (idx == -1) {
39                 throw new ConverterException(String.format("Option value '%s' not found in datapoint '%s'",
40                         type.toString(), new HmDatapointInfo(dp)));
41             }
42             return idx;
43         }
44     }
45
46     @Override
47     protected boolean fromBindingValidation(HmDatapoint dp) {
48         return (dp.isStringType()) || (dp.isEnumType() && dp.getValue() instanceof Number);
49     }
50
51     @Override
52     protected StringType fromBinding(HmDatapoint dp) throws ConverterException {
53         if (dp.isStringType()) {
54             return new StringType(String.valueOf(dp.getValue()));
55         } else {
56             String value = dp.getOptionValue();
57             if (value == null) {
58                 throw new ConverterException(String.format("Option for value '%s' not found in datapoint '%s'",
59                         dp.getValue(), new HmDatapointInfo(dp)));
60             }
61             return new StringType(value);
62         }
63     }
64 }