I have encountered a scenario in which my application is terminating the BLE connection via a call to sd_ble_gap_disconnect, while around the same time I receive a write request from a peer device. This write request is for a characteristic that has authorization permissions set, so a BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST is sent from the Soft Device; however this event comes before I receive a BLE_GAP_EVT_DISCONNECTED event (that I would expect once the connection termination has completed). When I call sd_ble_gatts_rw_authorize_reply to respond to the request (immediately after receiving it), I receive a NRF_ERROR_INVALID_STATE error. According to the API reference, this error message should only occur for "Invalid Connection State or no authorization request pending." In my case, the authorization request was definitely pending, so I can only assume that the Soft Device is returning the error because the BLE connection has been terminated.
My questions here are:
1. Is this situation possible? It would expect the Soft Device to have sent the BLE_GAP_EVT_DISCONNECTED to me first if the connection was terminated. Or is this some kind of race condition that can happen based on the timing of the call to sd_ble_gap_disconnect and the write request. Note that I am using a Bluetooth sniffer and also have some logging capabilities within my application, so I'm pretty sure that my analysis is correct.
2. Assuming that this situation is possible and my analysis, how should I handle this situation? My thought was this: in my application I can maintain a global state flag of the connected status that I set to FALSE as soon as I call sd_ble_gap_disconnect (as well as anytime a BLE_GAP_EVT_DISCONNECTED event occurs). When I receive the BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST and if this flag is set to FALSE then I can then simply ignore the event and not call sd_ble_gatts_rw_authorize_reply. Will any problems be caused by me not calling sd_ble_gatts_rw_authorize_reply?
Thanks!