Restoring state from HA when API reconnects

I have an input_boolean that is used in an ESPHome script. I’m saving that state in a global to survive a reboot. That seems to work fine.

But if the input_boolean’s state changes while the ESP is disconnected it doesn’t refresh once the API reconnects. Is there a way, perhaps with on_boot for the ESP to get an updated state from HA?

I have a global to save the input_boolean state:

globals:
  - id: allowed
    type: bool
    restore_value: yes
    initial_value: "true"

And I set it like this:

binary_sensor:
  - platform: homeassistant
    name: "BinaryFrom HA"
    id: my_switch
    entity_id: input_boolean.my_switch
    on_state:
      - globals.set:
          id: allowed
          value: !lambda "return id(my_switch).state;"
      - logger.log: "Updated allowed state"

This seems to work as after a reboot (and still disconnected from the API) it will restore the last state.

But, when the API reconnects the state isn’t refreshed.

Again, if the input_boolean’s state changed while the API is disconnected it doesn’t seem like the ESP refreshes the state on reconnecting.

Is there a way to force that?

Try some on_boot automation like this:

esphome:
  on_boot:
    then:
      - wait_until:
          condition:
            api.connected
      - homeassistant.action:
          action: homeassistant.update_entity
          data:
            entity_id: input_boolean.my_switch
      - delay: 1s
      - lambda: |-
          id(allowed) = id(my_switch).state;
          ESP_LOGD("main","HA boolean synch =%d",id(allowed));

Not tested…

I just tried that. That’s asking the integration to immediately update the entity’s state in HA. When I run that action nothing is logged in the ESP’s logs.

But I figured out the issue. When the ESPHome reboots it must set its state of the entity as something like “unknown.” So, when the API reconnects it does send the current state of the entity to the ESP, but that doesn’t trigger on_state.

But using on_state_changed does trigger on the state change from the after-boot state of the entity in ESPHome.

Update: or setting the trigger_on_initial_state option.

Thanks.

I’m not sure if I follow you… So the on_boot I posted above doesn’t update the allowed, neither print the log line?

Sorry, I was saying calling the HA action homeassistant.update_entity doesn’t really do anything on the ESP – it’s not forcing an update. The update happens when the API reconnects.

Your lambda does work to copy the now-refreshed state to the global. And, well, I did ask about doing it in on_boot, but the real issue was on_state didn’t fire after a reboot when the ESP’s state for that entity was unknown. Just using on_state_changed allows it to trigger after the reboot.

So, yes, your code did also solve it.

Thanks!

Ok, understood now.
And nice catch on_state_changed. More simple and elegant.