This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

Proper way to wait for events

I'm trying to establish a bond in my project and then perform service discovery, however the discovery is returning the BUSY error.

I tried to wait for the events according to the documentation but they will never trigger so long as I have the while(bondPending){} statement there because the events are part of the same interrupt.

What's the proper way to perform two actions (dm_security_setup_req() & ble_db_discovery_start() in this case) sequentially, while waiting for an event between the two?

    /* Perform bonding upon connection */
bondPending = 1;
err_code = dm_security_setup_req(&m_dm_device_handle);
APP_ERROR_CHECK(err_code);

while(bondPending){}

// Discover peer's services. 
err_code = ble_db_discovery_start(&m_ble_db_discovery, p_event->event_param.p_gap_param->conn_handle);
APP_ERROR_CHECK(err_code);

case DM_EVT_SECURITY_SETUP_COMPLETE:
    bondPending = 0;
    APPL_LOG("[APPL]: >> DM_EVT_SECURITY_SETUP_COMPLETE\r\n");
    // Heart rate service discovered. Enable notification of Heart Rate Measurement.
    err_code = ble_hrs_c_hrm_notif_enable(&m_ble_hrs_c);
    APP_ERROR_CHECK(err_code);
    APPL_LOG("[APPL]: << DM_EVT_SECURITY_SETUP_COMPLETE\r\n");
    break;

case DM_EVT_LINK_SECURED:
    bondPending = 0;
    APPL_LOG("[APPL]: >> DM_LINK_SECURED_IND\r\n");
    APPL_LOG("[APPL]: << DM_LINK_SECURED_IND\r\n");
    break;
  • dm_security_setup_req calls sd_ble_gap_encrypt This is what I read from the header file ble_gap.h->sd_ble_gap_encrypt

    • @retval ::NRF_ERROR_BUSY Procedure already in progress or not allowed at this time, wait for pending procedures to complete and retry.

    It says that just waiting is not enough, you need to retry again

    You can start a timer instead of WHILE and check for the bondPending flag in the timer callback and call dm_security_setup_req again. That should be safe way to do this. There are few examples in SDK that do it this way (ble_app_ancs_c for example), how much time you app can wait is app specific, I recommend you to wait few connection intervals until the possibility of security setup failure is excluded.

Related