I have a number of sensors from my Komfovent MHRV unit that have multiple states. I have been creating these sensors using a mapper template translating the number from MODBUS to a named state.
sensor:
- platform: template
sensors:
unit_of_measurement: "State"
value_template: >-
{% set mapper = {
'0' : 'StayAtHome',
'1' : 'WorkingWeek',
'2' : 'Office',
'3' : 'Custom'} %}
{% set state = states('sensor.komfovent_scheduler_num') %}
{{ mapper[state] if state in mapper else 'Unknown' }}
These sensors have started to Error.
ValueError: Sensor sensor.komfovent_scheduler_mode has device class None, state class None unit State and suggested precision None thus indicating it has a numeric value; however, it has the non-numeric value: WorkingWeek (<class 'str'>)
2023-07-01 17:47:06.454 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved
By replacing unit_of_measurement: "State" with device_class: enum I have got rid of the error.
I did delete that and I added a device_class, not a state_class.
This change solves the error problem. I am just wondering what the right YAML would be to add the options to the sensor (as per docs) and if those could be used to do the translation.
That’s not how the enum device_class works. You supply a list of valid states. There is no translation.
Hence: just delete the unit of measurement.
The legacy template sensor does not support the option list, and won’t as no new features are being added now that we have the new format.
The new format for template sensors does not support enum option lists either as far as I can see. Though you could open a feature request if there isn’t one already.
Ah, yes. I have gone full circle here. I remember looking at the Template Sensor docs and wondering how I could define the sensors I had with the new format.
Looking at it again, it looks like the new syntax should simply be like this (there is an indentation error in this example I think);
template:
- sensor:
- name: "Komfovent Scheduler Mode"
state: >
{% set mapper = {
'0' : 'StayAtHome',
'1' : 'WorkingWeek',
'2' : 'Office',
'3' : 'Custom'} %}
{% set state = states('sensor.komfovent_scheduler_num') %}
{{ mapper[state] if state in mapper else 'Unknown' }}