Settings rule variable to previousState


I have persistence setup and it’s working well. I’ve been able to persist data upon restarts.

Now I am trying to set the variables in rules to the previous state but it’s not working (or more likely I’m doing it wrong).

I have defined global vars in the default rules file.

I’ve tried to add

var Number door1 = Click_Counter_Door1.previousState().state

however the rule fails. I can get the Click_Counter_Door1.previousState().state and send it to another text label and it works.

What I am trying to do is increment the value in the previous state by one on each update event. The item is a string and I’ve tried to cast it as a number but haven’t had much luck.

Full rule is:

var Number door1 = 0
rule "Count Door"
   Item MQTTItem received update
   door1 = door1 + 1

Obviously this works fine and I can see the label in my sitemap update but when I restart OH the counter goes back to 0.

Any thoughts?

That’s exactly what you told it do

Every time the rules file is loaded (restarted) the global is set to zero.

Why don’t you just persist Click_Counter_Door1 , have it restore on startup, and not have any global variable at all.

Your rule only needs to add to existing state and then postupdate.

You might want to add a line that checks first if state is NULL (the very first run) and sets to zero.

Thats what I tried to do in the first part by setting the global var to the previous state. Because Click_Counter_Door1 is a string I am having trouble incrementing this value even with casting it to a Number or Integer.

You don’t need previousState. Restore on startup will do that for you automatically at system boot time, that’s what it is for.

Then make it a number type Item.
If you have trouble, post your rule code and the error message.

EDIT - I should add that changing the type of an existing Item (e.g. String to Number) can cause problems if it has already been persisted as one type. That might have something to do with your original difficulties, and might come around again. Try making a brand new Number Item, persist it, restore it, have your rule deal with NULL case for first time use.

1 Like