I'd like to prevent multiple connections to my ESP32.
Is there a built-in way or a better way to do it?
My current implementation is as follows:
static volatile uint16_t connectionIdToKeep = -1;
class ServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
ble.log("ServerCallbacks: Connected");
const auto id = pServer->getConnId();
if (ble.deviceConnected) {
ble.alert("ServerCallbacks: Client %x is already connected! Disconnecting new one %x", connectionIdToKeep, id);
pServer->disconnect(id);
return;
}
connectionIdToKeep = id;
ble.deviceConnected = true;
ble.lastTimeDeviceConnectedInSeconds = millis()*1e-3;
ble.success("ServerCallbacks: Client %x is connected, welcome!", connectionIdToKeep);
#if SUPPORT_BUZZER
/// BLE connection jingle
buzzer.playBleConnectedMelody();
#endif
};
void onDisconnect(BLEServer* pServer) {
const auto id = pServer->getConnId();
/// Should I disconnect silently?
if (id != connectionIdToKeep) {
ble.warn("ServerCallbacks: Disconnected unwanted connection %x", id);
return;
}
ble.deviceConnected = false;
ble.success("ServerCallbacks: Disconnected");
#if SUPPORT_BUZZER
/// BLE connection jingle
buzzer.playBleDisconnectedMelody();
#endif
}
};