Search code examples
openhab

How to write an openHAB rule which increments a number?


I want to write a Rule in openHAB2, which increments a counter of all group items. The items:

Group counters
Number cnt1 (counters)
Number cnt2 (counters)

My try of a rule:

rule "Increase value .1 per minute"
when 
    Time cron "0 * * * * ?" or
    System started
then
    // Initialize. Necessary?
    counters?.members.forEach(counter|
        postUpdate(counter, 0.0)
    )
    counters?.members.forEach(counter|
        postUpdate(counter, 0.1 + counter.state)
    }
end

But that does not work. Exception: Error during the execution of startup rule 'Increase value .1 per minute': Could not invoke method: org.eclipse.xtext.xbase.lib.DoubleExtensions.operator_plus(double,byte) on instance: null

I tried to explore the type of counter.state, and with logInfo(counter.state.class) it correctly logs ...DecimalType.


Solution

  • it seems the implicit type casting doesn't seem to work. If you'd change the rule to something like:

    rule "Increase value .1 per minute"
    when 
        Time cron "0 * * * * ?" or
        System started
    then
        // Initialize. Necessary?
        counters?.members.forEach(counter|
            if (counter.state == null) {
                postUpdate(counter, 0.0)
            }
        )
        counters?.members.forEach(counter|
            postUpdate(counter, 0.1 + (counter.state as DecimalType))
        }
    end
    

    it should work. Hope this helps,

    Thomas E.-E.