Hi
I’m writing this in case someone is looking for a way to create a template sensor where at least one set of multiple conditions need to be true in order to return an ON state (or whichever state is needed)
YAML is a new language for me and there are lots of examples of using variables or if…elif etc, but I couldn’t find anything using a logical AND or a logical OR in templates. Automation conditions, yes, but not in templating, but I got there in the end and hopefully this will find it’s way to someone that needs it.
I kinda fudged this together, so if there’s a better/alternative way then please share.
The example below is creating a sensor to detect when specific people/devices from home have WiFi enabled on their device and are connected to the home WiFi.
(The idea being that the result can underpin any away/home logic for alarms lights etc…)
Each of the mobile devices to be tracked have their companion app “Wifi Connection” and “WiFi State” sensors activated.
Example people:
Dave - Samsung S22
Brian - Pixel 6
Helen - IPhone 12
Sensor name: someone_is_on_wifi
# Mobile Device Home WIFI Detection
- platform: template
sensors:
someone_is_on_wifi:
friendly_name: Someone trusted is connected to our WiFi
icon_template: >-
{% if is_state('binary_sensor.dave_s22_wifi_state','on') and is_state('sensor.dave_s22_wifi_state','MyHomeWIFIName') %}
mdi:wifi
{% elif is_state('binary_sensor.brian_pixel6_wifi_state','on') and is_state('sensor.brian_pixel6_wifi_connection','MyHomeWIFIName') %}
mdi:wifi
{% elif is_state('binary_sensor.helen_ip12_wifi_state','on') and is_state('sensor.helen_ip12_wifi_connection','MyHomeWIFIName') %}
mdi:wifi
{% else %}
mdi:wifi-off
{% endif %}
value_template: >-
{% if is_state('binary_sensor.dave_s22_wifi_state','on') and is_state('sensor.dave_s22_wifi_state','MyHomeWIFIName') %}
on
{% elif is_state('binary_sensor.brian_pixel6_wifi_state','on') and is_state('sensor.brian_pixel6_wifi_connection','MyHomeWIFIName') %}
on
{% elif is_state('binary_sensor.helen_ip12_wifi_state','on') and is_state('sensor.helen_ip12_wifi_connection','MyHomeWIFIName') %}
on
{% else %}
off
{% endif %}
This’ll be obvious to many, but like all knowledge, it’s easy when you already know the answer