- Platform information:
- Hardware: Raspberry Pi 4
- OS: Raspbian Bullseye 11.8
- Java Runtime Environment: OpenJDK (build 17.0.7+7-Raspbian-1deb11u1rpt1)
- openHAB version: 4.1.0.M2
Context:
I have default persistence configuration in SQL database for every item on every change. But for few items I would like to store values also when the item’s value is updated (e.g. for Water meter flow rate or Rain rate)
If I extend the persistence configuration for those items then I get those item’s values stored twice (one for default strategy, second for particular item strategy). And also I get stored zero values for most of the time
So I wanted to write simple javascript rule which executes everytime the item is updated and check if the old and new values are the same and if yes then persist the item value manually.
My current simple test rule:
configuration: {}
triggers:
- id: "3"
configuration:
itemName: TestNumberItem
type: core.ItemStateUpdateTrigger
conditions: []
actions:
- inputs: {}
id: "2"
configuration:
type: application/javascript
script: >
console.log("Persist unchanged values rule: eventType = %s, oldItemState
= %s, itemState = %s", event.type, event.oldItemState,
event.itemState);
if (event.oldItemState && event.oldItemState == event.itemState && Float.parseFloat(event.itemState) > 0) {
items.getItem(event.itemName).history.persist();
}
type: script.ScriptAction
Console output:
Persist unchanged values rule: eventType = ItemStateUpdatedEvent, oldItemState = undefined, itemState = 0
Persist unchanged values rule: eventType = ItemStateUpdatedEvent, oldItemState = undefined, itemState = 2.4
With this rule the event is always of type ItemStateUpdatedEvent no matter if the state has changed or is still the same. And as it is stated in the documentation the event.oldItemState is only available when item’s value has changed.
Is there any other way how to check the previous value in ItemStateUpdateTrigger event? Or could be the event object extended with this oldItemState state also for this type of trigger?