How do I achieve a switch toggle in a single automation or script?

I have a few situations that require a switch toggle based on different values. For example, if a humidity sensor is above 45%, turn on a switch until the humidity is below 45% and then turn it off.

I can only seem to do this with two separate automations. Is there a way to combine this into a single automation or script?

Ofc, use trigger ids. Post your automations, and I’ll try to help you out

You need 2 triggers and as action a choose condition that checks which trigger was fired.

I’ve just been playing around but I figure someone knows the best practice for this so I can learn.

I have an automation for the trigger:

alias: RV Dehumidifier
description: ""
trigger:
  - platform: numeric_state
    entity_id: sensor.rv_humidity
    for:
      hours: 0
      minutes: 10
      seconds: 0
    above: 45
condition:
  - condition: device
    type: is_off
    device_id: 78edfca4e84b3b378f1b9a71ec02610b
    entity_id: switch.wp_10
    domain: switch
action:
  - service: script.rv_dehumidifier_turn_off_device_script
    data: {}
mode: single

that then triggers a script:

alias: RV Dehumidifier - Turn Off Device script
sequence:
  - if:
      - condition: numeric_state
        entity_id: sensor.rv_humidity
        above: 45
    then:
      - type: turn_on
        device_id: 78edfca4e84b3b378f1b9a71ec02610b
        entity_id: switch.wp_10
        domain: switch
      - delay:
          hours: 0
          minutes: 0
          seconds: 0
          milliseconds: 0
    else:
      - type: turn_off
        device_id: 78edfca4e84b3b378f1b9a71ec02610b
        entity_id: switch.wp_10
        domain: switch
mode: single
icon: mdi:camera-timer

It just feels clunky to me but I can’t seem to find any examples of best practice.

alias: example
trigger:
  - id: 'on'
    platform: numeric_state
    entity_id: sensor.rv_humidity
    above: 45
    for:
      minutes: 10
  - id: 'off'
    platform: numeric_state
    entity_id: sensor.rv_humidity
    below: 45
condition: []
action:
  - service: 'switch.turn_{{ trigger.id }}'
    target:
      entity_id: switch.wp_10

Results in ‘Error: Template rendered invalid service: switch.turn_’

That does seem incredibly simple though.

How did you test the automation?

Did you simply click Run?

Reference: Testing your automation

To test it, the humidity value must increase from below 45 to above 45. The easiest way to simulate it is to go to Developer Tools> States, select sensor.rv_humidity, ensure its value is currently below 45, set its value to 50, then click the Set State button.

1 Like

How much can one guy learn in a short thread? All of it!

Thanks for the lesson, that was what I was looking for. I did just click on ‘run’ so the bonus lesson there is deeply appreciated too. Now I can go and rewrite all my other stuff using this.

:bowing_man:

2 Likes