主要代码
/**@brief Function for handling the Application‘s BLE Stack events. * * @param[in] p_ble_evt Bluetooth stack event. */ static void on_ble_evt(ble_evt_t * p_ble_evt) { switch (p_ble_evt->header.evt_id) { case BLE_GAP_EVT_CONNECTED: m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle; break; case BLE_GAP_EVT_DISCONNECTED: m_conn_handle = BLE_CONN_HANDLE_INVALID; // Set connection handle to 0xFFFF advertising_init();//利用这个函数底层调用sd_ble_gap_device_name_get函数来获取设备名称 advertising_start(); break; case BLE_GAP_EVT_TIMEOUT: if (p_ble_evt->evt.gap_evt.params.timeout.src == BLE_GAP_TIMEOUT_SRC_ADVERTISING) { advertising_start(); } break; default: // No implementation needed. break; } }
/**@brief Function for initializing the Advertising functionality. */ static void advertising_init(void) { uint32_t err_code; ble_advdata_t advdata; memset(&advdata, 0, sizeof(advdata)); advdata.name_type = BLE_ADVDATA_FULL_NAME; advdata.include_appearance = false; advdata.flags = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE; advdata.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]); advdata.uuids_complete.p_uuids = m_adv_uuids; err_code = ble_advdata_set(&advdata,NULL); APP_ERROR_CHECK(err_code); } /**@brief Function for starting advertising. */ static void advertising_start(void) { uint32_t err_code; ble_gap_adv_params_t adv_params; // Start advertising memset(&adv_params, 0, sizeof(adv_params)); adv_params.type = BLE_GAP_ADV_TYPE_ADV_IND; adv_params.p_peer_addr = NULL; adv_params.fp = BLE_GAP_ADV_FP_ANY; adv_params.interval = APP_ADV_INTERVAL; adv_params.timeout = APP_ADV_TIMEOUT_IN_SECONDS; err_code = sd_ble_gap_adv_start(&adv_params); APP_ERROR_CHECK(err_code); } /**@brief Function for stopping advertising. */ static void advertising_stop(void) { uint32_t err_code; err_code = sd_ble_gap_adv_stop(); APP_ERROR_CHECK(err_code); }
需要注意的原来的广播中预留可以作为设备名的大小长度。
时间: 2024-10-20 06:16:52