What am I doing wrong? - Condition -

binary_sensor:
  - platform: gpio
    pin:
      number: GPIO4
    name: "Cat repellor 1 PIR"
    id: pir
    device_class: motion
    on_press:
      if:
        condition:
          switch.is_off: switch.sonar
      then:
        - switch.turn_on: sonar
        - delay: 10s
        - switch.turn_off: sonar

switch:
  - platform: gpio
    name: "Cat repellor 1 Switch"
    id: sonar
    pin:
      number: GPIO27
      inverted: False

I aim to turn on (and 10 seconds later off) the switch only if the current state of the switch is off.

I’m getting this error:

INFO Reading configuration...
Failed config

binary_sensor.gpio: [source /config/esphome/esp32dev01.yaml:40]
  platform: gpio
  pin: 
    number: GPIO4
  name: Cat repellor 1 PIR
  id: pir
  device_class: motion
  on_press:  [source /config/esphome/esp32dev01.yaml:47]
    
    [if] is an invalid option for [on_press]. Please check the indentation.
    if:  [source /config/esphome/esp32dev01.yaml:48]
      condition: 
        switch.is_off: switch.sonar
    then: 
      - switch.turn_on: 
          id: sonar
      - delay: 10s
      - switch.turn_off: 
          id: sonar
```

Check docs of if
You do on… then … if … then (again)

I tried many combinations before posting my question…

  - platform: gpio
    pin:
      number: GPIO4
    name: "Cat repellor 1 PIR"
    id: pir
    device_class: motion
    on_press:
      then:
        if:
          condition:
          # Same syntax for is_off
            switch.is_off: switch.sonar
        then:
          - switch.turn_on: sonar
          - delay: 10s
          - switch.turn_off: sonar
NFO Reading configuration...
Failed config

binary_sensor.gpio: [source /config/esphome/esp32dev01.yaml:40]
  platform: gpio
  pin: 
    number: GPIO4
  name: Cat repellor 1 PIR
  id: pir
  device_class: motion
  on_press:  [source /config/esphome/esp32dev01.yaml:47]
    
    Cannot have two actions in one item. Key 'if' overrides 'then'! Did you forget to indent the block inside the action?.
    then:  [source /config/esphome/esp32dev01.yaml:48]
      if: 
        condition: 
          switch.is_off: switch.sonar
      then: 
        - switch.turn_on: sonar
        - delay: 10s
        - switch.turn_off: sonar

Condition and the last then should be idented at same level

1 Like

Thanks, that works!