I am struggling with rules - and maybe I am simply not reading the right (parts) of the documentation. At startup I would like to sum up 2 item value into a new item:
I retrieve data from Stiebel Eltron LWZ403 using the Modbus Binding.
Item PWWSUMME1 is holding the energy created in kWh, eg 412
Item PWWSUMME2 is holding the energy created in MWh, eg 15
To get to the total of 15.412 kWh I want to multiply PWWSUMME2 by 1000 and add PWWSUMME1 followed by saving that new value into a virtual item PWWSUMME
rule “INIT”
when
System started
then
// Set WWALARM to off = 0
sendCommand(WWALARM, OFF)
// Calc PWWSUMME & PHEIZENSUMME
var num1 = PWWSUMME1.state
var num2 = PWWSUMME2.state
var num3 = (num2 * 1000 + num1)
PWWSUMME.state = num3
end
However, I receive the following error
Error during the execution of startup rule ‘INIT’: Unknown variable or command ‘*’; line 11, column 14, length 11
Help is being appreciated a lot If anyone knows really good tutorial for how to write code within rules, I would be really thankful. I can generally code (Java, Python, PHP, AngularJS,…) but need to get familiarized with the Syntax and commands I am allowed to use in OH2.4 rules (and honestly I did not find the official documentation too helpful).
I use * for multiply in rules. Upon checking, I note that the variables involved were all declared as Numbers (cos rules can be picky). Seems unlikely a clue is needed to interpret *, but it might be good practice anyway to declare var Number num1 = PWWSUMME1.state as Number
etc.
rule “INIT”
when
System started
then
// Set WWALARM to off = 0
WWALARM.sendCommand(OFF)
// Calc PWWSUMME & PHEIZENSUMME
var Number num1 = PWWSUMME1.state as Number
var Number num2 = PWWSUMME2.state as Number
var Number num3 = (num2 * 1000 + num1)
PWWSUMME.postUpdate(num3)
end
Well, it clearl did not work w/o the declaration and what I pasted I copied out of openhab.log - should be easy to reproduce - just create any rule and do what I did: no declaration just
var num1 = any number value
var num2 = any number value
var num3 = num1 * num2
Would be interesting to see your results. I am running on OH-2.4.0 (Docker).
The Rules parser is fickle and easily confused. I too would have expected the * to work, but in this case I think it is because we are using a DecimalType on both sides of the operator. DecimalType doesn’t directly implement .multiply and for whatever reason the Rules parser didn’t bother to check the parent classes/interfaces for a .multiply method and just gave up.
If one side were already cast to a Number, I bet it would have worked. And this is the more common use case as we are typically multiplying by a constant or something like that.
I know that I’ve been one of the defenders of the Rules DSL over the years, but I’m going to be so glad when we can use something else as the default.