Binary sensor template with state

Hi everyone,

I am trying to use blueprint for Sensor Light, however in triggers section I am supposed to use a binary sensor.

So I am trying to create a binary sensor using templates. I have a wall switch that doesn’t have on and off state, but instead it has action, which is null, but when I press a button, it changes to single_l1 for a short period of time.

{{ is_state('sensor.living_room_switch_action', 'single_l1')}}

I’d like to use this short change of action to toggle the binary sensor from on/off and vice versa. I’m new to home assistant and I haven’t been able to find out how to do that.

Try this:

# configuration.yaml
template:
  - trigger:
      - platform: state
        entity_id: sensor.living_room_switch_action
        to: "single_l1"
    binary_sensor:
      - name: "My Light State" # or whatever you want to call it
        state: "{{ not this.state if this.state is defined else false }}"
2 Likes

Thanks for that. It works when the state is on and I turn it off with the switch. However, when it’s off I cannot turn it on again. Any idea why?

I tried "on" and "off" instead of true and false, but nothing seems to work.

EDIT: made it work with this:

{{ true if this.state is defined and this.state == "off" else false }}

Your template doesn’t need to explicitly indicate boolean true/false. It is capable of doing it implicitly.

{{ this.state is defined and this.state == 'off' }}
2 Likes

you could also do {{ not (this.state | bool(true)) }}
this.state is always defined as far as I know, it will be unknown before it triggered.

I tried that in the template editor and could not get it to work. But I did not initialise this.