Reliable way to detect when a binary_sensor is synced with HA

I have a simple binary_sensor that I import from HA into EPSHome:

binary_sensor:
  - platform: homeassistant
    id: mcu_disable_sleep
    name: "Input boolean 'MCU Disable Sleep' from HA"
    entity_id: input_boolean.mcu_disable_sleep

How can I detect after boot when the value of this sensor is synced with HA?
In other words: How can I discriminate the false state of this sensor from the state before any API connection has been established?

Basically I need an event that is triggered when the ESPHome log shows the Sending initial state message:

[09:09:22][D][binary_sensor:034]: 'Input boolean 'MCU Disable Sleep' from HA': Sending initial state OFF

I tried the events on_press, on_release and on_state but none of them does fire when the state is synced with HA after a boot of the MCU.

I know that I can monitor the API connection state using the api.connected condition, but I am sick and tired of the fact that I cannot use the normal debug log anymore, when I use api.connected as the log connection also counts as API connected. So while debugging the API condition is worthless to tell me when the binary_sensor becomes reliable.

Also in serial/usb? Likely not, if I get ESPHome doc right.

Otherwise, I suspect a combination of publish_initial_state and on_state might work for you.

2 Likes

Chris, you are da man of da day! :smiley:

publish_initial_state: true is the solution of my problem. It enables the events that were not working for me on first API connect.

I did not try the serial/USB solution. As I understand it, it requires an FTDI adapter and thus would not work once the MCU is hidden in the wall and only accessible OTA.

THANKS !!!

And here is a quick code sample to show the solution:

  - platform: homeassistant
    id: mcu_disable_sleep
    name: "Input boolean 'MCU Disable Sleep' from HA"
    entity_id: input_boolean.mcu_disable_sleep
    publish_initial_state: true
    on_state:
      - logger.log: BINARY SENSOR ON_STATE HAS HAPPENED!
    on_press:
      - logger.log: BINARY SENSOR ON_PRESS HAS HAPPENED!
      - deep_sleep.prevent: my_deep_sleep
    on_release:
      - logger.log: BINARY SENSOR ON_RELEASE HAS HAPPENED!
      - component.update: sht_main
      - component.update: sht_dewpoint
      - delay: 1s  # make sure log and sensors updates are written before going to sleep
      - deep_sleep.allow: my_deep_sleep
1 Like