Please help streamline the code automations.yaml

I have a switch and a light, and they bridge through the Home Assistant to realize the switch on, turn on the light, turn the switch on, turn off the light, and turn off the light. But I also use other devices to control the light switch, so I also need a script to check the status of the light. If the light is on, the switch should turn on. If the light is on, the switch should be switched off. So I wrote 4 pieces of code in the original way. Now I want to be able to simplify the code. My code is as follows. Thanks.

- alias: 'onoff'
  trigger:
    platform: state
    entity_id: switch.wall_switch_right_158d00012f7c
    to: 'on'
  condition:

  action:
    - service: light.turn_on
      entity_id: light.gateway_light_34ce008bf8

      

- alias: 'lonoff'
  trigger:
    platform: state
    entity_id: light.gateway_light_34ce008bf8
    to: 'on'
  condition:

  action:
    - service: switch.turn_on
      entity_id: switch.wall_switch_right_158d00012f7c
      

- alias: 'offon'
  trigger:
    platform: state
    entity_id: switch.wall_switch_right_158d00012f7c
    to: 'off'
  condition:
  action:
    - service: light.turn_off
      entity_id: light.gateway_light_34ce008bf8


  
- alias: 'loffon'
  trigger:
    platform: state
    entity_id: light.gateway_light_34ce008bf8
    to: 'off'
  condition:
  action:
    - service: switch.turn_off
      entity_id: switch.wall_switch_right_158d00012f7c

Use ``` before and after your code so that it appears correctly (you can edit your code).

You can use templates to reduce the number of automations. Check here for examples. However, if you are just starting off, I would leave it as is. Get the desired functionality first and then worry about simplifying.

1 Like

What kind of light are you using?
I only have experience with the HUE lights, and these do update the status to HA if switched on by other means. It depends on the polling how fast the update happens. I manually set it to 2 seconds. Maybe this is not applying to your lights though.

Thank you for your reply, I am xiaomi gateway light, the principle should be the same

Then maybe first try it out if HA gets updated. Turn on the light, and wait some time to see if HA updates the light status. 30s - 1min.

If it does, all you need to do is reduce the update time :slight_smile:

Look at the example, a little clear, thank you, but I do not have a programming foundation, I need to look deep in the end how to write code. Thank you very much!

I use a condition to check the status of a light. This way a light is only switched on when it’s off and the other way around. This could simplify your automations I think.

  condition:
    condition: state
    entity_id: light.mylight
    state: 'off'

You could also combine this with a toggle action instead of turn_on and turn_off