添加广播内容。这种直接把内容广播出去,发现者不必连接就能获取数据。
媒介一:通过 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;