新增廣播內容 和 動態廣播
新增廣播內容。這種直接把內容廣播出去,發現者不必連線就能獲取資料。
媒介一:通過 ble_advdata_manuf_data_t (廣播內容新增MAC地址)
媒介二:通過 ble_advdata_service_data_t (新增動態廣播內容)
實現動態廣播的方法是:廣播->停止廣播->修改引數->重啟廣播
程式實現:
#define APP_COMPANY_IDENTIFIER 0x4D48
#define ADVDATA_BUFFER_SIZE 6
static uint8_t manuf_str[ADVDATA_BUFFER_SIZE] = {0};
static uint16_t manuf_str_len = 6;
#define SERVICE_UUID 0xB000
static uint8_t service_str[4] = {1,2,3,4};
static uint16_t service_str_len = 4;
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;
//get MAC
ble_gap_addr_t gap_address;
sd_ble_gap_address_get(&gap_address);
manuf_str[0] = gap_address.addr[5];
manuf_str[1] = gap_address.addr[4];
manuf_str[2] = gap_address.addr[3];
manuf_str[3] = gap_address.addr[2];
manuf_str[4] = gap_address.addr[1];
manuf_str[5] = gap_address.addr[0];
ble_advdata_manuf_data_t manuf_data;
manuf_data.company_identifier = APP_COMPANY_IDENTIFIER;
manuf_data.data.size = manuf_str_len;
manuf_data.data.p_data = manuf_str;
advdata.p_manuf_specific_data = &manuf_data;
ble_advdata_service_data_t service_data;
service_data.service_uuid = SERVICE_UUID;
service_data.data.p_data = service_str;
service_data.data.size = service_str_len;
advdata.p_service_data_array = &service_data;
advdata.service_data_count = 1;//可以多個,下面介紹
ble_advdata_t scanrsp;
memset(&scanrsp, 0, sizeof(scanrsp));
scanrsp.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
scanrsp.uuids_complete.p_uuids = m_adv_uuids;
scanrsp.p_tx_power_level = &tx_power_level;
ble_adv_modes_config_t options = {0};
options.ble_adv_fast_enabled = BLE_ADV_FAST_ENABLED;
options.ble_adv_fast_interval = APP_ADV_INTERVAL;
options.ble_adv_fast_timeout = APP_ADV_TIMEOUT_IN_SECONDS;
err_code = ble_advertising_init(&advdata, &scanrsp, &options, on_adv_evt, NULL);
APP_ERROR_CHECK(err_code);
service_str[3]++;//每次呼叫,陣列最後一個加1
}
int main(void)
{
uint32_t err_code;
APP_TIMER_INIT(APP_TIMER_PRESCALER, APP_TIMER_OP_QUEUE_SIZE, false);
ble_stack_init();
gap_params_init();
services_init();
advertising_init();
conn_params_init();
err_code = ble_advertising_start(BLE_ADV_MODE_FAST);
APP_ERROR_CHECK(err_code);
while(1)
{
power_manage();
}
}
執行程式,在手機nrf Master Control中可以發現廣播內容中多了 Manufacturer data 和 Service data
本實驗動態廣播通過按鍵事件觸發
每觸發一次按鍵事件,都發現Service data中的data[3]會加1
補充:廣播多個Service data 。由於直接廣播的資料只有 個,所以放到掃描迴應的方式廣播。
ble_advdata_service_data_t service_data[2];
service_data[0].service_uuid = SERVICE_UUID;
service_data[0].data.p_data = service_str;
service_data[0].data.size = service_str_len;
service_data[1].service_uuid = SERVICE_UUID;
service_data[1].data.p_data = service_str;
service_data[1].data.size = service_str_len;
scanrsp.p_service_data_array = service_data;
scanrsp.service_data_count = 2;