Heater's time is on using a counter (hystory_stats or template sensor ?)

Greetings,
I tried this year to add a sensor to measure the whole time my heater was on using history_stats and influxDB to store long time history (8 months).
To do so, I added this sensor in my config :

  - platform: history_stats
    name: Time heater on
    entity_id: sensor.heater
    state: 'heat'
    type: time
    start: '{{ as_datetime(1669478400) }}'
    end: '{{ now() }}'

But it did not ended with what I expected in influxDB, resulting in strange values, especially going up and down as I was expecting to addition any time unit when the state of the heater was on ‘heat’
Below is what the data looks like :


I don’t even know what is the unit (ms, sec, min ?)

So, I know that I messed up with something without being able to identify my mistakes.

If someone has any clue, I’d be very grateful.

Have a nice day

After some researches, I found the template sensors…

template:
  - sensor:
    - name: "Time heater on"
      unique_id: time_heating
      device_class: 'duration'
      unit_of_measurement: min
      state_class: total_increasing
      state: >
        {% if is_state('sensor.heater', 'heat') %}
          {{ (as_timestamp(now()) - as_timestamp('2023-05-01T06:54:44.000Z'))/60}}
        {% else %}
          {{ this.state }}
        {% endif %}

I dont’ know yet why, but yesterday, it seemed to work. Now, it gives me absurd results.
The dev mod gives me the result of

{{ (as_timestamp(now()) - as_timestamp(‘2023-05-01T06:54:44.000Z’))/60}}

when the heater’s state is ‘heat’

The logs give me this error

Error adding entities for domain sensor with platform template
Error while setting up template platform for sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 583, in state
    numerical_value = float(value)  # type:ignore[arg-type]
                      ^^^^^^^^^^^^
ValueError: could not convert string to float: 'unavailable'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 471, in async_add_entities
    await asyncio.gather(*tasks)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 749, in _async_add_entity
    await entity.add_to_platform_finish()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 849, in add_to_platform_finish
    await self.async_added_to_hass()
  File "/usr/src/homeassistant/homeassistant/components/template/sensor.py", line 224, in async_added_to_hass
    await super().async_added_to_hass()
  File "/usr/src/homeassistant/homeassistant/helpers/template_entity.py", line 409, in async_added_to_hass
    await self._async_template_startup()
  File "/usr/src/homeassistant/homeassistant/helpers/template_entity.py", line 380, in _async_template_startup
    result_info.async_refresh()
  File "/usr/src/homeassistant/homeassistant/helpers/event.py", line 974, in async_refresh
    self._refresh(None)
  File "/usr/src/homeassistant/homeassistant/helpers/event.py", line 1154, in _refresh
    self.hass.async_run_hass_job(self._job, event, updates)
  File "/usr/src/homeassistant/homeassistant/core.py", line 618, in async_run_hass_job
    hassjob.target(*args)
  File "/usr/src/homeassistant/homeassistant/helpers/template_entity.py", line 349, in _handle_results
    self.async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 590, in async_write_ha_state
    self._async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 654, in _async_write_ha_state
    state = self._stringify_state(available)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 596, in _stringify_state
    if (state := self.state) is None:
                 ^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 585, in state
    raise ValueError(
ValueError: Sensor sensor.time_heating has device class 'duration', state class 'total_increasing' unit 'min' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'unavailable' (<class 'str'>)

well, I’m quite stucked into nowhere :expressionless:
if someone has any clue, I’d be glad to give it a try
thanks

Hi,
Well, I have tried many things, but they are not working. If some would be able to help me, I’d be glad.

The last version of the code is

template:
  - sensor:
    - name: Time heating
      unique_id: time_heating
      device_class: duration
      unit_of_measurement: min
      state_class: total_increasing
      state: "{{is_state('sensor.heater', 'heat')}}"

Nothing’s happening. No counting at all. No error log

What am I missing ?

It seems like you have misunderstood the function of these sensors.

Your History-Stats sensor was the closest to what you want. It was actually counting the hours the heater was in the “heat” state. However, History-Stats is based on the History integration and is therefor limited to the span of the Recorder.

Your first template sensor was returning the total number of minutes between your current time and the datetime from May 1st… it had no actual connection to how long the sensor’s state value was “heat”.

Your second template sensor isn’t working because you have set it up with a defined unit of measurement, which requires a numeric state value, but the template for it’s state will only ever return true or false.

What I do is have a History-Stats sensor to track the “on”-time throughout a single day.

History Stats Example
sensor:    
  - platform: history_stats
    name: Heat_Daily_Active_Hours
    unique_id: heat_daily_active_hours_0001
    entity_id: sensor.thermostat_hvac_action
    state: "heating"
    type: time
    start: "{{ today_at() }}"
    end: "{{ now() }}"

Then, set up Utility Meter Helpers to handle to cyclic summation of the daily values. I do a weekly, monthly, and annual for both heating and cooling.

I don’t use InfluxDB, by I assume you would then base your “yearly” utility meter.

Thank you Drew !

Well, I went back to history stats with this

sensor:
  - platform: history_stats
    name: Time heating
    unique_id: time_heating
    entity_id: sensor.heater
    state: "heat"
    type: time
    start: "{{ as_datetime('1693526400') }}"
    end: "{{ now() }}"

I linked it with the Utility meter helper ! That was probably the missing piece.

Will check how it is running

Thank you again…