I’m developing a simple toy on an ESP32 board (ESP-WROOM-32). I have this working development code for receiving messages via BLE.
#include <Arduino.h>
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
#define DEVICE_NAME "DUMMY_1"
#define UUID_SERVICE "..." // Generic Access UUID
#define UUID_CHARACTERISTIC "..." // Device Name UUID
BLECharacteristic *pCharacteristic;
class MyCallbacks : public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
std::string value = pCharacteristic->getValue();
Serial.print("Received data: ");
Serial.println(value.c_str());
}
};
class MyServerCallbacks : public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
Serial.println("Client connected");
}
void onDisconnect(BLEServer* pServer) {
Serial.println("Client disconnected");
// Restart advertising after disconnection
pServer->startAdvertising();
}
};
void setup() {
Serial.begin(115200);
BLEDevice::init(DEVICE_NAME);
BLEServer *pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
BLEService *pService = pServer->createService(UUID_SERVICE);
pCharacteristic = pService->createCharacteristic(
UUID_CHARACTERISTIC,
BLECharacteristic::PROPERTY_WRITE
);
pCharacteristic->setCallbacks(new MyCallbacks());
pService->start();
// BLESecurity *pSecurity = new BLESecurity();
// pSecurity->setStaticPIN(1234);
BLEAdvertising *pAdvertising = pServer->getAdvertising();
pAdvertising->start();
}
void loop() {
// Nothing in the loop
}
Now everyone can write to the characteristic. I would like to enable this only for bonded phones. The ESP32, however is just a box with a motor (on top of small toy car), it does not have any display, so I wanted to make a simple protection with static PIN.
The lines BLESecurity
are already present in the code, however uncommenting them does not work. My phone asks for PIN but when entered, it will be disconnected after ca. 30 seconds.
Any help or advice?