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.smartmeter.internal.conformity.negate;
15 import java.util.function.Function;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.openhab.binding.smartmeter.internal.MeterValue;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
24 * Handles the Negate Bit property for a specific meter value.
26 * @author Matthias Steigenberger - Initial contribution
30 public class NegateHandler {
31 private static final Logger LOGGER = LoggerFactory.getLogger(NegateHandler.class);
34 * Gets whether negation should be applied for the given <code>negateProperty</code> and the {@link MeterValue}
35 * provided by the <code>getObisValueFunction</code>
37 * @param negateProperty The negate property (in form {@code <OBIS>:<POSITION>:<BIT_SET>})
38 * @param getObisValueFunction The function to get the {@link MeterValue} from an OBIS code.
39 * @return whether to negate or not.
41 public static boolean shouldNegateState(String negateProperty,
42 Function<String, @Nullable MeterValue<?>> getObisValueFunction) {
43 NegateBitModel negateModel = NegateBitParser.parseNegateProperty(negateProperty);
44 MeterValue<?> value = getObisValueFunction.apply(negateModel.getNegateChannelId());
45 boolean isStatus = negateModel.isStatus();
47 String status = value.getStatus();
49 if (isStatus && status != null) {
52 stringValue = value.getValue();
54 boolean negateBit = isNegateSet(stringValue, negateModel.getNegatePosition());
56 return negateBit == negateModel.isNegateBit();
63 * Gets whether the bit at position <code>negatePosition</code> is set or not.
65 * @param value The value which must be a number to check the bit
66 * @param negatePosition The position to check
67 * @return Whether the given bit is set or not
69 public static boolean isNegateSet(String value, int negatePosition) {
72 longValue = (long) Double.parseDouble(value);
73 } catch (NumberFormatException e) {
74 LOGGER.warn("Failed to parse value: {} when determining isNegateSet, assuming false", value);
77 return (longValue & (1L << negatePosition)) != 0;