Automation with two actions depending on state of entity

Hi,
I’m migration my home automation from another system to HA, and am a bit lost in the yaml syntax.

I have a input select entity with two options: “Disconnected from grid” / “Connected to grid”, configured in configurations.yaml

input_select:
  inverter_mode:
    name: Inverter Switch
    options:
      - "Disconnected from grid"
      - "Connected to grid"
    initial: "Connected to grid"
    icon: mdi:target

For each of these options I created a rule file to send the appropriate command (to disconnect / connect the inverter from the grid) via MQTT to the inverter.

Everything is working perfectly fine.

My question: how can I combine the two rule files into a single rule file? My solution works, but feels so messy.

inverter_set_mode_connected.yaml

alias: "Set Inverter Mode Connected"
trigger:
    platform: state
    entity_id: input_select.inverter_mode
    to: "Connected to grid"
action:
  service: mqtt.publish
  data:
    topic: victron/W/7c3866560fa4/vebus/261/Mode
    payload: '{"value": 3}'

inverter_set_mode_disconnected.yaml

alias: "Set Inverter Mode Disconnected"
trigger:
    platform: state
    entity_id: input_select.inverter_mode
    to: "Disconnected from grid"
action:
  service: mqtt.publish
  data:
    topic: victron/W/7c3866560fa4/vebus/261/Mode
    payload: '{"value": 2}'

NB - the forum is warning me about unformatted code. How do I fix it?

Try a single automation with two triggers - “connected” and “disconnected”.

If you give each trigger an ID, you can use “choose” in the action to do different things. Here’s a simple example:

description: ""
mode: single
trigger:
  - platform: state
    entity_id:
      - light.bedroom_lights
    to: "on"
    id: turn_on
  - platform: state
    entity_id:
      - light.bedroom_lights
    to: "off"
    id: turn_off
condition: []
action:
  - choose:
      - conditions:
          - condition: trigger
            id:
              - turn_on
        sequence:
          - service: light.turn_on
            metadata: {}
            data: {}
            target:
              entity_id: light.cooker_lights
      - conditions:
          - condition: trigger
            id:
              - turn_off
        sequence:
          - service: light.turn_off
            metadata: {}
            data: {}
            target:
              entity_id: light.cooker_lights

I usually ignore that warning… :roll_eyes:

That looks perfect, thanks! I’ll give that a try.

//update - it worked like a charm. One bit of file-clutter less, more cohesive structure and I learned new things in the process. Thanks!