Writing characteritstic value using Web bluetooth API

Viewed 1589

I need to write a encrypted value to a characteristic of a BLE device using Web Bluetooth API. I can log the service and the characteristic. But I am unable to write the value.

We are referring a python script which can successfully write to the characteristic. The data written is encrypted and then converted to byte array and written to the characteristic.

We are trying to write the same value via javascript to the characteristic but we are getting NotSupportedError.

Can someone please help me figure out the solution?

Code:

     navigator.bluetooth
      .requestDevice({
        filters: [{ name: deviceName }],
        optionalServices: [GATT_SERVICE], 
      })
      .then((device) => {
        // Step 2: Connect to it
        console.log("device:", device);
        return device.gatt.connect();
      })
      .then((server) => {
        // Step 3: Get the Service
        console.log("server: ", server);
        return server.getPrimaryService(GATT_SERVICE);
      })
      .then((service) => {
        // Step 4: get the Characteristic
        console.log("service: ", service);
        
        return service.getCharacteristic(GATT_CHARACTERISTIC);
      })
      .then((characteristic) => {
       // data contains the value to be written to the BLE device
        writeBuffer(data, 0);

        function writeBuffer(data, start) {
          writeOut(data, start);
        }

        function writeOut(data, start) {
          if (start >= data.length) return;

          characteristic
            .writeValue(
              new TextEncoder().encode(data.substring(start, start + 20))
            )
            .then(() => {
              writeOut(data, start + 20);
            });
        }
     })
      .catch((error) => {
        console.log(error);
      });

Since the length is more than 512 bytes, I am taking a substring and trying to write the value.

2 Answers

If you manually connect your computer to the Bluetooth device before connecting via the web page does it work?

If you are using Chrome (or Chromium based browser) then this is likely because Chrome does not automatically pair on all operating systems. To read/write encrypted characteristics the Bluetooth device must be bonded with the computer. macOS and Android will bond when necessary, but Windows/Linux/ChromeOS do not. This should hopefully be corrected soon. You can follow https://crbug.com/960258 to track the progress of this work.

Related