Binary Sensor Template goes unavailable

Hello,

I hava a binary sensor in my configuration.yaml setup like this:

template:
  - binary_sensor:
      -name: Specialweek
      -unique_id: Specialweek
      -state: '{{"special" in state_attr("calender.private", "message") }}'

what it does so far:

It creates a custom sensor that is “on” as long as I have an event in my calender that contains the word “special”. But as soon as this event is over, the sensor becomes unavailable instead of turning off. How come? How can I change that?

I would like it to be “on” as long as the condition is true, and turn off otherwise.

Thank you

what happens to “message” when the event is over and what errors are in your logs? Chances are that you have to protect against an absent message attribute, which your template does not do.

ok, guess you hit the nail. when there is no event active in my calender, the “message” attribute is absent! how can I prepare the sensor for that?

      -state: >
         {% set message = state_attr("calender.private", "message") %}
         {% if message %}
           {{ 'special' in message }}
         {% else %}
            False
         {% endif %}

or more condensed…

      -state: >
         {% set message = state_attr("calender.private", "message") %}
         {{ 'special' in message if message else False }}

or using the iff filter that’s similar to excels if macro

      -state: >
         {% set message = state_attr("calender.private", "message") %}
         {{  message | iif('special' in message, False, False) }}
1 Like

image

I just copied your code and change calender name and the desired message string. what does it mean?

try it again, I left out the multiline indicator

works like charm. thank you so much :slight_smile:

just for the sake of clarification: when you put the code inside the template developer tools it says

“false” type: string

because of

...
         {% else %}
            False
         {% endif %}

When I look up the entity it says “off” - as intented. I am aware how “if / then / else” works, but why wouldnt one just put

         {% else %}
            Off
         {% endif %}

instead of false? (because I thought the boolean input is either on or off.)

binary sensors work with true/false as a returned value from templates. with short template’s it’s shorter to omit the words on and off.

For example…

{% if is_state('sensor.xyz', 'hello') %}
  on
{% else %}
  off
{% endif %}

vs

{{ is_state('sensor.xyz', 'hello') }}

it’s just easier to do.