Central: Services and characteristics

How to access services and characteristics included in BLE peripherals.

obniz.js automatically searches for services of the peripheral and characteristics and descriptors associated with it after the BLE connection is completed, and connecting to them is also completed just after searching finished, so it is possible to operate all services and below immediately.

Services

Services associated with peripherals (bleRemoteService) are stored in peripheral.services in the form of an a array. By using peripheral.getService(), you can get the services with a certain UUID contained in it.

// Javascript Full Example

var obniz = new Obniz("OBNIZ_ID_HERE");
obniz.onconnect = async function () {
  await obniz.ble.initWait(); 
  var target = {
      uuids: ["fff0"],
  };
  var peripheral = await obniz.ble.scan.startOneWait(target);
  if(!peripheral) {
      console.log('no such peripheral')
      return;
  }
  try {
    await peripheral.connectWait();
    console.log("connected");
    console.log("number of services=" + peripheral.services.length);
    var service = peripheral.getService("1800")
    if (!service) {
        console.log("service not found")
        return;
    }
    console.log(service.uuid) // => 1800
  } catch(e) {
    console.error(e);
  }
}

Characteristics

You can also get the characteristics associated with the services (bleRemoteCharacteristics) in a similar way. It is stored in service.characteristics as an array, and characteristic using UUID can be found by service.getCharacteristic().

// Javascript Full Example

var obniz = new Obniz("OBNIZ_ID_HERE");
obniz.onconnect = async function () {
  await obniz.ble.initWait(); 
  var target = {
      uuids: ["fff0"],
  };
  var peripheral = await obniz.ble.scan.startOneWait(target);
  if(!peripheral) {
      console.log('no such peripheral')
      return;
  }
  try {
    await peripheral.connectWait();
    console.log("connected");
    console.log("number of services=" + peripheral.services.length);
    var service = peripheral.getService("1800");
    var c = service.getCharacteristic("fff0");
    console.log(c.uuid); // => "fff0"
  } catch(e) {
    console.error(e);
  }
}