esphome / issues

Issue Tracker for ESPHome
https://esphome.io/
291 stars 36 forks source link

BLE `on_connect` is triggerd before device is actually connected #4153

Open ithinkido opened 1 year ago

ithinkido commented 1 year ago

The problem

When setting up actions to run that are triggered by the on_connect trigger, it looks like the action is called before the connection is complete, resulting in the action running without being connected.

Which version of ESPHome has the issue?

v2022.12.8

What type of installation are you using?

pip

Which version of Home Assistant has the issue?

This is not connected to HA

What platform are you using?

ESP32

Board

ESD32 dev board

Component causing the issue

BLE client

Example YAML snippet

# Get current settings on discovery
ble_client:
  - mac_address: mac_address
    id: Pinecil
    on_connect:
      then:
        - lambda: |-
            ESP_LOGI("", "BLE CONNECTED", "");
        - delay: 1ms
        - lambda: |-
            ESP_LOGI("", "READING CURRENT SETTINGS","");
            id(GET_CURRENT_SETTING_TEMP).update();

....
...

  ## READ TEMP
sensor:
  - platform: ble_client
    type: characteristic
    ble_client_id: Pinecil
    id: GET_CURRENT_SETTING_SOLDERING_TEMP
    name: Current soldering temp setpoint
    service_uuid: f6d75f91-5a10-4eba-a233-47d3f26a907f
    characteristic_uuid: 00000001-0000-1000-8000-00805f9b34fb
    lambda: |-
      float value = (x[1] << 8) + x[0]; 
        if ( int(id(SET_VALUE_SOLDERING_TEMP).state) != int (value )){
          auto call = id(SET_VALUE_SOLDERING_TEMP).make_call();
          call.set_value(value);
          call.perform(); 
        }  
      return{value};
    update_interval: never # only update on connect
    notify: False

Anything in the logs that might be useful for us?

I have two attached log files, one with a delay after the  action is called and one without. Both logs are made using LOG_LEVEL = very verbose.

In these logs it can be seen that ESPhome is reporting "connected", but when trying to run the action, the script to get data from the device fails.   
With an additional delay added in - the action works as expected

Additional information

The issue can be resolved by adding a delay, any delay works, even 1ms. This patch solution works, but there seems to be a bug in the way the on_connect action is triggered. debug_no_delay.txt debug_with_delay.txt

github-actions[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.