2 * Copyright (c) 2010-2024 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.enocean.internal.eep;
15 import javax.measure.Unit;
16 import javax.measure.quantity.Energy;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.binding.enocean.internal.config.EnOceanChannelTotalusageConfig;
21 import org.openhab.core.config.core.Configuration;
22 import org.openhab.core.library.types.QuantityType;
23 import org.openhab.core.library.unit.Units;
24 import org.openhab.core.types.State;
25 import org.openhab.core.types.UnDefType;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
31 * @author Dominik Vorreiter - initial contribution
35 public abstract class EEPHelper {
36 private static final Logger logger = LoggerFactory.getLogger(EEPHelper.class);
38 public static State validateTotalUsage(State value, @Nullable State currentState, Configuration config) {
39 EnOceanChannelTotalusageConfig c = config.as(EnOceanChannelTotalusageConfig.class);
41 if (c.validateValue && (value instanceof QuantityType) && (currentState instanceof QuantityType)) {
42 @SuppressWarnings("unchecked")
43 QuantityType<Energy> newValue = value.as(QuantityType.class);
45 if (newValue != null) {
46 newValue = newValue.toUnit(Units.KILOWATT_HOUR);
49 @SuppressWarnings("unchecked")
50 QuantityType<Energy> oldValue = currentState.as(QuantityType.class);
52 if (oldValue != null) {
53 oldValue = oldValue.toUnit(Units.KILOWATT_HOUR);
56 if ((newValue != null) && (oldValue != null)) {
57 if (newValue.compareTo(oldValue) < 0) {
58 if ((oldValue.subtract(newValue).doubleValue() < 1.0)) {
59 return UnDefType.UNDEF;
62 if (newValue.subtract(oldValue).doubleValue() > 10.0) {
63 return UnDefType.UNDEF;
72 public static boolean validateUnscaledValue(int unscaledValue, double unscaledMin, double unscaledMax) {
73 if (unscaledValue < unscaledMin) {
74 logger.debug("Unscaled value ({}) lower than the minimum allowed ({})", unscaledValue, unscaledMin);
76 } else if (unscaledValue > unscaledMax) {
77 logger.debug("Unscaled value ({}) bigger than the maximum allowed ({})", unscaledValue, unscaledMax);
84 public static State calculateState(int unscaledValue, double scaledMin, double scaledMax, double unscaledMin,
85 double unscaledMax, Unit<?> unit) {
86 if (!validateUnscaledValue(unscaledValue, unscaledMin, unscaledMax)) {
87 return UnDefType.UNDEF;
90 double scaledValue = scaledMin + ((unscaledValue * (scaledMax - scaledMin)) / (unscaledMax - unscaledMin));
91 return new QuantityType<>(scaledValue, unit);