The way you would work around that in the .persist file would be to do away with the default and configure these Items independently so they only save on updates and not changes. If you save on both you will get two entries because an update and a change are two separate events and you’ve configured both to be saved.
I don’t think it’s because the Item is configured twice in the file.
This has the potential to be a pain though so if it’s just a couple of Items a rule might be the way to go. But that’s going to be a pain there too so it might be worth while fixing this in the persistence config in the end. See Design Pattern: Group Based Persistence for one way to make this easier.
Yes, because the ItemStateChangedEvent is a different event and a different rule trigger. The variables stored in the event
Object (or implicit variables in Rules DSL) are dictated by the rule trigger. You are not triggering the rule with an ItemStateChangedEvent so the rule never sees anything associated with that change. It only sees the updates.
Not really. You’ll have to get the previous state in other ways. Luckily you have a couple options:
- pull it from persistence, though timing might become an issue
- store the old value in the cache each time the rule triggers.
This last approach would look something like this:
var previousState = cache.private.get("prev", () => event.itemState);
if(event.itemState == previousState) {
items[event.itemName].history.persist();
}
cache.private.put("prev", event.itemState);
This script is pretty simple and it makes sense to keep it all in the script action. But if it were more complicated, you could split the test into the script condition.
Script Condition
var previousState = cache.private.get("prev", () => event.itemState);
var isUnchanged = (event.itemState == previousState);
cache.private.put("prev", event.itemState);
isUnchanged;
And then the Script Action becomes
items[event.itemName].history.persist();
It doesn’t really make anything better here, but for more complicated rules it can cause a lot of simplification of the code.
However, given the overhead of running a rule, if this Item updates a whole lot you might need to go back to the persistence configuration approach. Just make sure these Items are only stored on updates, not updates and changes.