12.- Notify. Simple and didactic example.
- Notifications are well explained on this website:
https://openlabpro.com/guide/ble-notify-on-esp32-controller/
Important: each mobile device must have a CHARACTERISTIC_UUID. If you have multiple mobiles, set a CHARACTERISTIC_UUID for each one. You can generate UUID: https://www.uuidgenerator.net/
// Modified Juan A. Villalpando.
// http://kio4.com/arduino/160_Wemos_ESP32_BLE.htm
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
// Each client, mobile with a CHARACTERISTIC_UUID.
// Generate UUID: https://www.uuidgenerator.net/
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
//#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
#define CHARACTERISTIC_UUID "d6f841fa-a37d-11ea-bb37-0242ac130002"
BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;
int value = 0;
String valor = "";
// These functions will detect when the device is connected or disconnected.
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
};
void setup() {
Serial.begin(115200);
BLEDevice::init("MyESP32");
// Create BLE Server.
BLEServer *pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
// Create BLE Service with properties READ, WRITE, NOTIFY, INDICATE
BLEService *pService = pServer->createService(SERVICE_UUID);
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY |
BLECharacteristic::PROPERTY_INDICATE
);
// BLE descriptor.
pCharacteristic->addDescriptor(new BLE2902());
// Start BLE service.
pService->start();
// Start BLE advertising.
pServer->getAdvertising()->start();
}
void loop() {
if (deviceConnected) {
Serial.printf("*** NOTIFY: %d ***\n", value);
valor = (String) value;
pCharacteristic->setValue(valor.c_str()); // Set value.
pCharacteristic->notify(); // Notify value.
//pCharacteristic->indicate();
value++;
delay(800);
}
}
