openHAB: timestamp from last Item update

Posted by ads' corner on Thursday, 2021-01-28
Posted in [Openhab]

If openHAB has a Persistence service configured, the time of the last Item update (and a couple other times) is available in Rules. This makes it quite handy to check if a certain item hasn’t been updated in a long time. As example I have the Tankerkoenig Binding installed, and this data is persisted in InfluxDB. This way I can see historic gas prices in Grafana.

When the Telegram Bot answers the /tanken question, it appends the timestamp of the last gas prices update.

In this case I might have different update timestamps from different stations, because the result returns the top N prices. I just pick the last price here.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
    if (telegramLastMessage.state.toString == "Diesel") {
        var reply = "Dieselpreise:"
        var DateTime lastUpdate

        val HashMap<String, DecimalType> DieselMap = newHashMap
{% for tk in tankerkoenig %}
        if (TK_{{ tk[0] }}_Diesel.state != NULL && TK_{{ tk[0] }}_Diesel.state != UNDEF && TK_{{ tk[0] }}_Open.state == OPEN) {
            DieselMap.put("{{ tk[1] }}", (TK_{{ tk[0] }}_Diesel.state as DecimalType))
            lastUpdate = TK_{{ tk[0] }}_Diesel.lastUpdate("influxdb")
        }
{% endfor %}
        for (Price : DieselMap.entrySet.sortBy[value]) {
            var String key = Price.getKey().toString
            var String value = Price.getValue().toString
            reply = reply + String::format("\n%s: `%s`€", key, value)
        }
        reply = reply + String::format("\n\nvon: %s", lastUpdate.toString("yyyy-MM-dd HH:mm"))

        logInfo("Dieselpreise", reply)
        telegramAction.sendTelegramAnswer(Long::parseLong(telegramLastMessageChatId.state.toString), telegramLastMessageReplyId.state.toString, reply)

The entire code is explained in this blog posting. The relevant part is this:

1
2
3
4
5
var DateTime lastUpdate

lastUpdate = TK_{{ tk[0] }}_Diesel.lastUpdate("influxdb")

reply = reply + String::format("\n\nvon: %s", lastUpdate.toString("yyyy-MM-dd HH:mm"))

This defines a DateTime variable. While looping through the results, the lastUpdate timestamp from the influxdb persistance service is stored. And later when the result string is created, the formatted timestamp is appened.

Keep in mind that openHAB can have multiple Persistance services configured. The one you want to use (influxdb) is specified here.


Categories: [Openhab]