API on_client_connected automations not triggering after initial boot

I have a shelly I want to switch to normal mode (aka switch directly controls the relay instead of the bulbs) when it’s disconnected from the API. The on_client_connected actions all work when the device first boots, but afterward, if the API disconnects, it does not run the on_client_connected actions again.

I am using this yaml:

api:
  encryption:
    key: 
  on_client_disconnected:
    then:
      - lambda: |-
          id(light_mode_restore_value) = id(mode).state;
          id(light_mode_restore_sensor).publish_state(id(light_mode_restore_value));
          id(api_status).publish_state("API Disconnected");
      - select.set:
          id: mode
          option: "Normal Mode"
  on_client_connected:
    then:
      - lambda: |-
          ESP_LOGI("api", "Reconnected to HA, restoring mode: %s", id(light_mode_restore_value).c_str());
          id(api_status).publish_state("API Connected");
      - select.set: # Step 2: Set the select component to the saved value
          id: mode
          option: !lambda 'return id(light_mode_restore_value);' # Use the saved global value as the new option

I can still control the device with HA so I’m pretty sure the device isn’t still disconnected.

Any ideas?

So what’s the point then?

It’s not switching back to smart mode once the api connects again, so instead of the switch controlling the bulbs, it turns the relay on/off

I got confused. If it’s not disconnected, on_client_connected would eventually never trigger.

The on_client_disconnected is triggering:

Is it possible the api disconnect and reconnect is faster than the actions are triggering?

In fact I think there is some timing conflict. Also the whole documentation is confusing to me.

What about status sensor? You could build your automations on it.

binary_sensor:
  - platform: status
    name: "Living Room Connection"
    id: ha_connection
    
    on_press:
      - logger.log: "Connected to HA"
      
    on_release:
      - logger.log: "Disconnected from HA"

I think your correct.

I believe what is happening in the on_client_connected/disconnected is that when I go into, say the logs, it’s a connect/ disconnect, so when the log disconnects, it’s triggering the disconnect.

The automation under status sensor seems to be working thanks

Yep, because it detects any client connection like HA or dashboard.