openhab / openhab-js

openHAB JavaScript Library for JavaScript Scripting Automation
https://www.openhab.org/addons/automation/jsscripting/
Eclipse Public License 2.0
38 stars 31 forks source link

[items] Persistence wrapper discards timestamps #226

Closed maniac103 closed 1 year ago

maniac103 commented 1 year ago

In one of my rules, I use PersistenceExtensions to grab a value with timestamp to fill 2 items with it:

var PersistenceExtensions = Java.type("org.openhab.core.persistence.extensions.PersistenceExtensions");
var ZonedDateTime = Java.type("java.time.ZonedDateTime");
var LocalTime = Java.type("java.time.LocalTime");
var windSpeedItem = items.getItem("GardenWindSensorGustSpeed").rawItem;
var maxToday = PersistenceExtensions.maximumSince(windSpeedItem, ZonedDateTime.now().with(LocalTime.MIDNIGHT));
if (maxToday) {
  items.getItem("GardenWindSensorVirtualWindSpeedMaxToday").postUpdate(maxToday.getState().toString());
  items.getItem("GardenWindSensorVirtualWindSpeedMaxTodayTime").postUpdate(time.ZonedDateTime.parse(maxToday.getTimestamp().toString()));
}

Since I need the timestamp, I can't use item.history. It would be great if the ItemHistory object could handle that situation, e.g. by returning an object containing both state and timestamp (the latter as ZonedDateTime), for all applicable calls:

That way, the above rule would become much shorter:

var midnight = time.toZDT().toStartOfDay(); // see #225 ;-)
var maxToday = items.getItem("GardenWindSensorGustSpeed").history.maximumSince(midnight);
if (maxToday) {
  items.getItem("GardenWindSensorVirtualWindSpeedMaxToday").postUpdate(maxToday.state);
  items.getItem("GardenWindSensorVirtualWindSpeedMaxTodayTime").postUpdate(maxToday.timestamp);
}
florian-h05 commented 1 year ago

Whilst this is a breaking change, I have nothing against it because I see the benefits of changing the ItemHistory class to also return a timestamp as well as we should return the string state where provided to return the value with its unit. The next release of the library already includes a breaking change, so let’s add on more!

Do you want to implement that yourself?

maniac103 commented 1 year ago

I can do it, but I'd appreciate guidance on how exactly the returned result should look like. Just an object with a string named state and a ZonedDateTime named timestamp?

florian-h05 commented 1 year ago

That’s exactly what I’d expect.

This object with those two properties would get returned for all PersistenceExtensions methods that return a HistoricItem, see https://www.openhab.org/javadoc/latest/org/openhab/core/persistence/extensions/persistenceextensions. Just keep in mind that all methods can return null, and convert the Java ZonedDateTime to its JS counterpart. Have a look at the utility functions at the bottom of the JS file.