[SOLVED] Get success or failure response from Bluetooth-le write

Issue

I’m using the Bluetooth-LE community plugin in a Ionic React project.

I’m writing a value to the GATT server with the following code:

await BleClient.write(device.deviceId, SERV_SYSTEM_SETTINGS, CHAR_RTC, dvDateTime );

This works fine except I need to be able to set a flag variable to indicate whether the write was a success or failure. Their is nothing in the docs to indicate how this can be done. However, their is also a

writeWithoutResponse(deviceId: string, service: string, characteristic: string, value: DataView, options?: TimeoutOptions | undefined) => Promise<void>

This implies that

write(deviceId: string, service: string, characteristic: string, value: DataView, options?: TimeoutOptions | undefined) => Promise<void>

Should return a success or failure response.

I’ve tried the rather newbish move of hoping the response could be caught in a variable as below, without success:

const writeFlag = await BleClient.write(device.deviceId, SERV_SYSTEM_SETTINGS, CHAR_RTC, dvDateTime );
console.log("WRITE FLAG: " + writeFlag);

However writeFlag remains undefined.

How do I get a response from the write process? I can manually check the GATT device and see that my write command is being received correctly by the device, but I need to be able to act upon this success/failure in code.

Any pointers/ suggestions will be greatly appreciated.

Thanks.

Solution

I need to be able to set a flag variable to indicate whether the write
was a success or failure. There is nothing in the docs to indicate how
this can be done.

You linked/shared right what the docs say is returned.

write(
  deviceId: string,
  service: string,
  characteristic: string,
  value: DataView,
  options?: TimeoutOptions | undefined
) => Promise<void>

It returns a Promise with no value, i.e. like a void return.

If the Promise resolves this means the write was a success, if it rejects this is a failure.

If you need to "capture" the success/failure, or rather the resolves/rejected status you can use a try/catch pattern.

Example:

try {
  await BleClient.write(
    device.deviceId,
    SERV_SYSTEM_SETTINGS,
    CHAR_RTC,
    dvDateTime
  );
  // success!
  // set any local success flag
} catch(error) {
  // failure, and error is likely undefined because void value
  // set any local non-success flag
}

Answered By – Drew Reese

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *