Help with Automations and device states to trigger lights based off MQTT event

Hi all,

I have two lights in a group which I trigger off/on using MQTT from an ESP8266 switch.

I do this with two binary sensors:

binary_sensor:
- platform: mqtt
name: matt_lights
state_topic: "home/matt/bedroom/lights"
payload_on: "1"
payload_off: "0"

Currently I’m using the toggle functionality in automations. I was wondering if there was a way I could improve below, so that when off/0 is received, the lights will trigger off (if they were on), and vice versa.

Basically the problem I’m trying to solve is that sometimes one light will be on, while the other will be off. If I press the button, they will switch roles with the other now on, and the other light off!

- alias: 'ESP Button Lights'
trigger:
- platform: state
entity_id: binary_sensor.matt_lights
to: 'on'
- platform: state
entity_id: binary_sensor.matt_lights
to: 'off' 
action:
service: switch.toggle
entity_id:
- switch.matts_bed_lamp
- switch.matts_desk_light

Help improving above appreciated :slight_smile:

Thanks,

Matt

Wouldn’t changing:

service: switch.toggle 

to

service: switch.turn_off

be sufficient? You would also have to create an opposite automation to this one, where it triggers on changing from ‘off’ to ‘on’ and then use

service: switch.turn_on

Prerequisite for this is that your switch has different commands for command_on and command_off.

Hey thanks.

Didn’t realise it was that simple.

The following works:

- alias: esp-button-lights-on
  trigger:
    - platform: state
      entity_id: binary_sensor.matt_lights
      to: 'on'
  action:
    service: switch.turn_on
    entity_id:
      - switch.matts_bed_lamp
      - switch.matts_desk_light

- alias: esp-button-lights-off  
  trigger:
    - platform: state
      entity_id: binary_sensor.matt_lights
      to: 'off' 
  action:
    service: switch.turn_off
    entity_id:
      - switch.matts_bed_lamp
      - switch.matts_desk_light

Do I actually have to do it under two aliases, or is it possible to have each state/action under one alias?

Thanks,

Matt

You can do it all in one automation. Untested but this should work:

- alias: 'ESP Button On / Off'
  trigger:
    - platform: state
      entity_id: binary_sensor.matt_lights
  action:
    service_template: >
     {% if trigger.to_state.state == 'on' %}
       switch.turn_on
     {% else %}
       switch.turn_off
     {% endif %}
    entity_id:
      - switch.matts_bed_lamp
      - switch.matts_desk_light
2 Likes

Hey thanks!

That works :slight_smile:

Much appreciated @corunir and @tom_l :+1: