ikoza
ikoza

Reputation: 93

How to listen for BLE characteristic change with web bluetooth API?

I have a BLE scale I intend to use with bluetooth web API. With BLE scanner, I've managed to find the relevant service and characteristic UUID for the weight measuring. With that I was able to connect to the device, but I have no luck reading any value from the characteristic... it just disconnects after a few seconds. What do I do wrong? (config: android10, chrome 92.0.4515.131)

Here's the react code:

import { useState } from "react";

const App = () => {
  const [reading, setReading] = useState(null);
  const options = {
    primaryService: "0000780a-0000-1000-8000-00805f9b34fb",
    serviceCharacteristic: "00008aa2-0000-1000-8000-00805f9b34fb",
  };

  function handleScaleMeasurementCharacteristic(characteristic) {
    console.log(characteristic);
    console.log("Starting notifications...");
    return characteristic.startNotifications().then((char) => {
      console.log("Adding event listener...");
      char.addEventListener(
        "oncharacteristicvaluechanged",
        onCharacteristicValueChanged
      );
    });
  }

  const onCharacteristicValueChanged = (event) => {
    setReading(event.target.value.getUint8(0));
  };

  const onDisconnected = (event) => {
    console.log(`The device ${event.target.name} is disconnected`);
  };

  const onButtonClick = () => {
    navigator.bluetooth
      .requestDevice({
        filters: [{ services: [options.primaryService] }],
      })
      .then((device) => {
        device.addEventListener("gattserverdisconnected", onDisconnected);
        return device.gatt.connect();
      })
      .then((server) => server.getPrimaryService(options.primaryService))
      .then((service) => {
        service
          .getCharacteristic(options.serviceCharacteristic)
          .then(handleScaleMeasurementCharacteristic);
      });
  };

  return (
    <>
      <center style={{ paddingTop: 50 }}>
        {reading !== null ? (
          <h2>{reading}</h2>
        ) : (
          <button onClick={onButtonClick}>CONNECT TO SCALE</button>
        )}
      </center>
    </>
  );
};

export default App;

And here is the console log:

console log screenshot

Upvotes: 3

Views: 1365

Answers (1)

user18309290
user18309290

Reputation: 8300

Event type is characteristicvaluechanged. Using addEventListener method:

addEventListener('characteristicvaluechanged', event => { });

The same, but using the oncharacteristicvaluechanged event handler property:

oncharacteristicvaluechanged = event => { };

Upvotes: 0

Related Questions