I’m a little bit lost with with calculation of the difference between to numbers in a rule: I want to calculate the difference between the last and the actual counter of my smart meter. The item (SmartMeter_10180) is from type Number. I have the following rule:
var Number LetzterBezug
rule "Leistungmittel Stromzähler berechnen"
when
Item SmartMeter_10180 received update
then
logInfo ("Strom", "LetzterBezug: " + LetzterBezug)
var aktBezug = SmartMeter_10180.state as Number
var test = aktBezug - LetzterBezug
logInfo ("Strom", "aktBezug: " + aktBezug)
logInfo ("Strom", "div " + test)
LetzterBezug = aktBezug
end
But the result locks completly strange, one example from the log:
2022-11-01 18:47:47.977 [INFO ] [org.openhab.core.model.script.Strom ] - div 7560
For me, 1.86932157 - 186932136 = 21 and not 7560!? I assume a problem with the calculation based on numbers. I tried with int, but I have no idea how to convert. Could anybody explain what’s going wrong and help me in the right direction?
No it’s not, at least based on the events.log. It’s a Number:Power (I think). That means it’s carrying units of measurement (“Wh” in this case). You have to do math with numbers carrying units with other numbers carrying compatible units.
It’s not really clear what’s going on here, but see what happens if you do the following:
var aktBezug = SmartMeter_10180.state
We might need to change that line declaring LetzterBezung to var QuantityType<Power> LetzterBezug too but based on the logs I’m not sure.
First, it’s “Energy”, not “Power”. “Power” would be just W, not Wh.
That error is strange. It;'s not recognizing the subtraction as a subtraction at all. That implies that neither operand is something that Rule DSL recognizes as something that can be used in a subtraction.
You can try:
var test = aktBezug.subtract(LetzterBezug)
That might give it enough context to figure out what to do. If not, we’ll have to become explicit and cast the two.
OK, we need to tell it that the State we pulled from the Item is a QuantityType too.
var aktBezug = SmartMeter_10180.state as QuantityType<Energy>
There wasn’t enough context for it to figure that out. I bet it would have worked if we were subtracting from LetzterBezug. The order the variable appear greatly impact Rules DSL’s ability to guess and cast Objects on its own. It’s a real pain.
2022-11-01 20:54:22.098 [INFO ] [org.openhab.core.model.script.Strom ] - div 2.1999999980000000000000000000000001759999998400 Wh
Thanks for your support! No I can continue with the calcuation of the Power out the consumed energy… let’s see how I can use my new knowledge and when I need you’re support again