Base on switches state, set sensor value

Hello,

Looking for help to create sensor that will have value of current running program on dish machine. Home Connect showing me all programs as separate switches, so I wanted to check every switch and based on which is ‘on’ set value of my sensor to use it later in dashboard to show which program is running right now.

I wrote:

- sensor:
    - name: "Wash machine running program"
      unique_id: "wash_machine_running_program"
      state: >
          {% if state_attr('switch.zmywarka_do_naczyn_poznan_program_quick65') == 'on' %}
            Quick65
          {% elif state_attr('switch.zmywarka_do_naczyn_poznan_program_quick45') == 'on' %}
            Quick45
          {% elif state_attr('switch.zmywarka_do_naczyn_poznan_program_prerinse') == 'on' %}
            PreRinse
          {% elif state_attr('switch.zmywarka_do_naczyn_poznan_program_nightwash') == 'on' %}
            NightWash
          {% elif state_attr('switch.zmywarka_do_naczyn_poznan_program_machinecare') == 'on' %}
            MachineCare
          {% elif state_attr('switch.zmywarka_do_naczyn_poznan_program_intensiv70') == 'on' %}
            Intensiv70
          {% elif state_attr('switch.zmywarka_do_naczyn_poznan_program_glas40') == 'on' %}
            Glas40
          {% elif state_attr('switch.zmywarka_do_naczyn_poznan_program_eco50') == 'on' %}
            Eco50
          {% elif state_attr('switch.zmywarka_do_naczyn_poznan_program_auto2') == 'on' %}
            Auto2
          {% else %} off
          {% endif %}

But after that sensor is in “unavailable” state even if at the end there is
{% else %} off

How to do it ?

It’s unavailable because there’s an error in the template.

Use the states() function, not the state_attr() function.

Example 1

state: >
   {% if states('switch.zmywarka_do_naczyn_poznan_program_quick65') == 'on' %}
     Quick65

You can also do it like this with the is_state() function.

Example 2

state: >
   {% if is_state('switch.zmywarka_do_naczyn_poznan_program_quick65', 'on') %}
     Quick65

Reference

Templating - States