BleCharacteristic initialization in a class

The problem is that the BleCharacteristic callback is a BleOnDataReceivedCallback. Unlike some other classes, this unfortunately can’t take a C++ class instance directly so you need to implement it with two member functions, one static and one not.

// In BLEHandler class definition
void onDataReceived(const uint8_t* data, size_t len, const BlePeerDevice& peer);

static void onDataReceivedStatic(const uint8_t* data, size_t len, const BlePeerDevice& peer, void* context);

// Characteristic defnition
BleCharacteristic rxCharacteristic{"rx", BleCharacteristicProperty::WRITE_WO_RSP, rxUuid, serviceUuid, onDataReceivedStatic, this};

The implementation of the static member function looks like this:

void BLEHandler::onDataReceivedStatic(const uint8_t* data, size_t len, const BlePeerDevice& peer, void* context) 
{
    BLEHandler *handler = (BLEHandler *)context;
    handler->onDataReceived(data, len, peer); 
}

What you’re doing is saving a pointer to this in the context. In order to call a non-static class member you need not only the function, but which instance of it, which the onDataReceivedStatic function does by getting it from the context.

4 Likes