Pass an Object into a BLE Callback Function

rcarnemolla
Posts: 1
Joined: Tue Feb 14, 2023 9:14 pm

Pass an Object into a BLE Callback Function

Postby rcarnemolla » Tue Feb 14, 2023 10:15 pm

I am writing callbacks for the esp_ble_gatts_register_callback and esp_ble_gap_register_callback to be member functions of a new class, but they are static and I need to access the class's member objects inside the callbacks. I was hoping to pass the this pointer as an argument, but the register functions require specific structure. Is there any way to get member data into the callback?

My class:

Code: Select all

class BLEClass {
public:
    BLEClass(ISettings *settings) : settings(settings){}

    void initialize(void)
    {
        esp_err_t ret;

        ret = nvs_flash_init();
        esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
        ret = esp_bt_controller_init(&bt_cfg);
        ret = esp_bt_controller_enable(ESP_BT_MODE_BLE);
        ret = esp_bluedroid_init();
        ret = esp_bluedroid_enable();
        ret = esp_ble_gatts_register_callback(gatts_event_handler);
        ret = esp_ble_gap_register_callback(gap_event_handler);
        ret = esp_ble_gatts_app_register(PROFILE_A_APP_ID);

        esp_err_t local_mtu_ret = esp_ble_gatt_set_local_mtu(500);

        return;
    }
The register and callback headers:

Code: Select all

/**
 * @brief GAP callback function type
 * @param event : Event type
 * @param param : Point to callback parameter, currently is union type
 */
typedef void (* esp_gap_ble_cb_t)(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);

/**
 * @brief           This function is called to occur gap event, such as scan result
 *
 * @param[in]       callback: callback function
 *
 * @return
 *                  - ESP_OK : success
 *                  - other  : failed
 *
 */
esp_err_t esp_ble_gap_register_callback(esp_gap_ble_cb_t callback);

MicroController
Posts: 1710
Joined: Mon Oct 17, 2022 7:38 pm
Location: Europe, Germany

Re: Pass an Object into a BLE Callback Function

Postby MicroController » Thu Feb 16, 2023 5:59 pm

Apparently, there is no way to associate some user arg with the Bluetooth callbacks. However, given that there is only one Bluetooth peripheral present in the SoC, it wouldn't make much sense to have.
How about just using a global variable holding your object (singleton) and then just have the C-style callback functions call the appropriate member function(s) of that global object?

Who is online

Users browsing this forum: Bing [Bot] and 57 guests