Trigger rule when a value passes a set limit

Hi.
Sorry for all the questions from me today, soon my OH3 will be running nice :slight_smile:

I want a rule that triggers when my light sensors reported level goes from a value below 20 to a value above 20. I thought the logical thing would be something like this:

Apparently it doesn’t work that way though… Anyone knows how to do this?

I would use the Item changed trigger without any Pervious State nor State setting and do the needed checks in the Action part (i.e the script)

Ok. That’s actually the way I’m doing it in my old .rules file, thought there maybe would be a nicer way to do it in the new rules engine :slight_smile:

You can do it in a scripted Action… or use a Condition (maybe two).

Use the “but only if” clause instead. That’s the skirt of thing it’s designed to handle. And you can set up the conditions in this case without code.

There is, the “but only if”, also known as a condition. The when clause can’t do anything more than the rule triggers you are used to. But the condition can check the state of Items and only execute the rule when certain conditions are meet, in this case, the current state of the item. To do the comparison to the previous state you will probably need to use a script condition as I don’t think the built in conditions work with the previous state.

1 Like

…and because of the need for a script condition I figured that doing it all in the when clause with one script would be virtually the same.

There are differences.

For one, both the script condition and the script action usually end up simpler as a result of the separation. But that’s just a small thing.

A bigger thing is that the rule never enters a running state if the conditionals fail whereas they will enter a running state if you put the conditions in the script action. Events like that can be logged to events.log (they appear to be turned off by default in OH 3), seen from MainUI, and I believe they can even be used as an event to trigger another rule (you’d have to hand code the trigger using the REST API I think for that one as the OSGI events are not exposed in the UI I think.

Another thing you can do is you can have rules that call other rules. When this happens you have the option to ignore the conditionals. If you put the if statements into the script action you can’t ignore them.

Finally, they are a damn good place to add error correcting code. For example, I used them on HestiaPi to revert certain Items to their old state if they were changed to an invalid state instead of running the actions.

Conditions are really much more powerful than just being a place to drop a bunch of if statements. I strongly advocate their use.

2 Likes