2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.ihc.internal.converters;
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;
22 * OnOffType <-> WSIntegerValue converter.
24 * @author Pauli Anttila - Initial contribution
26 public class OnOffTypeWSIntegerValueConverter implements Converter<WSIntegerValue, OnOffType> {
29 public OnOffType convertFromResourceValue(@NonNull WSIntegerValue from,
30 @NonNull ConverterAdditionalInfo convertData) throws ConversionException {
31 return from.value > 0 ^ convertData.getInverted() ? OnOffType.ON : OnOffType.OFF;
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;
40 if (convertData.getInverted()) {
41 newVal = newVal == value.maximumValue ? value.minimumValue : value.maximumValue;
43 if (newVal >= value.minimumValue && newVal <= value.maximumValue) {
44 return new WSIntegerValue(value.resourceID, newVal, value.minimumValue, value.maximumValue);
46 throw new ConversionException("Value is not between acceptable limits (min=" + value.minimumValue + ", max="
47 + value.maximumValue + ")");
51 private int getCommandLevel(@NonNull WSIntegerValue value, @NonNull ConverterAdditionalInfo convertData,
52 Command command) throws ConversionException {
54 if (convertData.getCommandLevels() != null) {
55 return (int) convertData.getCommandLevels().get(command);
57 return value.maximumValue;
58 } catch (RuntimeException e) {
59 throw new ConversionException(e);