Skip to content

Commit

Permalink
[smartmeter] Prevent NumberFormatException (openhab#16183)
Browse files Browse the repository at this point in the history
* Fix NumberFormatException
* Fix logger comment

---------

Signed-off-by: Leo Siepel <leosiepel@gmail.com>
Signed-off-by: René Ulbricht <rene_ulbricht@outlook.com>
  • Loading branch information
lsiepel authored and ulbi committed Jan 28, 2024
1 parent 39a1243 commit ca938ec
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
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.
Expand All @@ -26,6 +28,7 @@
*/
@NonNullByDefault
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}
Expand Down Expand Up @@ -64,7 +67,13 @@ public static boolean shouldNegateState(String negateProperty,
* @return Whether the given bit is set or not
*/
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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@ public void testNegateHandlingTrue() {
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
public void testNegateHandlingFalse() {
String negateProperty = "1-0_1-8-0:5:1";
Expand Down

0 comments on commit ca938ec

Please sign in to comment.