[smartmeter] Prevent NumberFormatException (#16183)

* Fix NumberFormatException
* Fix logger comment

---------

Signed-off-by: Leo Siepel <leosiepel@gmail.com>
Signed-off-by: Ciprian Pascu <contact@ciprianpascu.ro>
This commit is contained in:
lsiepel 2024-01-27 20:48:59 +01:00 committed by Ciprian Pascu
parent f730fb66d8
commit 62e67b4aa4
2 changed files with 20 additions and 1 deletions

View File

@ -17,6 +17,8 @@ import java.util.function.Function;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.smartmeter.internal.MeterValue; import org.openhab.binding.smartmeter.internal.MeterValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Handles the Negate Bit property for a specific meter value. * Handles the Negate Bit property for a specific meter value.
@ -26,6 +28,7 @@ import org.openhab.binding.smartmeter.internal.MeterValue;
*/ */
@NonNullByDefault @NonNullByDefault
public class NegateHandler { public class NegateHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(NegateHandler.class);
/** /**
* Gets whether negation should be applied for the given <code>negateProperty</code> and the {@link MeterValue} * Gets whether negation should be applied for the given <code>negateProperty</code> and the {@link MeterValue}
@ -64,7 +67,13 @@ public class NegateHandler {
* @return Whether the given bit is set or not * @return Whether the given bit is set or not
*/ */
public static boolean isNegateSet(String value, int negatePosition) { public static boolean isNegateSet(String value, int negatePosition) {
long longValue = Long.parseLong(value); long longValue = 0;
try {
longValue = (long) Double.parseDouble(value);
} catch (NumberFormatException e) {
LOGGER.warn("Failed to parse value: {} when determining isNegateSet, assuming false", value);
return false;
}
return (longValue & (1L << negatePosition)) != 0; return (longValue & (1L << negatePosition)) != 0;
} }
} }

View File

@ -46,6 +46,16 @@ public class TestNegateBit {
assertTrue(negateState); assertTrue(negateState);
} }
@Test
public void testNegateHandlingDecimalTrue() {
String negateProperty = "1-0_16-7-0:31:0";
boolean negateStateDot = NegateHandler.shouldNegateState(negateProperty,
obis -> new MeterValue<>(obis, "49.0", null));
assertTrue(negateStateDot);
}
@Test @Test
public void testNegateHandlingFalse() { public void testNegateHandlingFalse() {
String negateProperty = "1-0_1-8-0:5:1"; String negateProperty = "1-0_1-8-0:5:1";