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.