ESPHome with deep sleep and a switch

Hello,
I am currently trying to create a smart switch with an ESP32 board. This ESP will later on be battery powered, so I need the device to go into deep sleep. Therefore, I created the yaml file below for the ESPHome on the ESP32.
My problem now is that everything works perfectly if I have the deep sleep part disabled (as currently done in the config file) but as soon as I enable it, the switch can’t be switched inside home assistant except if you hit exactly the 2s window where the switch/ESP is online.
Can anyone help me out on how I can fix this so that I can hit the switch inside home assistant whenever I like and as soon as the ESP32 wakes up, it will act accordingly.
Thanks!

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

# Enable logging
logger:

ota:
  password: "abcd"

wifi:
  ssid: "myInternetSSID"
  password: "abcd"
  fast_connect: true

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "christmasdecoration"
    password: "abcd"

captive_portal:

switch:
  - platform: gpio
    id: switch_pin_14
    name: "Christmas Decoration"
    pin: 14
    on_turn_on:
    - logger.log: "Switch Turned On!"
    on_turn_off:
    - logger.log: "Switch Turned Off!"

# deep_sleep:
#   id: deep_sleep_1
#   run_duration: 2s
#   sleep_duration: 30s

mqtt:
  broker: 192.168.1.2
  username: mosquitto
  password: abcd
  discovery: true
  birth_message:
  will_message:
  on_message:
    # - topic: christmasdecoration/ota_mode
    #   payload: 'ON'
    #   then:
    #     - deep_sleep.prevent: deep_sleep_1
    # - topic: christmasdecoration/sleep_mode
    #   payload: 'ON'
    #   then:
    #     - deep_sleep.enter: deep_sleep_1
    - topic: christmasdecoration
      payload: 'ON'
      then:
        - switch.turn_on: switch_pin_14
    - topic: christmasdecoration
      payload: 'OFF'
      then:
        - switch.turn_off: switch_pin_14
    

Hello
I think that it is normal since when the ESP is in deep-sleep, there is no more wifi.
And then no connection is possible with home-assistant

Hi, I can’t imagine that this is the way to go. It would be completely useless this way. Also since MQTT is a publish-subscribe network, it should in theory fix the no-wifi problem (at least in my case).

Look at the retain flag. By default, in HA, it is not enabled. So, HA published to MQTT and even if esphome is not connected, then the message is dropped by the broker.
If retain is set to true, the broker will keep the last message on the topic until someone gets it.

Aaah thank you very much! That’s exactly what I was looking for! I was thinking in the wrong direction since this was not an esphome issue but rather a wrong config in the HA part.