Benefit from long term statistics for any sensor

Recent home-assistant versions (2021.9) brought the ability to benefit from long-term statistics for any sensor. However, it works only if sensor expose the state_class attribute.
Integrations can be updated to support this and will progressively do so.
However, regular sensors (command line sensors for instance) don’t configure state_class by default and don’t allow (so far) to do it.

There are two solutions.

Solution1: use customize.yaml

This works for command line sensors (at least). In customize.yml, you can specify a sensor to have a state_class. Example:

sensor.bicycle_distance:
  icon: mdi:bike
  state_class: total_increasing

Solution 2: create a modern template sensor based on your sensor

In configuration.yaml:

template:
  - sensor:
      - name: Total cycled meter
        unit_of_measurement: "m"
        state_class: total_increasing
        state: >
          {{ states('sensor.bicycle_distance')|int }}

For editors: don’t hesitate to adapt this based on the most recent stable version of home-assistant, it seems this evolves with each version.

4 Likes