dotintent / react-native-ble-plx

React Native BLE library
Apache License 2.0
3.08k stars 515 forks source link

iOS not sending all chunks #1241

Closed francesco-clementi-92 closed 1 month ago

francesco-clementi-92 commented 1 month ago

Prerequisites

Question

I don't think it's a bug, but I'm connecting with a thermal printer by bluetooth and I need to print a large chunk of data. On android everything is working fine, but on iOS only the first few chunks get printed. I'll provide soon the logs.

In the following code I get data to print, create a chunk of 20 and write each chunk to device. I read that iOS negotiates up to 187 byte MTU upon connection, but keeping to 20 should be safe.

Am I missing something?

Question related code

const print = async (data: string) => {
  const bufferLength = data.length;
  const maxChunkLength = 20;
  let chunk = 0;
  let base64String = '';

  const services = await BLEService.getServicesForDevice() as Service[];
  let found = false;
  for (const s of services) {
    const char = await BLEService.getCharacteristicsForDevice(s.uuid) as Characteristic[];

    for (const c of char) {
      if (c.isWritableWithoutResponse) {
        found = true;
        while (chunk < bufferLength) {
          base64String = data.slice(chunk, chunk + maxChunkLength);
          chunk += maxChunkLength;
          await BLEService.writeCharacteristicWithoutResponseForDevice(
            s.uuid,
            c.uuid,
            base64String
          );
        }
        break;
      }
    }
    if (found) {
      break;
    }
  }
};
francesco-clementi-92 commented 1 month ago

Fixed by adding a delay of 50 ms. Thanks for the amazing package