Hey guys,
I hope I am posting this in the right place. The members of this forum have taught me so much over the years and so I want to give back in a small way by posting this thread.
Recently I had the need to count how many times something happened and was looking for a way to do it via rules.
In my case I have a rule that sends me a notification in certain cases but wanted to limit the number it was sending throughout the day. This could be used for a variety of other purposes though.
I started off by making the dummy item I will use to do the counting:
Dimmer CounterItem //counts the number of times something happens
Then I made a rule to do the counting:
EDIT: Changes incorporated from post by Rossko57 below.
rule "Counting Rule"
when
//something happens
//Item is updated.
//etc.
then
var addone = 1 // first count if needed
if (CounterItem.state instanceof DecimalType) {
addone = ((CounterItem.state as DecimalType).intValue + 1)
}
postUpdate(CounterItem,addone)
logInfo("counting", "CounterItem set to: " + addone) //per comment from Rossko57 below, don't use 'CounterItem.state.toString' here because the item state probably wont update by the time this rule runs.
end
If the initial state of CounterItem is 0, this rule will change it to 1. The next time the rule runs, it will change it to 2 and so on. For fun, you can make a switch item and set the rule to run when that switch item is updated. Keep flipping the switch while watching the logs and youll see the number grow every time.
To implement this into another rule you can simply use something like the below statement in another rule. In my case this limited the number of notifications:
if(CounterItem.state < 3) {
//do stuff
//send notification
//etc.
}
else { //don't do stuff
logInfo("home.rules", "notification not sent because 3 have already been sent today.")
}
Finally I have another rule reset the state of CounterItem to 0 after I want the counting period to be over. for me its at 12:01 am every day.
rule "Counting reset"
when
Time cron "0 1 0 1/1 * ? *" //12:01am everyday
then
logInfo("home.rules", "CounterItem reset to 0")
CounterItem.postUpdate(0)
end
Hope this helps someone out there!
JM