capacitor-community/bluetooth-le

BleClient.write() does not respect offset and length of DataView

Closed this issue · 2 comments

Describe the bug
BleClient.write() sends all the data of the ArrayBuffer underlying the passed DataView argument. If the DataView is a view into only a section of that buffer, i.e. the DataView has a non-zero offset or a length that is shorter than the buffer's length, data is sent that is outside of the view's boundaries.

To Reproduce
Steps to reproduce the behavior:

  1. Create an ArrayBuffer
  2. Create a DataView into it with a non-zero offset and/or a length smaller than the buffer
  3. Send data with BleClient.write(device, service, characteristic, dataview)
const buffer = new ArrayBuffer(100)
const view = new DataView(buffer, 20, 10)
// the following will send all 100 bytes instead of the 10 bytes from byte 20 onward that the view points at
BleClient.write(device, service, characteristic, view)

Expected behavior
Only the data visible from the DataView is sent.

Plugin version:

  • @capacitor-community/bluetooth-le: 3.1.1

Smartphone (please complete the following information):

  • Device: Google Pixel 5
  • OS: Android 14
  • Browser: Capacitor WebView
  • Version: 5.5.0

Additional context
I've noticed this when writing a client for a GATT service that receives large-ish data transfers in chunks. I've kept a single ArrayBuffer with all the data and created DataViews for the individual chunks. This kept failing until I tried to copy the chunks into new ArrayBuffers and sending views into those.

While copying the data into new buffers is an acceptable workaround, I didn't expect this behavior, spent many hours debugging it and would like to spare others from this by fixing or documenting the behavior. I've looked into the plugin code and think this could be easily fixable by modifying dataViewToNumbers() (https://github.com/capacitor-community/bluetooth-le/blob/387dfa2d7099282ba89e718e6c8d5bd109078f45/src/conversion.ts#L11C1-L13C2).

Thank you for the issue and the detailed description. It was indeed an easy fix in dataViewToNumbers.

The fix is released with version 3.1.4.

Thank you very much! I'll upgrade to the new version as soon as I can. This library has helped me a lot in prototyping an app and I'm happy to make a small contribution back. 🙂