Operating hours counter - prevention of decreasing values

Hey,

I want to realize an operation hours counter. The counter itself seems to be working by the “on”-state.

sensor:
  - platform: history_stats
    name: operational hours light 01
    entity_id: light.down_01
    unique_id: cfa3c4e1-a3a5-41ac-xxxx-da4xxxxe1ded
    state: "on"
    type: time
    start: "{{ 0 }}"
    end: "{{ now() }}"

But:

The value is decreasing sometimes. How to prevent this? I think this relates to recorder. Is there any option to keep the values or another simple way to create counter for lots of devices?

Make a template sensor that is 1 if the light is on, and 0 if the light is off.

Pass that into a riemann sum/integral helper, set to hours. That will give you a lifetime count of the amount of hours the light is on, and won’t use the recorder at all.

History stats is limited to the amount of data in your recorder, and can only really tell you how long it was on for the last ~10 days or whatever you set it to.

Is my assumption correct that you explicitly do not mean a binary sensor?

sensor:
  - platform: integration
    source: binary_sensor.device_active
    name: HourCounter Device
    unique_id: e6a90d1c-afe9-4e47-b1e0-xxxxxxxx0e7a
    unit_time: h
    round: 2
    method: left

Correct. A binary_sensor is “on” or “off”. Integral can only operate on numeric values, so you must have a sensor that is a number.

I have seen that the counter and its value are only increased when the status goes from 1 to 0. Do you know what happens during a restart or when the device is running 24/7? Do you know a way how I can still always get current values?

template:
  - sensor:
    - name: "device active num"
      state: >-
        {{ is_state('binary_sensor.device_active', 'on') | abs }}

  - binary_sensor:
    - name: "device active"
      state: "{{ states('sensor.device_power') | float(0) > 5 }}"
      device_class: power
      
sensor:
  - platform: integration
    source: sensor.device_active_num
    name: HourCounter Device
    unique_id: e6a90d1c-afe9-4e47-b1e0-xxxxxxxx0e7a
    unit_time: h
    round: 2
    method: left

Look at the max_sub_interval option for integration sensor.

May you recommend a method in this case?

Hey @karwosts

I dont know why this values are decreasing. Can you help please?