]> git.basschouten.com Git - openhab-addons.git/blob
4bed06b0c0c4547e7dd41532f122a65140bff2d9
[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.ihc.internal.converters;
14
15 import org.eclipse.jdt.annotation.NonNull;
16 import org.openhab.binding.ihc.internal.ws.exeptions.ConversionException;
17 import org.openhab.binding.ihc.internal.ws.resourcevalues.WSIntegerValue;
18 import org.openhab.core.library.types.OnOffType;
19 import org.openhab.core.types.Command;
20
21 /**
22  * OnOffType <-> WSIntegerValue converter.
23  *
24  * @author Pauli Anttila - Initial contribution
25  */
26 public class OnOffTypeWSIntegerValueConverter implements Converter<WSIntegerValue, OnOffType> {
27
28     @Override
29     public OnOffType convertFromResourceValue(@NonNull WSIntegerValue from,
30             @NonNull ConverterAdditionalInfo convertData) throws ConversionException {
31         return from.value > 0 ^ convertData.getInverted() ? OnOffType.ON : OnOffType.OFF;
32     }
33
34     @Override
35     public WSIntegerValue convertFromOHType(@NonNull OnOffType from, @NonNull WSIntegerValue value,
36             @NonNull ConverterAdditionalInfo convertData) throws ConversionException {
37         int onLevel = Math.min(value.maximumValue, getCommandLevel(value, convertData, OnOffType.ON));
38         int newVal = from == OnOffType.ON ? onLevel : value.minimumValue;
39
40         if (convertData.getInverted()) {
41             newVal = newVal == value.maximumValue ? value.minimumValue : value.maximumValue;
42         }
43         if (newVal >= value.minimumValue && newVal <= value.maximumValue) {
44             return new WSIntegerValue(value.resourceID, newVal, value.minimumValue, value.maximumValue);
45         } else {
46             throw new ConversionException("Value is not between acceptable limits (min=" + value.minimumValue + ", max="
47                     + value.maximumValue + ")");
48         }
49     }
50
51     private int getCommandLevel(@NonNull WSIntegerValue value, @NonNull ConverterAdditionalInfo convertData,
52             Command command) throws ConversionException {
53         try {
54             if (convertData.getCommandLevels() != null) {
55                 return (int) convertData.getCommandLevels().get(command);
56             }
57             return value.maximumValue;
58         } catch (RuntimeException e) {
59             throw new ConversionException(e);
60         }
61     }
62 }