Code review for rules; checking state after 30s

The easy thing first. Livingroom_Lights is an Item you created manually, either through PaperUI or .items files. zwave_device_fccca473_node11_sensor_door is an Item that was automatically created because Simple Mode is either enabled or was enabled at some point in the past. You’ll have to disable Simple Mode, delete that Item and recreate it and link it to the right Channel on the Zwave Thing. You cannot change the name of Simple Mode created Items as far as I am aware.

Some ideas, some minor some major:

  • The rule is triggered with changed so there is a newState and previousState pair of implicit variables. You can change all the zwave_device_fccca473_node11_sensor_door.state with newState.

  • The rule only cares about the door opening, so trigger only when it changes to OPEN, changed to OPEN and you don’t need to check if the door is OPEN in the rule at all.

  • As rossko57 points out, what if the door is closed and then opened again within the 30 seconds of the timer? Let’s consider the following:

0 secs: door opens
0 secs: telegram message “Patio door opened”
20 secs: door closes
25 secs: door opens again
25 secs: telegram message “Patio door opened”
30 seconds: telegram message “Patio door is still open!”
55 secs: telegram message “Patio door is still open!”

Obviously that isn’t what is intended. What you would want is

0 secs: door opens
0 secs: telegram message “Patio door opened”
20 secs: door closes
25 secs: door opens again
25 secs: telegram message “Patio door opened”
55 secs: telegram message “Patio door is still open!”

To achieve this behavior, you need to cancel the old timer when the door closes. Make sure to set the Timer to null after cancelling it. See Design Pattern: Motion Sensor Timer for examples.

  • Since the previous bullet makes you need to care about CLOSED you have two options. Create another Rule that triggers on changed to CLOSED or keep the if statement and add an else to the one existing Rule.

  • I’ve become pretty big on meaningful error messages lately. Add an else to the check to make sure actions !== null and log an error. As written it will fail silently at first and then with an arcane error later when the Timer runs.

  • Let’s assume that you don’t want to cancel the Timer when the door opens and closes and opens again within the 30 seconds. In that case, add an else to the timer === null case to reschedule the timer. That would be an equally viable approach to the cancel approach.

  • In your new version of the code, the cancelling of the timer can be reduced to

timer?.cancel
timer = null
1 Like