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

How to know which physical device is disconnected in disconnect event?

Here the connect method is called

err_code = 
	sd_ble_gap_connect(
		peer_addr, 
		&m_scan_params, 
		&m_connection_param, 
		APP_BLE_CONN_CFG_TAG);

In the ble event handler there is the event BLE_GAP_EVT_DISCONNECTED

static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
{

    // ... other events

	case BLE_GAP_EVT_DISCONNECTED:
	{
		NRF_LOG_INFO("LBS central link 0x%x disconnected (reason: 0x%x)",
		p_gap_evt->conn_handle,
		p_gap_evt->params.disconnected.reason);

		if (ble_conn_state_n_centrals() == 0)
		{
			err_code = app_button_disable();
			APP_ERROR_CHECK(err_code);

			// Turn off connection indication LED
			bsp_board_led_off(CENTRAL_CONNECTED_LED);
		}

		// Start scanning
		scan_start();

		// Turn on LED for indicating scanning
		bsp_board_led_on(CENTRAL_SCANNING_LED);

	} break;

	// ... other events

}

I'm wondering how I can know with some unique identifer which device is being discconected.

For example, I have my tablet connected to the NRF and also some other NRF peripherals.

So when tablet disconnects, BLE_GAP_EVT_DISCONNECTED case is triggered.

How can I know my tablet is discconected? I have tried parsing advertising data for device name, and I know first data element is device name.

I have added this code to the case statement

bool is_tablet = is_tablet_or_not(p_ble_evt);
if(is_tablet){
	log("is_tablet is true");
	tabletDisconnected = true;
} else {
	log("is_tablet is false");
	tabletDisconnected = false;
}

But advertisment data in is_tablet_or_not is not there anymore

static bool is_tablet_or_not(ble_evt_t const * p_ble_evt){
	
	log("is_tablet_or_not");

	ble_gap_evt_adv_report_t adv_report = 
	    p_ble_evt->evt.gap_evt.params.adv_report;

	int name_length = adv_report.data[1]; // idx 1 is type idx 2 is length

	logIntWithMessage("type is ",adv_report.data[0]);   // logs "type is 0" 
	logIntWithMessage("length is ",adv_report.data[1]); // logs "length is 0"

	char name[name_length];

	for(int i = 2; i < 2 + name_length; i++){
		name[i] = adv_report.data[i];
	}

	logStrWithMessage("name is ",name);
  
	// strcmp returns 0 when two strings are equal
	bool is_tablet_name = (strcmp(name,"Tablet") == 0);

	if(is_tablet_name){
		return true;
	} 
	else 
	{
		return false;
	}
}

Can I use advertisment data to parse for device name again, or can I used some other identifier to know if my tablet is disconnected?

Related