Average off time sensor

Hi All,

I need some help creating a template sensor.
I have a switch that is turned of via sleepcycle that lets hassio know when i go to sleep.
This same switch is turned on when sleepcycle ends my sleep.

So i have a timestamp when the switch is turned off and back on again. if you do some calculations you can determine how long i have slept. What I would like is to take the average over 7 days and get a average value of how long i slept each day. This will be the value of my new sensor which im going to use to turn my thermostat on a couple hours before i wake up (on average).

Is there anybody that can help me figure this out.

I have looked at the SQL sensor integration but i don’t understand SQL that much.

This is surprisingly complicated… I’ve never tried anything like this, so I could just be missing something obvious, but I’m interested, so I’ll take a guess at it.

First, you need to record the amount of time you slept every day. You could automate this in one of two ways:

  1. (My choice, if it works) Create a trigger-based template sensor that is updated when the sleepcycle switch state changes to off. You could then use the trigger variables to compare trigger.from_state.last_changed to trigger.to_state.last_changed, and record the difference as the state of this sensor.
  2. Create a RESTful sensor that does the same thing once a day, using the data from the history REST API.

Then, as long as statistics works how I imagine, you can track the mean of the sensor you have created, over the last seven days.