I’m trying to convert the hex number output of a battery pack to a number item using parseInt inside a rule. So far my attempts have been giving me persistent errors.
Heres the rule:
rule "Battery Level"
when Time cron "0/15 * * * * ?" //run every 15 seconds
then
var string = executeCommandLine("i2cget -y 1 0x62 0x4 b",10000)
logInfo("Hex",string)
var int value = Integer::parseInt(string)
logInfo("Test",value)
end
2020-10-17 20:28:25.282 [INFO ] [el.core.internal.ModelRepositoryImpl] - Validation issues found in configuration model ‘battery.rules’, using it anyway:
The use of wildcard imports is deprecated.
2020-10-17 20:28:25.371 [INFO ] [el.core.internal.ModelRepositoryImpl] - Refreshing model ‘battery.rules’
Why is it not working I going bald, I have tried also
//convert hex_code to Number type
var MyNumber = Integer.parseInt(hex_code, 16) as Number
//use the following for large_hex_code
var MyNumber1 = Long.parseLong(hex_code, 16) as Number
// coverting hex_code into DecimalType
var DecimalType parsedResult = DecimalType.valueOf(Long.parseLong(hex_code, 16).toString);
val itemvalue = new java.math.BigDecimal(Integer::parseInt(hex_code, 16))
I guess I don’t know or its not working or is broken.
Oh well try another approach
Install JS Transformation Pattern
Create File in transformation folder HEXtoDEC.JS
(function(i) {
if (i == 'NULL') { return i; }
if ((i == '-') || (i == 'UNDEF')) { return 'Undefined'; }
return (parseInt(i,16));
})(input)
Then use a transform in your rule
rule "Battery Level"
when Time cron "0/15 * * * * ?" //run every 15 seconds
then
var hex_code = executeCommandLine("i2cget -y 1 0x62 0x4 b",10000)
var value = transform("JS", "HEXtoDEC.js", hex_code)
logInfo("Hex",hex_code)
logInfo("Test",value)
end
The only little niggly issue remaining is that the value variable still appears to be a string so I’m unable to perform any mathematical operations on it.
I’ve tried using var int value and var Number value but no luck.
Ok so I think it was my item definition causing issues, the rule now returns a NumberItem.
Here’s the rule:
rule "Battery Level"
when Time cron "0/30 * * * * ?" //run every 30 seconds
then
var hex_code = executeCommandLine("i2cget -y 1 0x62 0x4 b",10000)
var value = transform("JS", "HEXtoDEC.JS", hex_code)
logInfo("Hex",hex_code)
logInfo("Test",value)
Battery.postUpdate(value)
logInfo("Battery", Battery.toString)
end
Item:
Number Battery "Battery Percentage [%s %%]" <batterylevel>