OH3: persistence maximumSince produces error

  • OH 3.4.3 on rPi4 with 4GB

Running this rule:

rule "trial"
    when
        Time cron "5 0/1 8 ? * *   *"
    then
        val RULE_ID = 01

        val AVERAGE_EXPORT_RECENT_DAYS = 2
        val RECENT_AVERAGE_EXPORT = (spp_Export.averageSince(now().minusDays(AVERAGE_EXPORT_RECENT_DAYS)) as Number) + 0
        val EXPORT_YESTERDAY      = (spp_Export.maximumSince(now().minusDays(1)) as Number) + 0

        logInfo(LOG_PREFIX + RULE_ID + ".01",
            "RECENT_AVERAGE_EXPORT = {}", RECENT_AVERAGE_EXPORT)

        logInfo(LOG_PREFIX + RULE_ID + ".02",
            "EXPORT_YESTERDAY = {}", EXPORT_YESTERDAY)
end

… creates this error:

2024-08-14 08:50:05.349 [ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID 'test-1' failed: Could not cast 8/12/24, 8:51 AM: spp_Export -> 24.547 to java.lang.Number; line 14, column 38, length 78 in test

… which is unclear to me as to why I get the error.

Basically averageSince() works, maximumSince() doesn’t.

Any hints appreciated.

Why the + 0?

It’s complaining about line 14. Which line is 14 in this .rules file?

Pay close attention to what each persisitence extension action returns. From the docs averageSince returns

Gets the average value of the State of a persisted Item since a certain point in time.

So we can expect that method (and any method that returns the result of a calculation across multiple values) to return a Number.

However, maximumSince returns\

Gets the maximum value of the State of a persisted Item since a certain point in time (returns HistoricItem)

This is not a number. It’s a date time and a number combined in a HistoricItem Object. You can’t do math with a HistoricItem but you can do math with it’s state property. And you can find out when the Item was at that state from the timestamp property.

(spp_Export.maximumSince(now().minusDays(1)).state as Number) + 0
1 Like

It was a brain fart I had once upon a time…

The one you’ve identified :slight_smile:

val EXPORT_YESTERDAY      = (spp_Export.maximumSince(now().minusDays(1)) as Number) + 0

Well, spotted… I have to admit, despite having read the persistence doc, it remained oblivious to me that, as you said, a HistoricItem is … an object I can’t do math with.

(spp_Export.maximumSince(now().minusDays(1)).state as Number)

… is the solution. Thank you!

2024-08-14 22:54:05.349 [INFO ] [.openhab.core.model.script.test.1.01] - RECENT_AVERAGE_EXPORT = 1.693403489396487
2024-08-14 22:54:05.351 [INFO ] [.openhab.core.model.script.test.1.02] - EXPORT_YESTERDAY = 0.002

… and yes, the values are shocking, as it has been raining , with next literally zero export.