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

(Zephyr / NCS) Defining BLE scan data and advertising data during runtime

I have seen this question answered for the old Nordic SDK but have not been able to find a solution in Zephyr & NCS. I'm following this post on how to develop a custom BLE service in NCS. I see on step 5 they start the BLE advertising using the sd[] and ad[] arrays defined for compile time. However, I am generating my device's name during runtime using the onboard chip ID. I am using the following to set my name: 

	hwinfo_get_device_id(dev_uuid, sizeof(dev_uuid));

	name_holder[0] = 'h';
    name_holder[1] = '2';
    name_holder[2] = 'o';
    name_holder[3] = convertLowerNibleToChar( dev_uuid[3]);
    name_holder[4] = convertUpperNibleToChar( dev_uuid[4]);
    name_holder[5] = convertLowerNibleToChar( dev_uuid[4]);
    name_holder[6] = convertUpperNibleToChar( dev_uuid[5]);
    name_holder[7] = convertLowerNibleToChar( dev_uuid[5]);
	name_holder[8] = '\0';

	settings_runtime_set("bt/dis/serial", name_holder, sizeof(name_holder));
	
    bt_set_name(name_holder);

I want to include the device name in my advertising data and scan data arrays, but those properties are defined during compile time. How would update this information during the device's runtime?  

  • I solved this with the help of . You can dynamically update the sd and ad arrays at any time before advertising has started. My implementation is below: 

    	struct bt_data ad[] = {
    		BT_DATA_BYTES(BT_DATA_UUID128_ALL, HISTORY_SERVICE_UUID),
    		BT_DATA(BT_DATA_NAME_COMPLETE, name_holder, sizeof(name_holder)),
    	};
    
    	struct bt_data sd[] = {
    		BT_DATA(BT_DATA_NAME_COMPLETE, name_holder, sizeof(name_holder)),
    	};
    
    	//Start advertising
    	err = bt_le_adv_start(BT_LE_ADV_CONN, ad, ARRAY_SIZE(ad),
    			      sd, ARRAY_SIZE(sd));
    	if (err) 
    	{
    		printk("Advertising failed to start (err %d)\n", err);
    		return;
    	}
    
    	printk("Advertising successfully started\n");

Related