Help to build a template sensor from multiple sensors

Hi,

I’m trying to build a template sensor that reads the state of two sensors but I’m not sure it it’s possible and, if it is, how to acomplish.

I’ve a sensors.yaml file and and I have two binary sensors. I want that if sensor A is off and sensor B is off, this new sensor state is OFF. If sensors A and B are on, then, this sensor should be ON. any other state (off/on or on/off), it stays as it was before.

I’ve tried this, but I’m getting erros:

- platform: template
  sensors:
    laststate:
      friendly_name: "Last State"
      value_template: >-
        {% if is_state('binary_sensor.sensor_portao_da_garagem_fechado', 'off') and is_state('binary_sensor.sensor_portao_da_garagem_aberto,'off') %}
          off
        {% elif is_state('binary_sensor.sensor_portao_da_garagem_fechado', 'on') and is_state('binary_sensor.sensor_portao_da_garagem_aberto,'on') %}
          on
        {% endif %}

Can someone give me a hint on this?
Thanks in advance

you’re missing a single quote at the end of binary_sensor.sensor_portao_da_garagem_aberto in both lines before the comma.

Also, you need an else statement

- platform: template
  sensors:
    laststate:
      friendly_name: "Last State"
      value_template: >-
        {% if is_state('binary_sensor.sensor_portao_da_garagem_fechado', 'off') and is_state('binary_sensor.sensor_portao_da_garagem_aberto','off') %}
          off
        {% elif is_state('binary_sensor.sensor_portao_da_garagem_fechado', 'on') and is_state('binary_sensor.sensor_portao_da_garagem_aberto','on') %}
          on
        {% else %}
          {{ states('sensor.laststate') }}
        {% endif %}
2 Likes

Thanks man, that solved!!!

Am I always obligated to use the else statement when using the if?

You’re only obligated to use it when you have a condition that can be met that is not in your if and elif statements. If you didn’t add that else to the template, it wouldn’t retain the previous state, it would have been blank because the code finished without an output.

1 Like

Got it!

Thanks for the help and the explanation!

1 Like