ESP32 BLE set bool to TRUE onNotify and FALSE when notifyStop

Hello,

Been scratching my head over this one for a few days. I can send a notify and notify-stop callback to my ESP32 from a BLE app I’m making, but I don’t know how to work with it ESP32-side. All I want is to change the device to start the program when the NOTIFY characteristic is called, when the app calls the BluetoothGatt.writeDescriptor(PROPERTY_NOTIFY) rather than the default onConnect provided in the ESP32_notify example. I can achieve this by using a built-in callback to switch a bool to true/false just like with the onConnect callback, but I don’t understand how to do it. This is for an open hardware project, please help!

ESP32 Notify example:

/*
    Video: https://www.youtube.com/watch?v=oCMOYS71NIU
    Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp
    Ported to Arduino ESP32 by Evandro Copercini

   Create a BLE server that, once we receive a connection, will send periodic notifications.
   The service advertises itself as: 4fafc201-1fb5-459e-8fcc-c5c9c331914b
   And has a characteristic of: beb5483e-36e1-4688-b7f5-ea07361b26a8

   The design of creating the BLE server is:
   1. Create a BLE Server
   2. Create a BLE Service
   3. Create a BLE Characteristic on the Service
   4. Create a BLE Descriptor on the characteristic
   5. Start the service.
   6. Start advertising.

   A connect hander associated with the server starts a background task that performs notification
   every couple of seconds.
*/
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint8_t value = 0;

// See the following for generating UUIDs:
// https://www.uuidgenerator.net/

#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"


class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
    };

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
    }
};



void setup() {
  Serial.begin(115200);

  // Create the BLE Device
  BLEDevice::init("MyESP32");

  // Create the BLE Server
  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());

  // Create the BLE Service
  BLEService *pService = pServer->createService(SERVICE_UUID);

  // Create a BLE Characteristic
  pCharacteristic = pService->createCharacteristic(
                      CHARACTERISTIC_UUID,
                      BLECharacteristic::PROPERTY_READ   |
                      BLECharacteristic::PROPERTY_WRITE  |
                      BLECharacteristic::PROPERTY_NOTIFY |
                      BLECharacteristic::PROPERTY_INDICATE
                    );

  // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
  // Create a BLE Descriptor
  pCharacteristic->addDescriptor(new BLE2902());

  // Start the service
  pService->start();

  // Start advertising
  pServer->getAdvertising()->start();
  Serial.println("Waiting a client connection to notify...");
}

void loop() {
    // notify changed value
    if (deviceConnected) {
        pCharacteristic->setValue(&value, 1);
        pCharacteristic->notify();
        value++;
        delay(10); // bluetooth stack will go into congestion, if too many packets are sent
    }
    // disconnecting
    if (!deviceConnected && oldDeviceConnected) {
        delay(500); // give the bluetooth stack the chance to get things ready
        pServer->startAdvertising(); // restart advertising
        Serial.println("start advertising");
        oldDeviceConnected = deviceConnected;
    }
    // connecting
    if (deviceConnected && !oldDeviceConnected) {
        // do stuff here on connecting
        oldDeviceConnected = deviceConnected;
    }
}

These are the Bluetooth functions from the nativescript-bluetooth package

Bluetooth.startNotifying = function (arg) {
  return new Promise(function (resolve, reject) {
    try {
      var wrapper = Bluetooth._getWrapper(arg, reject);
      if (wrapper === null) {
        // no need to reject, this has already been done
        return;
      }

      var gatt = wrapper.gatt;
      var bluetoothGattService = wrapper.bluetoothGattService;
      var characteristicUUID = Bluetooth._stringToUuid(arg.characteristicUUID);

      var bluetoothGattCharacteristic = Bluetooth._findNotifyCharacteristic(bluetoothGattService, characteristicUUID);
      if (!bluetoothGattCharacteristic) {
        reject("Could not find characteristic with UUID " + arg.characteristicUUID + " on service with UUID " + arg.serviceUUID + " on peripheral with UUID " + arg.peripheralUUID);
        return;
      }

      if (!gatt.setCharacteristicNotification(bluetoothGattCharacteristic, true)) {
        reject("Failed to register notification for characteristic " + arg.characteristicUUID);
        return;
      }

      var clientCharacteristicConfigId = Bluetooth._stringToUuid("2902");
      var bluetoothGattDescriptor = bluetoothGattCharacteristic.getDescriptor(clientCharacteristicConfigId);
      if (!bluetoothGattDescriptor) {
        bluetoothGattDescriptor = new android.bluetooth.BluetoothGattDescriptor(clientCharacteristicConfigId, android.bluetooth.BluetoothGattDescriptor.PERMISSION_WRITE);
        bluetoothGattCharacteristic.addDescriptor(bluetoothGattDescriptor);
        console.log("BluetoothGattDescriptor created...");
        //Any creation error will trigger the global catch. Ok.
      }

      // prefer notify over indicate
      if ((bluetoothGattCharacteristic.getProperties() & android.bluetooth.BluetoothGattCharacteristic.PROPERTY_NOTIFY) !== 0) {
        bluetoothGattDescriptor.setValue(android.bluetooth.BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
      } else if ((bluetoothGattCharacteristic.getProperties() & android.bluetooth.BluetoothGattCharacteristic.PROPERTY_INDICATE) !== 0) {
        bluetoothGattDescriptor.setValue(android.bluetooth.BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
      } else {
        reject("Characteristic " + characteristicUUID + " does not have NOTIFY or INDICATE property set");
        return;
      }

      if (gatt.writeDescriptor(bluetoothGattDescriptor)) {
        var cb = arg.onNotify || function (result) {
          console.log("No 'onNotify' callback function specified for 'startNotifying'");
        };
        var stateObject = Bluetooth._connections[arg.peripheralUUID];
        stateObject.onNotifyCallback = cb;
        console.log("--- notifying");
        resolve();
      } else {
        reject("Failed to set client characteristic notification for " + characteristicUUID);
      }
    } catch (ex) {
      console.log("Error in Bluetooth.startNotifying: " + ex);
      reject(ex);
    }
  });
};

// TODO lot of reuse between this and .startNotifying
Bluetooth.stopNotifying = function (arg) {
  return new Promise(function (resolve, reject) {
    try {
      var wrapper = Bluetooth._getWrapper(arg, reject);
      if (wrapper === null) {
        // no need to reject, this has already been done
        return;
      }

      var gatt = wrapper.gatt;
      var bluetoothGattService = wrapper.bluetoothGattService;
      var characteristicUUID = Bluetooth._stringToUuid(arg.characteristicUUID);

      var bluetoothGattCharacteristic = Bluetooth._findNotifyCharacteristic(bluetoothGattService, characteristicUUID);
      console.log("---- got gatt service char: " + bluetoothGattCharacteristic);

      if (!bluetoothGattCharacteristic) {
        reject("Could not find characteristic with UUID " + arg.characteristicUUID + " on service with UUID " + arg.serviceUUID + " on peripheral with UUID " + arg.peripheralUUID);
        return;
      }

      var stateObject = Bluetooth._connections[arg.peripheralUUID];
      stateObject.onNotifyCallback = null;

      if (gatt.setCharacteristicNotification(bluetoothGattCharacteristic, false)) {
        resolve();
      } else {
        reject("Failed to remove client characteristic notification for " + characteristicUUID);
      }

    } catch (ex) {
      console.log("Error in Bluetooth.stopNotifying: " + ex);
      reject(ex);
    }
  });
};

bump