How do I track how long a switch has been on?

Hello. I can’t measure gas consumption directly at my property. So my strategy is to measure how long the led is lit when the boiler is active, using a light sensor driving a GPIO pin, and estimate it from that.

This doesn’t work:

sensor:
  - platform: pulse_width
    pin: D1
    name: Gas Sensor
    id: gas_sensor
    device_class: gas
    accuracy_decimals: 1
    update_interval: 1s
    
  - platform: integration
    name: "Total Gas On Time"
    sensor: gas_sensor
    time_unit: min

pulse_width measures the time the light is on. But it holds that value until the next pulse. So the integrator is constantly accumulating the last measured duration.

I tried passing a binary_sensor to integration, but that choked.

I’ve seen solutions (e.g. here) using the History Stats component in Home Assistant, but I was hoping to do it on-device if possible to keep things as decoupled as possible.

I’m new to Home Assistant and ESPHome and this may be obviously doable, or obviously impossible but I can’t see it. Any guidance?

(P.S. I will want daily totals - either by resetting the total on-device at midnight, or in Home Assistant).

Many thanks.


UPDATE

I have a working solution combining ESPHome and Home Assistant as follows:

ESPHome:

binary_sensor:
  - platform: gpio
    pin: D8
    name: Gas Sensor
    id: gas_sensor

Home Assistant configuration.yaml:

  - platform: history_stats
    name: Gas ON today
    entity_id: binary_sensor.gas_sensor
    state: "on"
    type: time
    start: "{{ now().replace(hour=0, minute=0, second=0) }}"
    end: "{{ now() }}"
1 Like

Thanks for posting your solution. That’s exactly what I do with my oil-fired boiler.

I also have an entity for Burner On Yesterday:

  - platform: history_stats
    name: Burner on yesterday
    entity_id: binary_sensor.boiler_burner
    state: 'on'
    type: time
    end: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
    duration:
      hours: 24

Basically what that says is “ending last night at midnight, total up the previous 24 hours’ worth of run time.”

I also record this (and other) run-time statistics to a text file for long-term storage and analysis outside HA.

1 Like