Peripheral: Notification of value change

When obniz is used as a BLE peripheral, other devices connect the obniz device via BLE and read or write values. The value can be rewritten by the device via BLE if it has write permission, or change by itself. However, just change the value is not enough and use Notify to tell the other party that the value has changed.

Notify changes

You can use the characteristic.notify() function to notify the connected device that a characteristic value has changed. The characteristics must have a property that allows Notify to be sent. To be specific, “notify” is necessary in property, and CCCD in descriptor. You have to set the CCCD in the descriptor item as follows when creating characteristics. It is also necessary that the connected party subscribe to receive the notify.

var obniz = new Obniz("OBNIZ_ID_HERE");
obniz.onconnect = async function () {

  await obniz.ble.initWait();
 // create servce & characteristics
  var service = new obniz.ble.service({ uuid : "1234" });
  var characteristic = new obniz.ble.characteristic({
    uuid : "7777",
    data: [1, 2, 3],
    properties : ["read","write","notify"],  // add notify properties
    descriptors: [
      {
        uuid: '2902', //CCCD
        data: [0x00, 0x00],  //2byte
      }, 
    ],
  });
  service.addCharacteristic(characteristic);
  obniz.ble.peripheral.addService(service);

  // advertisement
  obniz.ble.advertisement.setAdvData(service.advData);
  obniz.ble.advertisement.setScanRespData({
    localName : "obniz BLE",
  });
  obniz.ble.advertisement.start();

  // on connection
  obniz.ble.peripheral.onconnectionupdates = function(data){
    console.log("remote device ", data.address, data.status)

    setTimeout(async function(){
      await characteristic.writeWait([0xFF])
      characteristic.notify();
    }, 10000)
  };
}