Combining two automations into 1

I have a device that is reporting itself as a sensor, so it actually sends states 0->255. I want to use this to configure a switch. I currently have this working fine but its two seperate automations. 0 turns the light off. 255 turns it on ( its never in-between)

I am working off of this template I have used before.

alias: HallSwitch
description: ''
trigger:
  - platform: state
    entity_id: sensor.entry_closet
condition: []
action:
  - service_template: switch.turn_{{ trigger.to_state.state }}
    data_template:
      device_id: 0bb600e137c915bcaa8049b1dc4bb76f
      entity_id: switch.entry_closet
      domain: switch
mode: single

Needless to say it doesn’t work since there isn’t switch.turn_0 or switch.turn_255. I am a bit unfamiliar with the templating and wondering if you all have a good suggestion for how convert 0 into off and 255 into 0?

I think this is how this goes… …the state is a string correct?

{{ 'off' if trigger.to_state.state == '0' else 'on' }}

Thanks so much, that worked. I was way overthinking it, thinking I needed a map variable or something that I could then use selectatr on.

You can use the visual automation editor from UI and pick the „choose“ action: If numeric state of sensor is 255, the turn on. Make „turn off“ the default.

Much easier to read and maintain.

2 Likes

Agree with @m0wlheld

Especially since the template, as written, has a serious drawback.