Im trying to create a binary_sensor that is equal with the newest value of a pair of two binary_sensors.
I placed this one under template: include …
- binary_sensor:
- name: "Linkes Fenster (Spitzboden)"
unique_id: binary_sensor.spitzboden_kontaktsensor_fenster_links_status
device_class: "window"
state: >
{% if as_timestamp(states.binary_sensor.spitzboden_kontaktsensor_fenster_links_1_status.last_changed) >as_timestamp(states.binary_sensor.spitzboden_kontaktsensor_fenster_links_2_status.last_changed) %}
{{states('binary_sensor.spitzboden_kontaktsensor_fenster_links_1_status')}}
{% else %}
{{states('binary_sensor.spitzboden_kontaktsensor_fenster_links_2_status')}}
{% endif %}
Every other template sensor is working.
Where is my mistake? Thank you for your help.
petro
(Petro)
June 12, 2023, 9:50am
2
On startup these may not exist and you need to account for that.
- binary_sensor:
- name: "Linkes Fenster (Spitzboden)"
unique_id: binary_sensor.spitzboden_kontaktsensor_fenster_links_status
device_class: "window"
state: >
{% set link1 = states.binary_sensor.spitzboden_kontaktsensor_fenster_links_1_status %}
{% set link2 = states.binary_sensor.spitzboden_kontaktsensor_fenster_links_2_status %}
{% if not link1 and not link2 %}
None
{% elif link1.last_changed > link2.last_changed %}
{{ link1.state }}
{% else %}
{{ link2.state }}
{% endif %}
Thank you for your reply. Obviously my attempt seemed to work as expected but the problem is, that the entity id created is not the unique id, but the one which is derived from the name, in this case “binary_sensor.linkes_fenster_spitzboden”. Is this the expected behavior?
petro
(Petro)
June 12, 2023, 9:58am
4
That is expected. The object_id is pulled from a sluggified name. Unique_id simply lets you adjust settings in the UI.
Troon
(Troon)
June 12, 2023, 9:59am
5
Trigger-based version, saves messing with timestamps:
template:
- trigger:
- platform: state
entity_id:
- binary_sensor.spitzboden_kontaktsensor_fenster_links_1_status -
- binary_sensor.spitzboden_kontaktsensor_fenster_links_2_status
to:
- 'on'
- 'off'
binary_sensor:
- name: "Linkes Fenster (Spitzboden)"
state: "{{ trigger.to_state.state }}"
Great idea, but how do i initialize it? The value is set when the first change is happening?!
petro
(Petro)
June 12, 2023, 10:21am
7
Yes, it will be unknown until the first sensor changes state.