How to automate a relay using esp32 ble tracker on presence detection?

I have installed ESPHome and added an esp32 to it. Then by using esp32_ble_tracker, I tracked the presence of my xiaomi band 4. Now I have a relay that is attached to pin number 27 of the same esp32. I have added a relay as a switch as can be seen in my esp32.yaml file attached below. I can manually turn/switch the relay ON/OFF, however I want to switch on my relay as soon esp32_ble_tracker detect the presence of my mi band 4. I believe it can be done by using some conditional statement with the binary sensor, however, I am unable to achieve it. Please help me.

my esp32.yaml file

esphome:
  name: esp32
  platform: ESP32
  board: nodemcu-32s

wifi:
  ssid: "BigPond0D15"
  password: "8438544242"

captive_portal:

# Enable logging
logger:

esp32_ble_tracker:

binary_sensor:
  - platform: ble_presence
    mac_address: E1:00:9D:XX:XX:XX
    name: "miBand4"
    id: blesensor
      
switch:
  - platform: gpio
    name: "Relay"
    pin: GPIO27
    id: relaySwitch
binary_sensor:
  - platform: ble_presence
    mac_address: E1:00:9D:XX:XX:XX
    name: "miBand4"
    id: blesensor
    on_state: 
      if:
        condition:
          binary_sensor.is_on: blesensor
        then:   
          - switch.turn_on: relaySwitch
        else:  
          - switch.turn_off: relaySwitch

That’s not working. relay is not switching off once i move out of home.

**I want to switch on my relay** as soon esp32_ble_tracker detect the presence of my mi band 4

The code was doing exactly what you said you want.
I edited it to also turn it off once the presence detection is off.

Enjoy!

Thanks @chelule It worked :slight_smile:

Hello. What devices do they use? What is the cheapest esp32 that you recommend to use that can communicate by mqtt to notify the presence? Thank you