Help with custom valued sensor

Hello!

I’m hoping somebody can help me. I’m trying to create a template sensor that produces useful information based on the value of my home UPS. Ive got a sensor that ranges from 1 to 10 based on the fault, this itself works great but im trying to create a sensor that will display what the fault actually is. The definition for each value is:
1 No events
2 High line voltage
3 Brownout
4 Loss of mains power
5 Small temporary power drop
6 Large temporary power drop
7 Small spike
8 Large spike
9 UPS self test
10 Excessive input voltage fluctuation

and I’ve tried to create a sensor based on this but it fails the config check.

- platform: template
  sensors:
    ups_coms_port:
      friendly_name: 'UPS Comms'
      value_template: '{% if is_state("sensor.ups_comms_port", "1") %} System OK {% else is_state("sensor.ups_comms_port", "2") %} High line voltage {% elif is_state("sensor.ups_comms_port", "3") %} Brownout{% elif is_state("sensor.ups_comms_port", "4") %} Loss of mains power{% elif is_state("sensor.ups_comms_port", "5") %} Small temporary power drop{% elif is_state("sensor.ups_comms_port", "6") %} Large temporary power drop{% elif is_state("sensor.ups_comms_port", "7") %} Small spike{% elif is_state("sensor.ups_comms_port", "8") %} Large spike{% elif is_state("sensor.ups_comms_port", "9") %} UPS self test{% else is_state("sensor.ups_comms_port", "10") %}Excessive input voltage fluctuation {% endif %}' 

Any Help would be great

Nevermind! Its sorted!

You may wish to consider using a dictionary, instead of an if-elif chain, like this:

- platform: template
  sensors:
    ups_coms_port:
      friendly_name: 'UPS Comms'
      value_template: >
        {% set msg = { 1: 'System OK', 2: 'High line voltage',
                       3: 'Brownout', 4: 'Loss of mains power',
                       5: 'Small temporary power drop', 6: 'Large temporary power drop',
                       7: 'Small spike', 8: 'Large spike',
                       9: 'UPS self test', 10: 'Excessive input voltage fluctuation' } %}
        {% set code = states('sensor.ups_comms_port') | int %}
        {{ msg[code] if code in msg.keys() else 'Unknown' }}

It helps improve legibility by separating data from logic. All the data resides in the msg dictionary as key-value pairs. The logic simply tries to find a matching key for the received code and returns its associated value (the code’s description). If no matching key is found, it reports Unknown.

3 Likes