Template sensor with discrete string values

I have created a multiline-if template sensor that combines few other sensor values and generates a human friendly ouput for the status of my heat pump.

The template sensor is defined like this:

template:
  - sensor:
      - name: "Nilan_CompactP"
        state: >
          {% if is_state('binary_sensor.nilan_compactp_compressorstate', 'off') %}
            off
          {% elif is_state('binary_sensor.nilan_compactp_deicingheatexchanger', 'on') or is_state('binary_sensor.nilan_compactp_deicingheatpump', 'on') %}
            defrosting
          {% elif is_state('binary_sensor.nilan_compactp_heatvalve', 'on') and is_state('binary_sensor.nilan_compactp_fourwayvalve', 'off') %}
            heating
          {% elif is_state('binary_sensor.nilan_compactp_heatvalve', 'on') and is_state('binary_sensor.nilan_compactp_fourwayvalve', 'on') %}
            cooling
          {% elif is_state('binary_sensor.nilan_compactp_hotwatervalve', 'on') and is_state('binary_sensor.nilan_compactp_fourwayvalve', 'off') %}
            hot water production
          {% else %}
            unknown
          {% endif %}
        state_class: measurement

The sensor itself works OK, meaning that it outputs the correct string value. The issue is with the history card in the GUI - it wants to plot a chart, but obviously fails since there are no numeric values.

I would like to have a discrete history chart, similar to the weather integration:
image

Question: How can I define a custom “enum” for my sensor?

The inclusion of the state_class option influences the graph’s appearance. From the documentation for state_class:

The state_class of the sensor. This will also display the value based on the user profile Number Format setting and influence the graphical presentation in the history visualization as a continuous value.

I’m not sure why you have added state_class to this Template Sensor because it’s normally used with numeric data (and this sensor’s data isn’t numeric).

I suggest you remove the state_class option (unless there’s an overriding reason for using it). The graph’s appearance might not change immediately (it may require the old data to be purged and that depends on how recorder’s purged duration is set) or it may happen the moment it gets a new value … not sure how it behaves in this situation where state_class is first included and then later removed.

1 Like

Removing the state_class actually did it. But I had to rename the sensor, otherwise it didn’t work (like you suggested). I would probably have to purge all history if I wanted to preserve the same sensor.