OH3 python script - if condition not executed

I’m currently trying to get a simple python script working on OH3.
(Design Pattern: Cascading Timers - #5 by F1nn)

This code is working fine:

@rule("Start Irrigation at 08:00")
@when("Time cron 0 0 8 * * ?")
@when("Item Irrigation_Manual received command ON")
def start_irrigation(event):
    log.info("start_irrigation")
    if items["Irrigation_Auto"] == ON or items["Irrigation_Manual"] == ON:
        # Reset the gatekeeper 
        global gatekeeper
        if gatekeeper:
            gatekeeper.cancel_all()

        gatekeeper = Gatekeeper(start_irrigation.log)

       ....

This code doesn’t work:

@rule("Start Irrigation at 08:00")
@when("Time cron 0 0 8 * * ?")
@when("Item Irrigation_Manual received command ON")
def start_irrigation(event):
    if items["Irrigation_Auto"] == ON or items["Irrigation_Manual"] == ON:
        # Reset the gatekeeper 
        global gatekeeper
        if gatekeeper:
            gatekeeper.cancel_all()

        gatekeeper = Gatekeeper(start_irrigation.log)

       ....

It only goes beyond the IF condition when I add the log.info() before.
When I remove it, it doesn’t execute any code. Sometimes it does once but no more.

For reference, this tis the complete file (with lots of debug prints tho): from core.rules import rulefrom core.triggers import whenfrom core.utils imp - Pastebin.com

I don’t really understand why it is acting like that.

I just added an else to the if condition in the second example:

else:
    	log.info("not true")
    	log.info(ir.getItem("Irrigation_Auto").state)
    	log.info(ir.getItem("Irrigation_Manual").state)

Output:

2021-01-06 14:57:10.954 [INFO ] [jsr223.jython.irrigation            ] - not true
2021-01-06 14:57:10.957 [INFO ] [jsr223.jython.irrigation            ] - OFF
2021-01-06 14:57:10.960 [INFO ] [jsr223.jython.irrigation            ] - ON

I really don’t understand why it goes into the “else” part.
Doesn’t the state get evaluated correctly in the “if” statement?

UPDATE:
With both items being “ON”, it always works. With just _Manual being ON it only works in 10% of switching on cases. It seems like a really weird race-condition to me. What am I missing here?

Solution: [JSR223][Jython]What is the correct way to avoid a race condition getting an item value inside a /received update/ triggered rule? - #11 by leif

That’s something I didn’t expect from happening and cost me quite a lot of time to figure out.

There can be a delay between a item receiving the command and the same item changing the state. In a split second this can happen: item received command ON, rule executed (but state is not yet changed, so still OFF, so wont execute after the IF), item changed state to ON.

I don’t know the equivalent in python, but in the DSL rules I use receivedCommand instead of Irrigation_Manual.state .

1 Like

Yeah looks like getting the state from

event.itemState

is the way to go.