How to advertise a DYNAMIC name after the deprecation of BT_LE_ADV_CONN_NAME ?

To advertise a *configurable* device name the previous guidance seemed to be:

prj.conf

CONFIG_BT_DEVICE_NAME_DYNAMIC=y
Code Snippet
// Advertisement Data
static const struct bt_data ad[] = {
    BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
    BT_DATA_BYTES(BT_DATA_UUID128_ALL, BT_UUID_MY_SERVICE_VAL),
};

err = bt_enable(NULL);

err = bt_set_name("My New Name");

err = bt_le_adv_start(BT_LE_ADV_CONN_NAME, ad, ARRAY_SIZE(ad), NULL, 0);
Please note I have intentionally removed all error handling from the code snippet for brevity.
BT_LE_ADV_CONN_NAME and similar macros are now deprecated. It seems that the recommended solution is to manually add the name to the advertising data however you cannot reference bt_get_name() from ad[] so it is not clear how best to replace the deprecated macros and still user bt_set_name() and add the dynamic name to advertising data.
What is the recommended approach for this please?
  • Hello,

    the advertising data however you cannot reference bt_get_name() from ad[]

    To enable dynamic updates of the ad[] struct, remove the const keyword. This allows the app to modify the advertisement payload and call bt_le_adv_update_data() to update it on the fly.

    struct bt_data ad[] = {
    		BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
    		BT_DATA(BT_DATA_NAME_COMPLETE, DEVICE_NAME, DEVICE_NAME_LEN),
    };
    
    int main(void)
    {
        
        int counter = 0;
    	int len;
    	uint8_t dev_name[BT_GAP_ADV_MAX_ADV_DATA_LEN];
    
        ...
    
    	for (;;) {
    		k_msleep(1000);
    		len = sprintf(dev_name, "Hello_World_%d", counter);
    		printk("New device name %s. Len %d\n", dev_name, len);
    		err = bt_set_name(dev_name);
    		if (err) {
    			printk("bt_set_name() failed. (err %d)\n", err);
    		}
    		
    		/* Update adv. payload with new device name */
    		ad[1].data = dev_name;
    		ad[1].data_len = len;
    		ad[1].type = BT_DATA_NAME_COMPLETE;
    
    		err = bt_le_adv_update_data(ad, ARRAY_SIZE(ad), NULL, 0);
    		if (err) {
    			printk("bt_le_adv_update_data() failed. (err %d)\n", err);
    		}
    
    		counter++;
    	}
    	return 0;
    }

    Best regards,

    Vidar

    Edit: Please note that bt_set_name() will update the device name in BT settings (NV storage) if CONFIG_BT_SETTINGS is enabled. This can result in excessive flash usage if the name is updated too frequently. In that case, you may want to update the name only in the advertisement payload, without updating the attribute table.

Related