]> git.basschouten.com Git - openhab-addons.git/blob
0ba18391d7a90771d11db7a091306b7ee7e7dd16
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.smartmeter.internal.conformity.negate;
14
15 import java.util.function.Function;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.openhab.binding.smartmeter.internal.MeterValue;
20
21 /**
22  * Handles the Negate Bit property for a specific meter value.
23  *
24  * @author Matthias Steigenberger - Initial contribution
25  *
26  */
27 @NonNullByDefault
28 public class NegateHandler {
29
30     /**
31      * Gets whether negation should be applied for the given <code>negateProperty</code> and the {@link MeterValue}
32      * provided by the <code>getObisValueFunction</code>
33      *
34      * @param negateProperty The negate property (in form {@code <OBIS>:<POSITION>:<BIT_SET>})
35      * @param getObisValueFunction The function to get the {@link MeterValue} from an OBIS code.
36      * @return whether to negate or not.
37      */
38     public static boolean shouldNegateState(String negateProperty,
39             Function<String, @Nullable MeterValue<?>> getObisValueFunction) {
40         NegateBitModel negateModel = NegateBitParser.parseNegateProperty(negateProperty);
41         MeterValue<?> value = getObisValueFunction.apply(negateModel.getNegateChannelId());
42         boolean isStatus = negateModel.isStatus();
43         if (value != null) {
44             String status = value.getStatus();
45             String stringValue;
46             if (isStatus && status != null) {
47                 stringValue = status;
48             } else {
49                 stringValue = value.getValue();
50             }
51             boolean negateBit = isNegateSet(stringValue, negateModel.getNegatePosition());
52
53             return negateBit == negateModel.isNegateBit();
54         } else {
55             return false;
56         }
57     }
58
59     /**
60      * Gets whether the bit at position <code>negatePosition</code> is set or not.
61      *
62      * @param value The value which must be a number to check the bit
63      * @param negatePosition The position to check
64      * @return Whether the given bit is set or not
65      */
66     public static boolean isNegateSet(String value, int negatePosition) {
67         long longValue = Long.parseLong(value);
68         return (longValue & (1L << negatePosition)) != 0;
69     }
70 }