I’m looking to count the time in seconds a binary sensor is on for the day. The binary sensor is already defined but I’m not really sure where to go from there. It looks like the history stats sensor in home assistant would work but I want to count it directly on the esp.
If you want to do it on the ESP:
- Create
on_press:
andon_release:
lambda code that calculates the sensor on time. - In the
on_release:
, calculate and store the total for the day so far and publish to a template sensor. - Use an
on_time:
trigger in a time component to reset the template sensor at midnight.
Thanks for the quick reply I’ve progressed this far.
- platform: gpio
name: "run time"
id: run_time
pin:
number: GPIO26
mode:
input: true
pullup: true
on_press:
then:
lambda: |-
return x id(sntp_time).now();
on_release:
then:
lambda: |-
return id(sntp_time).now() - x
But if this is correct I cannot figure out how to calculate the total for the day so far prior to publishing
First pass below. Compiles but in no way tested.
globals:
# used to store timestamp for sensor on
- id: timestamp
type: int
time:
- platform: sntp
id: sntp_time
# at midnight:
on_time:
- seconds: 0
minutes: 0
hours: 0
then:
# reset daily time counter
- sensor.template.publish:
id: run_time
state: !lambda 'return 0;'
binary_sensor:
# input binary sensor we want to calculate total on-time for
- platform: gpio
name: "Input Sensor"
id: input_sensor
pin:
number: GPIO26
mode:
input: true
pullup: true
on_press:
# store the current epoch time (seconds since 1/1/70)
- lambda: 'id(timestamp) = id(sntp_time).now().timestamp;'
on_release:
# calculate the total time = (old total time) + (current epoch time) - (stored on_press epoch time)
# and publish in the template sensor
- sensor.template.publish:
id: run_time
state: !lambda 'return id(run_time).state + id(sntp_time).now().timestamp - id(timestamp);'
sensor:
# total run time for the day sensor
- platform: template
name: "Run Time"
id: run_time
Take this with a grain of salt because I’m a coding half-wit (and I got help getting this one to work correctly back in the day), but this is what I use to track when my boiler is “on” in a 24 hour period. It’s been working flawlessly for years now.
It could be just as simple as editing the entity and the state and the percision of the output. (Then I just display the output in a graph card.)
# History Stats for Furnace
- platform: history_stats
name: FurnaceOnToday
entity_id: sensor.thermostat
state: 'heating'
type: time
start: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
end: '{{ now() }}'
Thanks for your help zoogara. I couldn’t quite get you code working but it turns out there was a pretty easy way to achieve this. I used the duty_time componet and just reset it a midnight. I assume the history stats would also have worked but I wanted to do it on the esp and I think that has to be done with home assistant