To check if an MQTT based device is still active, I would like to check every minute (using cron rule) and calculate the time since last change.
Idea:
If the difftime > 65 seconds --> take action…
In items file:
String VPNStatus “VPN Status [%s]” (gVPN) {mqtt="<[mosquitto:/vpn/status:state:default]"}
In rules file:
rule "check difftime"
when
Time cron “0 * * * * ?” //every minute
then
var Number test1 = (VPNStatus.lastUpdate as DateTimeType).calendar.timeInMillis
logInfo(“VPNSatus”, test1.toString)
end
In logfile there is error but cannot figure out what is wrong:
Error during the execution of rule difftime: org.eclipse.smarthome.core.library.types.DateTimeType
Sure, I found out that the VPNStatus was not in a persistence database.
The program was not aware of any datetime recording, adding it to the MySQL persistence seems to solve it.
Still having other problems, I’ll keep you informed!
-ben
An alternative approach is to use the Expire binding. This approach does not require persistence nor does it require polling.
Item
String VPNStatus "VPN Status [%s]" (gVPN) {mqtt="<[mosquitto:/vpn/status:state:default"], expire="1m"}
Rule
rule "Is offline"
when
Item VPNStatus changed to NULL
then
logInfo("VPN", "The VPN Status has not reported for over a minute, it must be offline.
end
Theory of operation:
The Expire binding sets the VPNStatus to NULL when it hasn’t received an update for more than a minute. The Rule triggers when the Item changes to NULL to report the Item has gone offline.
See the Expire binding’s readme for other options and details.
Another approach, if I understand your setup, would be to use a last will and testament message. This is a message the MQTT client registers with the broker to be sent when the client goes offline. OH can subscribe to that topic and generate an alert when the broker reports the client is offline.
I tried to use it with a Number Item, the Expire binding works but the state of the Item (when it expires) will become ‘undef’.
In a rule I cannot test against undef , at least the it generates an error:
An error occured during the script execution: The name 'undef' cannot be resolved to an item or type.