Push notification to include the time device has been on since


#1

1) Give a description of the problem
I have a device connected to a smart plug and would like to create a piston so that once we are away and if the device is on, it is turned off and a push notification is sent to us.

2) What is the expected behaviour?
I’d like the notification to include the time the device has been on since, i.e. “Device has been turned off. It was on since {time}”

3) What is happening/not happening?
I’m comfortable enough creating the piston - the only bit I don’t know how to do is include the time since the device has been on in the push notification. Do I need a separate piston to save the current time to a variable whenever my device state changes to on? And then refer to this variable in the push notification of my main piston? Or is there a slicker way to do it?

Thanks!


#2

Here’s something you can play with…

05/05/2020, 20:28:34 +432ms
+164ms ║Total time on: 8 minutes and 53 seconds
05/05/2020, 06:15:06 +752ms
+153ms ║Total time on: 4 minutes and 52 seconds


#3

Once off, you can use previousAge([device:attribute]) and age([device:attribute]) to calculate the time the device was on. For example:

with light
   turn off
   log to console "The light was on for " (previousAge([light:switch])-age([light:switch])/1000 " seconds"
   log to console "It was turned on at " addSeconds($now, (age([light:switch])-previousAge([light:switch])/1000)
end with

#4

Thanks both - I will experiment with both :slight_smile:


#5

That doesn’t seem to be working for me. I’ve put the following into a push notification where the message is of type “Expression”:

“$device was left on so I have turned it off. It was on for” "(previousAge([Iron:switch])-age([Iron:switch])/1000 "“seconds”

But it’s not picking up the $device or the previousAge formula. What am I missing?


#6

I believe there are too many quotes… Try this slight variation to the Expression:

$device" was left on so I have turned it off. It was on for "(previousAge([Iron:switch])-age([Iron:switch])/1000" seconds”


#7

Hmm with that I get “Invalid parenthesis closure termination” error.


#8

They look well placed to me… Perhaps try running it anyways…

Sorry, I don’t have time at the moment to pick apart his Expression… but usually, pure text is in quotes, and code is not.

Personally, I usually store data into variables before this step. It makes it much easier to see whats going on behind the scenes.


Edit:

Ooops… There may be a missing end parenthesis before the “/1000
(three open requires three close)


#9

If you combine PreviousAge() with formatDuration() it will give you a nicely formatted time in hours, minutes and seconds.

https://wiki.webcore.co/Functions#formatDuration

$device " was left on so I have turned it off. It was on for " formatDuration(previousAge([Iron:switch]),'s',false)


#10

Many thanks! I was getting random numbers up until that tip :slight_smile: