Optimize automation with trigger ids

I just took a look at trigger id’s thinking I could simplify my automations. So instead of a separate automation for every action I can combine them.

Most of my automations are pretty “binary”, for example, turning on a light when there is movement and x amount of lumen. And turn off the same light when there is no motion for x amount of time.

Before my automation looked like this:

- id: licht_kantoor_aan
  alias: Zet het licht aan in het kantoor bij beweging
  trigger:
    platform: state
    entity_id: binary_sensor.motion_kantoor_home_security_motion_detection
    to: 'on'
  condition:
    condition: numeric_state
    entity_id: sensor.motion_kantoor_illuminance
    below: 25
  action:
    service: light.turn_on
    entity_id: light.kantoor

- id: licht_kantoor_uit
  alias: Zet het licht uit in het kantoor bij geen beweging
  trigger:
    platform: state
    entity_id: binary_sensor.motion_kantoor_home_security_motion_detection
    to: 'off'
    for:
      seconds: 600
  action:
    service: light.turn_off
    entity_id: light.kantoor

Now when utilizing trigger IDs it looks like this:

- id: licht_kantoor_aan_uit
  alias: Zet het licht aan en uit in het kantoor
  trigger:
    - platform: state
      id: 'motion'
      entity_id: binary_sensor.motion_kantoor_home_security_motion_detection
      to: 'on'
    - platform: state
      id: 'no-motion'
      entity_id: binary_sensor.motion_kantoor_home_security_motion_detection
      to: 'off'
      for:
        seconds: 600
  action:
    - choose:
        - conditions:
            - condition: trigger
              id: 'motion'
            - condition: numeric_state
              entity_id: sensor.motion_kantoor_illuminance
              below: 25
          sequence:
            - service: light.turn_on
              target:
                entity_id: light.kantoor
        - conditions:
            - condition: trigger
              id: 'no-motion'
          sequence:
            - service: light.turn_off
              target:
                entity_id: light.kantoor

Both cases work just fine. The advantage is that I now only have 1 automation to control the light. But the downside if that my code is actually 8 lines longer then the two separate automations.

Can my code be compacted while still retaining readability? Especially the choose actions takes a lot of lines.

It depends on what you mean by readability and if you know how to use templates.

you can use templates to decide which service call you use instead of the “choose” and in the template you can use “trigger.id” as a test for which call to make (turn_on or turn_off).

otherwise it’s a trade-off of more lines or more automations.

either way it’s no big deal aside from your own abilities and preferences.