nkolban / esp32-snippets

Sample ESP32 snippets and code fragments
https://leanpub.com/kolban-ESP32
Apache License 2.0
2.37k stars 710 forks source link

BLEDevice::getAddress() can't be used prior to init / no way to change device name after ::init() #1199

Open spbwgit opened 3 weeks ago

spbwgit commented 3 weeks ago

Perhaps not a common use case, but I was trying to embed the BT mac address in the name of my ESP32 device (ie. "gizmo-112233445566") when initializing BLEDevice, for uniqueness. Unfortunately, BLEDevice::getAddress() crashes if it's called before ::init().
Just a bit of a chicken and egg problem for my use case... It's entirely likely this is the desired behaviour -- ie. do not call getAddress() until after initialized.

In BLEDevice::getAddress(), there's a call to esp_bt_dev_get_address(), and this isn't allowed prior to calling esp_bluedroid_init(), which isn't invoked until BLEDevice::init(). I checked whether it's possible to call ::init() twice to update the device name, since there is no utility method to do so, however the call to esp_ble_gap_set_device_name() is within the if (!initialized){} block.

My workarounds for the moment could be: -call esp_bluedroid_init() prior to calling BLEDevice::getAddress(), since the function won't be called a second time. but it's possible btStart(), esp_bt_controller_enable() and others should be called first. I haven't looked too far into it. -find another way to get the mac prior to ::init(). e.g., with esp_read_mac(xxx, ESP_MAC_BT).

Anyhow.. just thought I'd mention that it'd be nice if there were an in-band way to either retrieve the mac in advance of init, or a way to set the name after the fact. Maybe this is an esoteric corner case though :)

chegewara commented 3 weeks ago

There is easier way to workaround this issue. You have espressif API to get mac address.

esp_read_mac(buf, ESP_MAC_BT);
spbwgit commented 3 weeks ago

Thanks @chegewara. Yes, that was the second workaround I mentioned. Works fine for me, and was kind of what my original code looked like, but then I noticed a getAddress() call and though I would try to not stray outside of the presented API... (then got bogged down for an hour tracking down the crash :) )