Problems with simple calcuation

Hi all

I’m struggling again with some simple rules. For this example, I’m working with integer numbers only.

I have the following defined at the top of my rules file

var Number m_main_missing
var Number m_main_wanted

In the item file I have

Number watering_main_today “Time running [%d]” (gWatering)

Now I want to simply calculate the vlaue for m_main_missing, I’m trying

m_main_missing = (m_main_wanted-(watering_main_today.state as Number))

But this gives me the following error:

Error during the execution of rule water Calculate time wanted: java.lang.Number

I still don’t really get the whole casting of int, Integer, DecimalType, and and…

Thanks for any clearifications :wink:

Try this one:

if(watering_main_today.state instanceof DecimalType) {
    m_main_missing = m_main_wanted - (watering_main_today.state as DecimalType).intValue
}

Of course, m_main_wanted has to be a valid Integer, too. :wink:

If I try it like that, m_main_missing is “null”.

Inserted a logInfo inside the if that is never executed. :thinking:

So…
What is the log of

logInfo ("w_Calculate_time","watering_main_today: {}",watering_main_today.state)

?

Ah, that’s the right question! :grinning:

Turns out, it’s

2017-07-29 17:29:00.017 [INFO ] [rthome.model.script.w_Calculate_time] - watering_main_today: NULL

So I had to insert the following at the beginning of the rule

if(watering_main_today.state == NULL) watering_main_today.postUpdate(0);

Thanks a lot for the quick help!

One question: Why the if instanceof DecimalType ? If I defined the Item as Number, can I not assume that it’s always a DecimalType? Or is the check exactly for NULL values ?

Afaik Number is parent of Decimal, and you can cast every valid Number to DecimalType.

Please keep in mind, that unlike jva you don’t need to use a ; at the and of line.
openHAB rules engine uses a DSL based on xtend, so there might be similarities but also differences to java.

Thanks for the explanation. A sure, don’t know how the ; slipped in there. Old habits I guess :roll_eyes:habits