This is a simple rule that works with an accumulating sensor reading that can be reset unpredictably. For example, a sensor that keeps track of the total kWh used but resets back to zero when the sensor loses power.
The rule will add the delta from the previous reading to the current reading to the Item holding the total. However, when the sensor Item get’s reset the rule treats the current reading as the delta. Therefore this rule only works for an accumulating sensor where the reported reading is always increasing.
If the total Item is NULL or UNDEF, it’s initialized to 0 and the delta becomes the first value.
Managing the total Item (e.g. resetting it once a day, adding up the sum for the week or month, etc.) are not handled by this rule.
Today I seem to have run into a problem with the rule. It will probably be my setup, but I would like to understand it.
I have the regular energy item from the meter and the sum item that I write the sum into. For some reason my system crashed yesterday and I rebooted today. Now the total counter value was added at startup. So it looks like the counter was reset, which didn’t happen.
Value meter about 2150kWh
Value sum yesterday about 2150kWh
Value meter after reboot 2160kWh
Value sum after reboot 4310kWh
Both items are saved on every change in rrd4j and restore on startup is enabled.
If you happen to configure using openhabian, you may have ZRAM in use for your persistence services. In the event of an unexpected crash or power failure, persistence data since last controlled reboot may be lost forever. Restore-on-startup may then pull up data from long ago.
When can event.oldItemState be NULL/UNDEF? I think only at startup. I’m not sure if it makes sense to set lastReading to 0, because this might result in a big delta value. I would rather skip before getting a wrong delta. What is your opinion?
It’s up to the binding, rules, and anything else that updates the state of the Item. The Item is definitely NULL when OH first loads the Item. Some bindings will set an Item to UNDEF when it cannot communicate with the actual device.
The beauty of rule templates is if you want to tweak it or do something different, you can modify the code of the rule that was created from the template. You are not stuck with what’s here. You are able and encouraged to use this template as a starting point and update it as needed to meet your needs.
That’s what this basically does. If the Item state is NULL or UNDEF, the delta becomes 0 meaning the previous sum gets used. The total doesn’t suddenly drop to 0. In effect, the NULL/UNDEF is just ignored.