@onekeyfe/hd-transport-react-native 1.2.0-alpha.16 → 1.2.0-alpha.161

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -93,7 +93,8 @@ const onDeviceBondState = (bleMacAddress) => new Promise((resolve, reject) => {
93
93
 
94
94
  const IOS_PACKET_LENGTH = 128;
95
95
  const ANDROID_PACKET_LENGTH = 192;
96
- const ANDROID_DEFAULT_MTU = 23;
96
+ const IOS_PROTOCOL_V2_PACKET_LENGTH = 244;
97
+ const ANDROID_PROTOCOL_V2_PACKET_LENGTH = 244;
97
98
  const ClassicServiceUUID = '00000001-0000-1000-8000-00805f9b34fb';
98
99
  const OneKeyServices = {
99
100
  classic: {
@@ -117,36 +118,38 @@ const getInfosForServiceUuid = (serviceUuid, deviceType) => {
117
118
  return null;
118
119
  }
119
120
  const normalizedServiceUuid = normalizeBleUuid(serviceUuid);
120
- const service = (_a = services[serviceUuid]) !== null && _a !== void 0 ? _a : Object.values(services).find(item => normalizeBleUuid(item.serviceUuid) === normalizedServiceUuid);
121
+ const service = (_a = services[serviceUuid]) !== null && _a !== void 0 ? _a : Object.values(services).find(item => normalizeBleUuid(item.serviceUuid) === normalizedServiceUuid ||
122
+ hdShared.matchesKnownBleUuid(serviceUuid, hdShared.createKnownBleUuidAliases(item.serviceUuid)));
121
123
  if (!service) {
122
124
  return null;
123
125
  }
124
126
  return service;
125
127
  };
126
128
  const normalizeBleUuid = (uuid) => (uuid !== null && uuid !== void 0 ? uuid : '').replace(/-/g, '').toLowerCase();
127
- const getBleUuidKey = (uuid) => {
128
- const normalized = normalizeBleUuid(uuid);
129
- return normalized.length >= 8 ? normalized.substring(4, 8) : normalized;
130
- };
131
129
  const isSameBleUuid = (left, right) => {
132
- const normalizedLeft = normalizeBleUuid(left);
133
- const normalizedRight = normalizeBleUuid(right);
134
- return (normalizedLeft === normalizedRight ||
135
- (getBleUuidKey(left) !== '' && getBleUuidKey(left) === getBleUuidKey(right)));
130
+ if (!left || !right)
131
+ return false;
132
+ return hdShared.matchesKnownBleUuid(left, hdShared.createKnownBleUuidAliases(right));
136
133
  };
137
134
 
138
135
  function hasWritableCapability(characteristic) {
139
136
  return !!(characteristic.isWritableWithResponse || characteristic.isWritableWithoutResponse);
140
137
  }
141
- function resolveProtocolV2PacketCapacity({ platform, iosPacketLength = IOS_PACKET_LENGTH, androidPacketLength = ANDROID_PACKET_LENGTH, mtu, }) {
142
- if (platform === 'ios') {
143
- return iosPacketLength;
144
- }
145
- if (platform === 'android') {
146
- const payloadLength = Math.max((mtu !== null && mtu !== void 0 ? mtu : ANDROID_DEFAULT_MTU) - 3, 1);
147
- return Math.min(androidPacketLength, payloadLength);
148
- }
149
- return androidPacketLength;
138
+ function resolveProtocolV2PacketCapacity({ platform, iosPacketLength = IOS_PROTOCOL_V2_PACKET_LENGTH, androidPacketLength = ANDROID_PROTOCOL_V2_PACKET_LENGTH, mtu, }) {
139
+ const negotiatedMtu = typeof mtu === 'number' && Number.isFinite(mtu) && mtu > 3 ? Math.floor(mtu) : 23;
140
+ const payloadLength = negotiatedMtu - 3;
141
+ const configuredPacketLength = platform === 'ios' ? iosPacketLength : androidPacketLength;
142
+ return Math.min(configuredPacketLength, payloadLength);
143
+ }
144
+ function shouldRefreshNegotiatedMtu(mtu) {
145
+ return typeof mtu !== 'number' || !Number.isFinite(mtu) || mtu <= 23;
146
+ }
147
+ function shouldWriteProtocolV2WithResponse({ platform, highThroughput, requestedWithResponse, characteristic, }) {
148
+ if (!characteristic.isWritableWithResponse)
149
+ return false;
150
+ if (!characteristic.isWritableWithoutResponse)
151
+ return true;
152
+ return requestedWithResponse === true || (platform === 'ios' && !highThroughput);
150
153
  }
151
154
 
152
155
  const timer = process.env.NODE_ENV === 'development'
@@ -203,59 +206,20 @@ const isHeaderChunk = (chunk) => {
203
206
  return false;
204
207
  };
205
208
 
206
- const Log$1 = bleLogger;
207
209
  class BleTransport {
208
210
  constructor(device, writeCharacteristic, notifyCharacteristic) {
209
211
  this.name = 'ReactNativeBleTransport';
210
- this.mtuSize = 23;
211
212
  this.id = device.id;
212
213
  this.device = device;
213
214
  this.writeCharacteristic = writeCharacteristic;
214
215
  this.notifyCharacteristic = notifyCharacteristic;
215
216
  }
216
- writeWithRetry(data, retryCount = BleTransport.MAX_RETRIES) {
217
+ writeWithRetry(data) {
217
218
  return __awaiter(this, void 0, void 0, function* () {
218
- try {
219
- yield this.writeCharacteristic.writeWithoutResponse(data);
220
- }
221
- catch (error) {
222
- Log$1 === null || Log$1 === void 0 ? void 0 : Log$1.debug(`Write retry attempt ${BleTransport.MAX_RETRIES - retryCount + 1}, error: ${error}`);
223
- if (retryCount > 0) {
224
- yield hdShared.wait(BleTransport.RETRY_DELAY);
225
- if (error.errorCode === reactNativeBlePlx.BleErrorCode.DeviceDisconnected ||
226
- error.errorCode === reactNativeBlePlx.BleErrorCode.CharacteristicNotFound) {
227
- try {
228
- yield this.device.connect();
229
- yield this.device.discoverAllServicesAndCharacteristics();
230
- }
231
- catch (e) {
232
- Log$1 === null || Log$1 === void 0 ? void 0 : Log$1.debug(`Connect or discoverAllServicesAndCharacteristics error: ${e}`);
233
- }
234
- }
235
- else {
236
- Log$1 === null || Log$1 === void 0 ? void 0 : Log$1.debug(`writeCharacteristic error: ${error}`);
237
- }
238
- return this.writeWithRetry(data, retryCount - 1);
239
- }
240
- throw error;
241
- }
219
+ yield this.writeCharacteristic.writeWithoutResponse(data);
242
220
  });
243
221
  }
244
222
  }
245
- BleTransport.MAX_RETRIES = 5;
246
- BleTransport.RETRY_DELAY = 2000;
247
-
248
- function createTransportCallLog(name, protocol, data) {
249
- if (name === 'ResourceUpdate' || name === 'ResourceAck') {
250
- return {
251
- name,
252
- protocol,
253
- file_name: data.file_name,
254
- hash: data.hash,
255
- };
256
- }
257
- return { name, protocol };
258
- }
259
223
 
260
224
  const { check, ProtocolV1, parseConfigure } = transport__default["default"];
261
225
  const Log = bleLogger;
@@ -264,10 +228,35 @@ const FIRMWARE_UPLOAD_WRITE_BURST_SIZE = reactNative.Platform.OS === 'ios' ? 4 :
264
228
  const FIRMWARE_UPLOAD_WRITE_PAUSE_MS = reactNative.Platform.OS === 'ios' ? 8 : 10;
265
229
  const FIRMWARE_UPLOAD_WRITE_FLUSH_DELAY_MS = reactNative.Platform.OS === 'ios' ? 24 : 30;
266
230
  const FIRMWARE_UPLOAD_WRITE_MAX_RETRIES = 8;
267
- const FIRMWARE_UPLOAD_RECONNECT_RETRY_DELAY_MS = 2000;
268
231
  const ANDROID_FIRMWARE_UPLOAD_PACKET_LENGTH = 192;
269
232
  const FIRMWARE_UPLOAD_WRITE_PACKET_CAPACITY = reactNative.Platform.OS === 'ios' ? IOS_PACKET_LENGTH : ANDROID_FIRMWARE_UPLOAD_PACKET_LENGTH;
270
233
  const ANDROID_GATT_CONGESTED_STATUS = 143;
234
+ const isAsciiWhitespace = (code) => code === 0x09 ||
235
+ code === 0x0a ||
236
+ code === 0x0b ||
237
+ code === 0x0c ||
238
+ code === 0x0d ||
239
+ code === 0x20;
240
+ const hasGattCongestedStatus = (text) => {
241
+ let searchFrom = 0;
242
+ while (searchFrom < text.length) {
243
+ const statusIndex = text.indexOf('status', searchFrom);
244
+ if (statusIndex < 0)
245
+ return false;
246
+ let cursor = statusIndex + 'status'.length;
247
+ while (cursor < text.length && isAsciiWhitespace(text.charCodeAt(cursor)))
248
+ cursor += 1;
249
+ if (text[cursor] === ':' || text[cursor] === '=') {
250
+ cursor += 1;
251
+ while (cursor < text.length && isAsciiWhitespace(text.charCodeAt(cursor)))
252
+ cursor += 1;
253
+ }
254
+ if (text.startsWith(String(ANDROID_GATT_CONGESTED_STATUS), cursor))
255
+ return true;
256
+ searchFrom = statusIndex + 'status'.length;
257
+ }
258
+ return false;
259
+ };
271
260
  const delay = (ms) => new Promise(resolve => {
272
261
  setTimeout(resolve, ms);
273
262
  });
@@ -275,10 +264,6 @@ const getFirmwareUploadWriteRetryType = (error) => {
275
264
  if (!error || typeof error !== 'object')
276
265
  return null;
277
266
  const bleWriteError = error;
278
- if (bleWriteError.errorCode === reactNativeBlePlx.BleErrorCode.DeviceDisconnected ||
279
- bleWriteError.errorCode === reactNativeBlePlx.BleErrorCode.CharacteristicNotFound) {
280
- return 'reconnectable';
281
- }
282
267
  if (bleWriteError.androidErrorCode === ANDROID_GATT_CONGESTED_STATUS ||
283
268
  bleWriteError.status === ANDROID_GATT_CONGESTED_STATUS) {
284
269
  return 'congested';
@@ -286,18 +271,24 @@ const getFirmwareUploadWriteRetryType = (error) => {
286
271
  const text = [bleWriteError.reason, bleWriteError.message, bleWriteError.name]
287
272
  .filter(value => typeof value === 'string')
288
273
  .join(' ');
289
- return /GATT_CONGESTED|status\s*[:=]?\s*143/.test(text) ? 'congested' : null;
274
+ return text.includes('GATT_CONGESTED') || hasGattCongestedStatus(text) ? 'congested' : null;
290
275
  };
291
276
  const resolveFirmwareUploadRetryDelay = (attempt, baseDelayMs = 200, maxDelayMs = 1200) => Math.min(baseDelayMs * Math.pow(2, attempt), maxDelayMs);
292
- const BLE_RESPONSE_TIMEOUT_MS = 30000;
293
- const PROTOCOL_PROBE_TIMEOUT_MS = 1000;
277
+ const PROTOCOL_PROBE_TIMEOUT_MS = 3000;
294
278
  const PROTOCOL_V2_PROBE_TIMEOUT_MS = 10000;
295
- const DEVICE_SCAN_TIMEOUT_MS = 8000;
279
+ const BLE_WRITE_PACKET_TIMEOUT_MS = 10000;
280
+ const BLE_NATIVE_TEARDOWN_TIMEOUT_MS = 3000;
281
+ const WEDGED_WRITE_MESSAGE = 'BLE write timeout after';
282
+ const isWedgedWriteError = (error) => (error === null || error === void 0 ? void 0 : error.errorCode) === hdShared.HardwareErrorCode.BleWriteCharacteristicError &&
283
+ typeof (error === null || error === void 0 ? void 0 : error.message) === 'string' &&
284
+ error.message.startsWith(WEDGED_WRITE_MESSAGE);
285
+ const BLE_WRITE_TIMEOUT_MANAGER_RESET_THRESHOLD = 2;
286
+ const DEVICE_SCAN_TIMEOUT_MS = 3000;
296
287
  const IOS_NOTIFY_READY_DELAY_MS = 150;
297
288
  const ANDROID_NOTIFY_READY_DELAY_MS = 300;
298
289
  const DEFAULT_PROTOCOL_V2_BLE_TUNING = {
299
- iosPacketLength: IOS_PACKET_LENGTH,
300
- androidPacketLength: ANDROID_PACKET_LENGTH,
290
+ iosPacketLength: IOS_PROTOCOL_V2_PACKET_LENGTH,
291
+ androidPacketLength: ANDROID_PROTOCOL_V2_PACKET_LENGTH,
301
292
  };
302
293
  let protocolV2BleTuning = Object.assign({}, DEFAULT_PROTOCOL_V2_BLE_TUNING);
303
294
  const normalizePositiveInteger = (value, fallback) => {
@@ -320,25 +311,37 @@ function resetProtocolV2BleTuning() {
320
311
  function getProtocolV2BleTuning() {
321
312
  return Object.assign({}, protocolV2BleTuning);
322
313
  }
323
- function inferProtocolHintFromDeviceName(name) {
324
- return /\bpro\s*2\b/i.test(name !== null && name !== void 0 ? name : '') ? 'V2' : undefined;
325
- }
326
314
  function getDeviceDisplayName(device) {
327
315
  return (device === null || device === void 0 ? void 0 : device.name) || (device === null || device === void 0 ? void 0 : device.localName) || null;
328
316
  }
329
- function isGenericBleService(uuid) {
330
- return ['1800', '1801', '180a'].includes(getBleUuidKey(uuid));
331
- }
332
- function hasKnownOneKeyService(device) {
333
- var _a;
334
- return ((_a = device === null || device === void 0 ? void 0 : device.serviceUUIDs) !== null && _a !== void 0 ? _a : []).some(serviceUuid => getInfosForServiceUuid(serviceUuid, 'classic'));
335
- }
336
- const ANDROID_REQUEST_MTU = 256;
317
+ const IOS_REQUEST_MTU = 247;
318
+ const ANDROID_REQUEST_MTU = 517;
319
+ const BLE_MTU_REFRESH_RETRY_DELAY_MS = 200;
320
+ const ANDROID_HIGH_PRIORITY_IDLE_MS = 1000;
321
+ const getRequestedBleMtu = () => reactNative.Platform.OS === 'android' ? ANDROID_REQUEST_MTU : IOS_REQUEST_MTU;
322
+ const BLE_NATIVE_CONNECT_TIMEOUT_MS = 3000;
337
323
  const connectOptions = {
338
- requestMTU: ANDROID_REQUEST_MTU,
339
- timeout: 3000,
324
+ requestMTU: getRequestedBleMtu(),
325
+ timeout: BLE_NATIVE_CONNECT_TIMEOUT_MS,
340
326
  refreshGatt: 'OnConnected',
341
327
  };
328
+ const fallbackConnectOptions = {
329
+ timeout: BLE_NATIVE_CONNECT_TIMEOUT_MS,
330
+ };
331
+ const BLE_CONNECT_TIMEOUT_MS = BLE_NATIVE_CONNECT_TIMEOUT_MS * 2 + 2000;
332
+ const BLE_GATT_SETUP_TIMEOUT_MS = 10000;
333
+ const PROTOCOL_REPROBE_FALLBACK_ATTEMPTS = 3;
334
+ const BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD = 2;
335
+ const CONNECT_TIMEOUT_MESSAGE = 'BLE connect timeout after';
336
+ const BLE_SETUP_WEDGED_MESSAGE = 'BLE setup wedged repeatedly';
337
+ const isConnectTimeoutError = (error) => (error === null || error === void 0 ? void 0 : error.errorCode) === hdShared.HardwareErrorCode.BleConnectedError &&
338
+ typeof (error === null || error === void 0 ? void 0 : error.message) === 'string' &&
339
+ error.message.startsWith(CONNECT_TIMEOUT_MESSAGE);
340
+ const isWedgedBleSetupError = (error) => (error === null || error === void 0 ? void 0 : error.errorCode) === hdShared.HardwareErrorCode.PollingTimeout &&
341
+ typeof (error === null || error === void 0 ? void 0 : error.message) === 'string' &&
342
+ error.message.startsWith(BLE_SETUP_WEDGED_MESSAGE);
343
+ const shouldRethrowBleSetupError = (error) => isConnectTimeoutError(error) || isWedgedBleSetupError(error);
344
+ const isNativeOperationTimeoutError = (error) => (error === null || error === void 0 ? void 0 : error.errorCode) === reactNativeBlePlx.BleErrorCode.OperationTimedOut;
342
345
  const tryToGetConfiguration = (device) => {
343
346
  if (!device || !device.serviceUUIDs)
344
347
  return null;
@@ -350,23 +353,25 @@ const tryToGetConfiguration = (device) => {
350
353
  return null;
351
354
  return infos;
352
355
  };
353
- const requestAndroidMtu = (device) => __awaiter(void 0, void 0, void 0, function* () {
354
- if (reactNative.Platform.OS !== 'android')
356
+ const requestNegotiatedMtu = (device, stage, attempt) => __awaiter(void 0, void 0, void 0, function* () {
357
+ if (reactNative.Platform.OS !== 'ios' && reactNative.Platform.OS !== 'android')
355
358
  return device;
356
359
  try {
357
- const mtuDevice = yield device.requestMTU(ANDROID_REQUEST_MTU);
358
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] MTU configured', {
359
- deviceId: device.id,
360
- requested: ANDROID_REQUEST_MTU,
361
- actual: mtuDevice.mtu,
362
- });
360
+ const mtuDevice = yield device.requestMTU(getRequestedBleMtu());
363
361
  return mtuDevice;
364
362
  }
365
363
  catch (error) {
366
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android MTU request failed:', error);
364
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] MTU refresh failed, continuing with current value', {
365
+ platform: reactNative.Platform.OS,
366
+ stage,
367
+ attempt,
368
+ actual: device.mtu,
369
+ error: error instanceof Error ? error.message : String(error),
370
+ });
367
371
  return device;
368
372
  }
369
373
  });
374
+ const resolveNegotiatedMtu = (device) => requestNegotiatedMtu(device, 'connected', 0);
370
375
  function remapError(error) {
371
376
  var _a;
372
377
  if (error instanceof reactNativeBlePlx.BleError) {
@@ -393,9 +398,16 @@ class ReactNativeBleTransport {
393
398
  this.stopped = false;
394
399
  this.scanTimeout = DEVICE_SCAN_TIMEOUT_MS;
395
400
  this.runPromise = null;
401
+ this.runPromiseDeviceId = null;
396
402
  this.firmwareUploadWriteRecoveryIds = new Set();
397
403
  this.deviceProtocol = new Map();
404
+ this.probingProtocols = new Map();
405
+ this.writeTimeoutCounts = new Map();
406
+ this.connectionSetupTimeoutCounts = new Map();
398
407
  this.deviceProtocolHints = new Map();
408
+ this.sessionProtocols = new Map();
409
+ this.confirmedProtocolV2 = new Set();
410
+ this.protocolReprobeFailures = new Map();
399
411
  this.protocolV2Assemblers = new Map();
400
412
  this.protocolV2FrameQueues = new Map();
401
413
  this.protocolV2FramePromises = new Map();
@@ -416,12 +428,17 @@ class ReactNativeBleTransport {
416
428
  this.rejectProtocolV2Frames(uuid, new Error(reason));
417
429
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 link invalidated:', uuid, reason);
418
430
  if (reason.startsWith('Protocol V2 link-fatal error:')) {
419
- yield this.release(uuid, true);
431
+ yield this.releaseNative(uuid, true);
420
432
  }
421
433
  }),
422
434
  });
423
435
  this.monitorTokens = new Map();
436
+ this.disconnectEventTokens = new Map();
437
+ this.protocolV2HighVolumeLogSignatures = new Map();
438
+ this.androidHighPriorityDevices = new Set();
439
+ this.androidPriorityResetTimers = new Map();
424
440
  this.nextMonitorToken = 1;
441
+ this.lifecycleOperations = new Map();
425
442
  this.scanTimeout = (_a = options.scanTimeout) !== null && _a !== void 0 ? _a : DEVICE_SCAN_TIMEOUT_MS;
426
443
  }
427
444
  init(logger, emitter) {
@@ -434,10 +451,18 @@ class ReactNativeBleTransport {
434
451
  this._messages = messages;
435
452
  }
436
453
  configureProtocolV2(signedData) {
454
+ const configuration = typeof signedData === 'string' ? signedData : JSON.stringify(signedData);
455
+ if (this.protocolV2SchemaConfiguration === configuration) {
456
+ return;
457
+ }
458
+ const isReconfiguration = this.protocolV2SchemaConfiguration !== undefined;
437
459
  this._messagesV2 = parseConfigure(signedData);
438
- this.protocolV2Links
439
- .invalidateAllLinks('Protocol V2 schema reconfigured')
440
- .catch(error => Log === null || Log === void 0 ? void 0 : Log.debug('Protocol V2 schema link cleanup failed:', error));
460
+ this.protocolV2SchemaConfiguration = configuration;
461
+ if (isReconfiguration) {
462
+ this.protocolV2Links
463
+ .invalidateAllLinks('Protocol V2 schema reconfigured')
464
+ .catch(error => Log === null || Log === void 0 ? void 0 : Log.debug('Protocol V2 schema link cleanup failed:', error));
465
+ }
441
466
  }
442
467
  listen() {
443
468
  }
@@ -448,7 +473,6 @@ class ReactNativeBleTransport {
448
473
  return Promise.resolve(this.blePlxManager);
449
474
  }
450
475
  resolveCharacteristics(device) {
451
- var _a, _b, _c, _d;
452
476
  return __awaiter(this, void 0, void 0, function* () {
453
477
  yield device.discoverAllServicesAndCharacteristics();
454
478
  let infos = tryToGetConfiguration(device);
@@ -465,19 +489,11 @@ class ReactNativeBleTransport {
465
489
  }
466
490
  }
467
491
  }
468
- let fallbackServiceUuid;
469
492
  if (!infos) {
470
493
  const services = yield device.services();
471
494
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Known OneKey service UUID not found, discovered services:', services === null || services === void 0 ? void 0 : services.map(service => service.uuid));
472
- const knownService = services.find(service => getInfosForServiceUuid(service.uuid, 'classic'));
473
- const fallbackService = (_a = knownService !== null && knownService !== void 0 ? knownService : services.find(service => !isGenericBleService(service.uuid))) !== null && _a !== void 0 ? _a : services[0];
474
- if (fallbackService) {
475
- fallbackServiceUuid = fallbackService.uuid;
476
- characteristics = yield device.characteristicsForService(fallbackService.uuid);
477
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Using fallback BLE service:', fallbackService.uuid);
478
- }
479
495
  }
480
- if (!infos && !fallbackServiceUuid) {
496
+ if (!infos) {
481
497
  try {
482
498
  Log === null || Log === void 0 ? void 0 : Log.debug('cancel connection when service not found');
483
499
  yield device.cancelConnection();
@@ -487,9 +503,7 @@ class ReactNativeBleTransport {
487
503
  }
488
504
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound);
489
505
  }
490
- const serviceUuid = (_b = infos === null || infos === void 0 ? void 0 : infos.serviceUuid) !== null && _b !== void 0 ? _b : fallbackServiceUuid;
491
- const writeUuid = (_c = infos === null || infos === void 0 ? void 0 : infos.writeUuid) !== null && _c !== void 0 ? _c : '00000002-0000-1000-8000-00805f9b34fb';
492
- const notifyUuid = (_d = infos === null || infos === void 0 ? void 0 : infos.notifyUuid) !== null && _d !== void 0 ? _d : '00000003-0000-1000-8000-00805f9b34fb';
506
+ const { serviceUuid, writeUuid, notifyUuid } = infos;
493
507
  if (!serviceUuid) {
494
508
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound);
495
509
  }
@@ -530,8 +544,8 @@ class ReactNativeBleTransport {
530
544
  attachDisconnectSubscription(transport, device, uuid) {
531
545
  var _a;
532
546
  (_a = transport.disconnectSubscription) === null || _a === void 0 ? void 0 : _a.remove();
547
+ const { monitorToken } = transport;
533
548
  transport.disconnectSubscription = device.onDisconnected(() => {
534
- var _a;
535
549
  if (this.firmwareUploadWriteRecoveryIds.has(uuid)) {
536
550
  Log === null || Log === void 0 ? void 0 : Log.debug('device disconnect ignored during FirmwareUpload write recovery: ', uuid);
537
551
  return;
@@ -540,17 +554,16 @@ class ReactNativeBleTransport {
540
554
  Log === null || Log === void 0 ? void 0 : Log.debug('device disconnect ignored for stale transport: ', device === null || device === void 0 ? void 0 : device.id);
541
555
  return;
542
556
  }
557
+ if (this.monitorTokens.get(uuid) !== monitorToken) {
558
+ Log === null || Log === void 0 ? void 0 : Log.debug('device disconnect ignored for stale generation: ', device === null || device === void 0 ? void 0 : device.id);
559
+ return;
560
+ }
543
561
  try {
544
562
  Log === null || Log === void 0 ? void 0 : Log.debug('device disconnect: ', device === null || device === void 0 ? void 0 : device.id);
545
- (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit('device-disconnect', {
546
- name: device === null || device === void 0 ? void 0 : device.name,
547
- id: device === null || device === void 0 ? void 0 : device.id,
548
- connectId: device === null || device === void 0 ? void 0 : device.id,
549
- });
550
- if (this.runPromise) {
563
+ this.emitDeviceDisconnect(uuid, device === null || device === void 0 ? void 0 : device.name, monitorToken);
564
+ if (this.runPromise && this.runPromiseDeviceId === uuid) {
551
565
  const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError);
552
566
  this.runPromise.reject(error);
553
- this.rejectAllProtocolV2Frames(error);
554
567
  }
555
568
  }
556
569
  catch (e) {
@@ -561,6 +574,22 @@ class ReactNativeBleTransport {
561
574
  }
562
575
  });
563
576
  }
577
+ emitDeviceDisconnect(uuid, name, token) {
578
+ var _a;
579
+ if (token === undefined || this.disconnectEventTokens.get(uuid) === token) {
580
+ return;
581
+ }
582
+ if (this.monitorTokens.get(uuid) !== token) {
583
+ Log === null || Log === void 0 ? void 0 : Log.debug('device disconnect event ignored for stale generation: ', uuid);
584
+ return;
585
+ }
586
+ this.disconnectEventTokens.set(uuid, token);
587
+ (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit(transport.TRANSPORT_EVENT.DEVICE_DISCONNECT, {
588
+ name,
589
+ id: uuid,
590
+ connectId: uuid,
591
+ });
592
+ }
564
593
  reconnectFirmwareUploadTransport(uuid, transport) {
565
594
  var _a, _b;
566
595
  return __awaiter(this, void 0, void 0, function* () {
@@ -574,19 +603,19 @@ class ReactNativeBleTransport {
574
603
  const isConnected = yield device.isConnected().catch(() => false);
575
604
  if (!isConnected) {
576
605
  try {
577
- device = yield device.connect(connectOptions);
606
+ device = yield this.connectWithTimeout(uuid, () => device.connect(connectOptions));
578
607
  }
579
608
  catch (e) {
580
609
  if (e.errorCode === reactNativeBlePlx.BleErrorCode.DeviceMTUChangeFailed ||
581
610
  e.errorCode === reactNativeBlePlx.BleErrorCode.OperationCancelled) {
582
- device = yield device.connect();
611
+ device = yield this.connectWithTimeout(uuid, () => device.connect());
583
612
  }
584
613
  else if (e.errorCode !== reactNativeBlePlx.BleErrorCode.DeviceAlreadyConnected) {
585
614
  throw e;
586
615
  }
587
616
  }
588
617
  }
589
- const { writeCharacteristic, notifyCharacteristic } = yield this.resolveCharacteristics(device);
618
+ const { writeCharacteristic, notifyCharacteristic } = yield this.resolveCharacteristicsWithTimeout(uuid, device);
590
619
  transport.device = device;
591
620
  transport.writeCharacteristic = writeCharacteristic;
592
621
  transport.notifyCharacteristic = notifyCharacteristic;
@@ -634,7 +663,7 @@ class ReactNativeBleTransport {
634
663
  allowDuplicates: true,
635
664
  scanMode: reactNativeBlePlx.ScanMode.LowLatency,
636
665
  }, (error, device) => {
637
- var _a, _b, _c;
666
+ var _a, _b;
638
667
  if (error) {
639
668
  Log === null || Log === void 0 ? void 0 : Log.debug('ble scan error: ', error);
640
669
  if ([reactNativeBlePlx.BleErrorCode.BluetoothPoweredOff, reactNativeBlePlx.BleErrorCode.BluetoothInUnknownState].includes(error.errorCode)) {
@@ -655,9 +684,14 @@ class ReactNativeBleTransport {
655
684
  return;
656
685
  }
657
686
  const displayName = getDeviceDisplayName(device);
658
- const isOneKey = hdShared.isOnekeyDevice((_b = device === null || device === void 0 ? void 0 : device.name) !== null && _b !== void 0 ? _b : null, device === null || device === void 0 ? void 0 : device.id) ||
659
- hdShared.isOnekeyDevice((_c = device === null || device === void 0 ? void 0 : device.localName) !== null && _c !== void 0 ? _c : null, device === null || device === void 0 ? void 0 : device.id) ||
660
- hasKnownOneKeyService(device);
687
+ const isUnnamedIOSPeripheral = reactNative.Platform.OS === 'ios' && !(displayName === null || displayName === void 0 ? void 0 : displayName.trim());
688
+ const isOneKey = !isUnnamedIOSPeripheral &&
689
+ hdShared.isOnekeyBluetoothDevice({
690
+ id: device === null || device === void 0 ? void 0 : device.id,
691
+ name: device === null || device === void 0 ? void 0 : device.name,
692
+ localName: device === null || device === void 0 ? void 0 : device.localName,
693
+ serviceUuids: (_b = device === null || device === void 0 ? void 0 : device.serviceUUIDs) !== null && _b !== void 0 ? _b : getBluetoothServiceUuids(),
694
+ });
661
695
  if (isOneKey) {
662
696
  addDevice(device);
663
697
  }
@@ -672,10 +706,15 @@ class ReactNativeBleTransport {
672
706
  });
673
707
  getConnectedDeviceIds(reactNative.Platform.OS === 'ios' ? getBluetoothServiceUuids() : []).then(devices => {
674
708
  for (const device of devices) {
675
- const { serviceUUIDs } = device;
676
- const hasCachedServiceUuid = Boolean(serviceUUIDs === null || serviceUUIDs === void 0 ? void 0 : serviceUUIDs.length);
677
- const keepDevice = reactNative.Platform.OS === 'ios' || hasCachedServiceUuid;
678
- if (keepDevice) {
709
+ const localName = 'localName' in device && typeof device.localName === 'string'
710
+ ? device.localName
711
+ : null;
712
+ if (hdShared.isOnekeyBluetoothDevice({
713
+ id: device.id,
714
+ name: device.name,
715
+ localName,
716
+ serviceUuids: device.serviceUUIDs,
717
+ })) {
679
718
  Log === null || Log === void 0 ? void 0 : Log.debug('search connected peripheral: ', device.id);
680
719
  addDevice(device);
681
720
  }
@@ -685,16 +724,11 @@ class ReactNativeBleTransport {
685
724
  var _a;
686
725
  if (deviceList.every(d => d.id !== device.id)) {
687
726
  const displayName = (_a = getDeviceDisplayName(device)) !== null && _a !== void 0 ? _a : 'Unknown BLE Device';
688
- const protocolHint = inferProtocolHintFromDeviceName(displayName);
689
- if (protocolHint) {
690
- this.deviceProtocolHints.set(device.id, protocolHint);
691
- }
692
727
  deviceList.push(Object.assign(Object.assign({}, device), { name: displayName, commType: 'ble' }));
693
728
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] OneKey BLE device discovered', {
694
729
  deviceId: device.id,
695
730
  name: displayName,
696
731
  serviceUUIDs: device.serviceUUIDs,
697
- protocolHint,
698
732
  });
699
733
  }
700
734
  };
@@ -705,13 +739,70 @@ class ReactNativeBleTransport {
705
739
  }));
706
740
  });
707
741
  }
742
+ installTransportForAcquire(uuid, device, characteristics) {
743
+ return __awaiter(this, void 0, void 0, function* () {
744
+ const { writeCharacteristic, notifyCharacteristic } = characteristics !== null && characteristics !== void 0 ? characteristics : (yield this.resolveCharacteristicsWithTimeout(uuid, device));
745
+ const transport$1 = new BleTransport(device, writeCharacteristic, notifyCharacteristic);
746
+ transport$1.mtuSize = typeof device.mtu === 'number' ? device.mtu : undefined;
747
+ const monitorToken = this.nextMonitorToken;
748
+ this.nextMonitorToken += 1;
749
+ const notifyTransactionId = `${uuid}:notify:${monitorToken}`;
750
+ transport$1.monitorToken = monitorToken;
751
+ transport$1.notifyTransactionId = notifyTransactionId;
752
+ this.monitorTokens.set(uuid, monitorToken);
753
+ transport$1.notifySubscription = this._monitorCharacteristic(transport$1.notifyCharacteristic, uuid, monitorToken, notifyTransactionId);
754
+ transportCache[uuid] = transport$1;
755
+ this.protocolV2HighVolumeLogSignatures.set(uuid, new Set());
756
+ this.protocolV2Assemblers.set(uuid, new transport.ProtocolV2FrameAssembler(transport.PROTOCOL_V2_BLE_FRAME_MAX_BYTES));
757
+ if (reactNative.Platform.OS === 'ios') {
758
+ yield new Promise(resolve => {
759
+ setTimeout(resolve, IOS_NOTIFY_READY_DELAY_MS);
760
+ });
761
+ }
762
+ else if (reactNative.Platform.OS === 'android') {
763
+ yield delay(ANDROID_NOTIFY_READY_DELAY_MS);
764
+ }
765
+ const initialMtu = transport$1.mtuSize;
766
+ let refreshAttempts = 0;
767
+ if ((reactNative.Platform.OS === 'ios' || reactNative.Platform.OS === 'android') &&
768
+ shouldRefreshNegotiatedMtu(transport$1.mtuSize)) {
769
+ refreshAttempts += 1;
770
+ let refreshedDevice = yield requestNegotiatedMtu(transport$1.device, 'servicesAndNotifyReady', 1);
771
+ transport$1.device = refreshedDevice;
772
+ transport$1.mtuSize =
773
+ typeof refreshedDevice.mtu === 'number' ? refreshedDevice.mtu : transport$1.mtuSize;
774
+ if (shouldRefreshNegotiatedMtu(transport$1.mtuSize)) {
775
+ yield delay(BLE_MTU_REFRESH_RETRY_DELAY_MS);
776
+ refreshAttempts += 1;
777
+ refreshedDevice = yield requestNegotiatedMtu(transport$1.device, 'servicesAndNotifyReady', 2);
778
+ transport$1.device = refreshedDevice;
779
+ transport$1.mtuSize =
780
+ typeof refreshedDevice.mtu === 'number' ? refreshedDevice.mtu : transport$1.mtuSize;
781
+ }
782
+ }
783
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] BLE MTU ready', {
784
+ platform: reactNative.Platform.OS,
785
+ requested: getRequestedBleMtu(),
786
+ initial: initialMtu,
787
+ actual: transport$1.mtuSize,
788
+ refreshAttempts,
789
+ });
790
+ return transport$1;
791
+ });
792
+ }
708
793
  acquire(input) {
709
- var _a, _b;
710
794
  return __awaiter(this, void 0, void 0, function* () {
711
- const { uuid, forceCleanRunPromise, expectedProtocol } = input;
795
+ const { uuid } = input;
712
796
  if (!uuid) {
713
797
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleRequiredUUID);
714
798
  }
799
+ return this.runLifecycleOperation(uuid, () => this.acquireUnlocked(input));
800
+ });
801
+ }
802
+ acquireUnlocked(input) {
803
+ var _a;
804
+ return __awaiter(this, void 0, void 0, function* () {
805
+ const { uuid, forceCleanRunPromise, expectedProtocol } = input;
715
806
  const cachedTransport = transportCache[uuid];
716
807
  if (cachedTransport) {
717
808
  const cachedProtocol = this.deviceProtocol.get(uuid);
@@ -723,14 +814,14 @@ class ReactNativeBleTransport {
723
814
  return { uuid, protocolType: cachedProtocol };
724
815
  }
725
816
  Log === null || Log === void 0 ? void 0 : Log.debug('transport not reusable, will release: ', uuid);
726
- yield this.release(uuid, true);
817
+ yield this.releaseUnlocked(uuid, true);
727
818
  }
728
819
  let device = null;
729
820
  if (forceCleanRunPromise && this.runPromise) {
730
821
  const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleForceCleanRunPromise);
731
822
  this.runPromise.reject(error);
732
- this.rejectAllProtocolV2Frames(error);
733
823
  this.runPromise = null;
824
+ this.runPromiseDeviceId = null;
734
825
  Log === null || Log === void 0 ? void 0 : Log.debug('Force clean Bluetooth run promise, forceCleanRunPromise: ', forceCleanRunPromise);
735
826
  }
736
827
  const blePlxManager = yield this.getPlxManager();
@@ -763,14 +854,17 @@ class ReactNativeBleTransport {
763
854
  if (!device) {
764
855
  Log === null || Log === void 0 ? void 0 : Log.debug('try to connect to device: ', uuid);
765
856
  try {
766
- device = yield blePlxManager.connectToDevice(uuid, connectOptions);
857
+ device = yield this.connectWithTimeout(uuid, () => blePlxManager.connectToDevice(uuid, connectOptions));
767
858
  }
768
859
  catch (e) {
769
860
  Log === null || Log === void 0 ? void 0 : Log.debug('try to connect to device has error: ', e);
861
+ if (shouldRethrowBleSetupError(e)) {
862
+ throw e;
863
+ }
770
864
  if (e.errorCode === reactNativeBlePlx.BleErrorCode.DeviceMTUChangeFailed ||
771
865
  e.errorCode === reactNativeBlePlx.BleErrorCode.OperationCancelled) {
772
866
  Log === null || Log === void 0 ? void 0 : Log.debug('first try to reconnect without params');
773
- device = yield blePlxManager.connectToDevice(uuid);
867
+ device = yield this.connectWithTimeout(uuid, () => blePlxManager.connectToDevice(uuid, fallbackConnectOptions));
774
868
  }
775
869
  else if (e.errorCode === reactNativeBlePlx.BleErrorCode.DeviceAlreadyConnected) {
776
870
  Log === null || Log === void 0 ? void 0 : Log.debug('device already connected');
@@ -786,23 +880,27 @@ class ReactNativeBleTransport {
786
880
  }
787
881
  if (!(yield device.isConnected())) {
788
882
  Log === null || Log === void 0 ? void 0 : Log.debug('not connected, try to connect to device: ', uuid);
883
+ const disconnectedDevice = device;
789
884
  try {
790
- device = yield device.connect(connectOptions);
885
+ device = yield this.connectWithTimeout(uuid, () => disconnectedDevice.connect(connectOptions));
791
886
  }
792
887
  catch (e) {
793
888
  Log === null || Log === void 0 ? void 0 : Log.debug('not connected, try to connect to device has error: ', e);
889
+ if (shouldRethrowBleSetupError(e)) {
890
+ throw e;
891
+ }
794
892
  if (e.errorCode === reactNativeBlePlx.BleErrorCode.DeviceMTUChangeFailed ||
795
893
  e.errorCode === reactNativeBlePlx.BleErrorCode.OperationCancelled) {
796
894
  Log === null || Log === void 0 ? void 0 : Log.debug('second try to reconnect without params');
797
895
  try {
798
- device = yield device.connect();
896
+ device = yield this.connectWithTimeout(uuid, () => disconnectedDevice.connect(fallbackConnectOptions));
799
897
  }
800
898
  catch (e) {
801
899
  Log === null || Log === void 0 ? void 0 : Log.debug('last try to reconnect error: ', e);
802
900
  if (e.errorCode === reactNativeBlePlx.BleErrorCode.OperationCancelled) {
803
901
  Log === null || Log === void 0 ? void 0 : Log.debug('last try to reconnect');
804
- yield device.cancelConnection();
805
- device = yield device.connect();
902
+ yield disconnectedDevice.cancelConnection();
903
+ device = yield this.connectWithTimeout(uuid, () => disconnectedDevice.connect(fallbackConnectOptions));
806
904
  }
807
905
  }
808
906
  }
@@ -811,44 +909,40 @@ class ReactNativeBleTransport {
811
909
  }
812
910
  }
813
911
  }
814
- device = yield requestAndroidMtu(device);
815
- const { writeCharacteristic, notifyCharacteristic } = yield this.resolveCharacteristics(device);
912
+ device = yield resolveNegotiatedMtu(device);
913
+ const acquiredDevice = device;
914
+ const { writeCharacteristic, notifyCharacteristic } = yield this.resolveCharacteristicsWithTimeout(uuid, acquiredDevice);
816
915
  const protocolHint = expectedProtocol
817
916
  ? undefined
818
- : (_a = this.deviceProtocolHints.get(uuid)) !== null && _a !== void 0 ? _a : inferProtocolHintFromDeviceName(getDeviceDisplayName(device));
819
- yield this.release(uuid, true);
917
+ : (_a = input.protocolHint) !== null && _a !== void 0 ? _a : this.deviceProtocolHints.get(uuid);
918
+ yield this.releaseUnlocked(uuid, true);
820
919
  if (protocolHint) {
821
920
  this.deviceProtocolHints.set(uuid, protocolHint);
822
921
  }
823
- const transport$1 = new BleTransport(device, writeCharacteristic, notifyCharacteristic);
824
- if (reactNative.Platform.OS === 'android') {
825
- transport$1.mtuSize = typeof device.mtu === 'number' ? device.mtu : transport$1.mtuSize;
826
- }
827
- const monitorToken = this.nextMonitorToken;
828
- this.nextMonitorToken += 1;
829
- const notifyTransactionId = `${uuid}:notify:${monitorToken}`;
830
- transport$1.monitorToken = monitorToken;
831
- transport$1.notifyTransactionId = notifyTransactionId;
832
- this.monitorTokens.set(uuid, monitorToken);
833
- transport$1.notifySubscription = this._monitorCharacteristic(transport$1.notifyCharacteristic, uuid, monitorToken, notifyTransactionId);
834
- transportCache[uuid] = transport$1;
835
- this.protocolV2Assemblers.set(uuid, new transport.ProtocolV2FrameAssembler());
836
- if (reactNative.Platform.OS === 'ios') {
837
- yield new Promise(resolve => {
838
- setTimeout(resolve, IOS_NOTIFY_READY_DELAY_MS);
839
- });
922
+ yield this.installTransportForAcquire(uuid, acquiredDevice, {
923
+ writeCharacteristic,
924
+ notifyCharacteristic,
925
+ });
926
+ try {
927
+ const protocolType = yield this.detectProtocol(uuid, expectedProtocol, protocolHint, () => __awaiter(this, void 0, void 0, function* () {
928
+ yield this.installTransportForAcquire(uuid, acquiredDevice);
929
+ }));
930
+ const currentTransport = transportCache[uuid];
931
+ if (!currentTransport) {
932
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
933
+ }
934
+ this.attachDisconnectSubscription(currentTransport, currentTransport.device, uuid);
935
+ return { uuid, protocolType };
840
936
  }
841
- else if (reactNative.Platform.OS === 'android') {
842
- yield delay(ANDROID_NOTIFY_READY_DELAY_MS);
937
+ catch (error) {
938
+ if ((error === null || error === void 0 ? void 0 : error.errorCode) === hdShared.HardwareErrorCode.BleDeviceBondError) {
939
+ yield this.disconnectUnlocked(uuid);
940
+ }
941
+ else {
942
+ yield this.releaseUnlocked(uuid, true);
943
+ }
944
+ throw error;
843
945
  }
844
- const protocolType = yield this.detectProtocol(uuid, expectedProtocol, protocolHint);
845
- (_b = this.emitter) === null || _b === void 0 ? void 0 : _b.emit('device-connect', {
846
- name: device.name,
847
- id: device.id,
848
- connectId: device.id,
849
- });
850
- this.attachDisconnectSubscription(transport$1, device, uuid);
851
- return { uuid, protocolType };
852
946
  });
853
947
  }
854
948
  _monitorCharacteristic(characteristic, uuid, monitorToken, notifyTransactionId) {
@@ -867,7 +961,7 @@ class ReactNativeBleTransport {
867
961
  Log === null || Log === void 0 ? void 0 : Log.debug('monitor error ignored for stale transport: ', uuid, notifyTransactionId);
868
962
  return;
869
963
  }
870
- if (this.deviceProtocol.get(uuid) === 'V2') {
964
+ if (this.getActiveProtocol(uuid) === 'V2') {
871
965
  let errorCode = hdShared.HardwareErrorCode.BleCharacteristicNotifyError;
872
966
  if ((_a = error.reason) === null || _a === void 0 ? void 0 : _a.includes('The connection has timed out unexpectedly')) {
873
967
  errorCode = hdShared.HardwareErrorCode.BleTimeoutError;
@@ -885,7 +979,7 @@ class ReactNativeBleTransport {
885
979
  this.rejectProtocolV2Frames(uuid, hdShared.ERRORS.TypedError(errorCode));
886
980
  return;
887
981
  }
888
- if (this.runPromise) {
982
+ if (this.runPromise && this.runPromiseDeviceId === uuid) {
889
983
  let ERROR = hdShared.HardwareErrorCode.BleCharacteristicNotifyError;
890
984
  if ((_h = error.reason) === null || _h === void 0 ? void 0 : _h.includes('The connection has timed out unexpectedly')) {
891
985
  ERROR = hdShared.HardwareErrorCode.BleTimeoutError;
@@ -900,13 +994,11 @@ class ReactNativeBleTransport {
900
994
  ((_p = error.reason) === null || _p === void 0 ? void 0 : _p.includes('notify change failed for device'))) {
901
995
  const notifyError = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleCharacteristicNotifyChangeFailure);
902
996
  this.runPromise.reject(notifyError);
903
- this.rejectAllProtocolV2Frames(notifyError);
904
997
  Log === null || Log === void 0 ? void 0 : Log.debug(`${hdShared.HardwareErrorCode.BleCharacteristicNotifyChangeFailure} ${error.message} ${error.reason}`);
905
998
  return;
906
999
  }
907
1000
  const notifyError = hdShared.ERRORS.TypedError(ERROR);
908
1001
  this.runPromise.reject(notifyError);
909
- this.rejectAllProtocolV2Frames(notifyError);
910
1002
  Log === null || Log === void 0 ? void 0 : Log.debug(': monitor notify error, and has unreleased Promise', Error);
911
1003
  }
912
1004
  return;
@@ -920,7 +1012,7 @@ class ReactNativeBleTransport {
920
1012
  }
921
1013
  try {
922
1014
  const data = buffer.Buffer.from(c.value, 'base64');
923
- const protocol = this.deviceProtocol.get(uuid);
1015
+ const protocol = this.getActiveProtocol(uuid);
924
1016
  if (!protocol) {
925
1017
  Log === null || Log === void 0 ? void 0 : Log.debug('monitor data ignored before protocol detection: ', uuid);
926
1018
  return;
@@ -940,16 +1032,18 @@ class ReactNativeBleTransport {
940
1032
  const value = buffer.Buffer.from(buffer$1);
941
1033
  bufferLength = 0;
942
1034
  buffer$1 = [];
943
- (_q = this.runPromise) === null || _q === void 0 ? void 0 : _q.resolve(value.toString('hex'));
1035
+ if (this.runPromiseDeviceId === uuid) {
1036
+ (_q = this.runPromise) === null || _q === void 0 ? void 0 : _q.resolve(value.toString('hex'));
1037
+ }
944
1038
  }
945
1039
  }
946
1040
  catch (error) {
947
1041
  Log === null || Log === void 0 ? void 0 : Log.debug('monitor data error: ', error);
948
1042
  const notifyError = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError);
949
- if (this.deviceProtocol.get(uuid) === 'V2') {
1043
+ if (this.getActiveProtocol(uuid) === 'V2') {
950
1044
  this.rejectProtocolV2Frames(uuid, notifyError);
951
1045
  }
952
- else {
1046
+ else if (this.runPromiseDeviceId === uuid) {
953
1047
  (_r = this.runPromise) === null || _r === void 0 ? void 0 : _r.reject(notifyError);
954
1048
  }
955
1049
  }
@@ -957,15 +1051,27 @@ class ReactNativeBleTransport {
957
1051
  return subscription;
958
1052
  }
959
1053
  release(uuid, onclose = false) {
960
- var _a, _b, _c, _d, _e, _f, _g;
961
1054
  return __awaiter(this, void 0, void 0, function* () {
962
- const transport = transportCache[uuid];
1055
+ return this.runLifecycleOperation(uuid, () => this.releaseUnlocked(uuid, onclose));
1056
+ });
1057
+ }
1058
+ releaseUnlocked(uuid, onclose = false) {
1059
+ return __awaiter(this, void 0, void 0, function* () {
963
1060
  yield this.protocolV2Links.invalidateLink(uuid, 'React Native BLE transport released');
964
- if (this.runPromise) {
1061
+ return this.releaseNative(uuid, onclose);
1062
+ });
1063
+ }
1064
+ releaseNative(uuid, onclose = false) {
1065
+ var _a, _b, _c, _d, _e;
1066
+ return __awaiter(this, void 0, void 0, function* () {
1067
+ const transport = transportCache[uuid];
1068
+ const manager = this.blePlxManager;
1069
+ if (this.runPromise && this.runPromiseDeviceId === uuid) {
965
1070
  const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleForceCleanRunPromise);
966
1071
  this.runPromise.reject(error);
967
1072
  this.runPromise = null;
968
- this.rejectAllProtocolV2Frames(error);
1073
+ this.runPromiseDeviceId = null;
1074
+ this.rejectProtocolV2Frames(uuid, error);
969
1075
  }
970
1076
  else {
971
1077
  this.resetProtocolV2Frames(uuid);
@@ -985,31 +1091,37 @@ class ReactNativeBleTransport {
985
1091
  Log === null || Log === void 0 ? void 0 : Log.debug('release: removing notify subscription, characteristic: ', (_c = transport.notifyCharacteristic) === null || _c === void 0 ? void 0 : _c.uuid);
986
1092
  (_d = transport.notifySubscription) === null || _d === void 0 ? void 0 : _d.remove();
987
1093
  transport.notifySubscription = undefined;
988
- if (transport.notifyTransactionId) {
989
- try {
990
- yield ((_e = this.blePlxManager) === null || _e === void 0 ? void 0 : _e.cancelTransaction(transport.notifyTransactionId));
991
- }
992
- catch (e) {
993
- Log === null || Log === void 0 ? void 0 : Log.debug('release: cancel notify transaction error (ignored): ', (e === null || e === void 0 ? void 0 : e.message) || e);
994
- }
1094
+ if (transportCache[uuid] === transport) {
1095
+ delete transportCache[uuid];
995
1096
  }
996
- delete transportCache[uuid];
997
1097
  }
1098
+ this.protocolV2HighVolumeLogSignatures.delete(uuid);
998
1099
  this.deviceProtocol.delete(uuid);
999
- (_f = this.protocolV2Assemblers.get(uuid)) === null || _f === void 0 ? void 0 : _f.reset();
1100
+ this.probingProtocols.delete(uuid);
1101
+ (_e = this.protocolV2Assemblers.get(uuid)) === null || _e === void 0 ? void 0 : _e.reset();
1000
1102
  this.protocolV2Assemblers.delete(uuid);
1001
1103
  this.resetProtocolV2Frames(uuid);
1002
- try {
1003
- yield ((_g = this.blePlxManager) === null || _g === void 0 ? void 0 : _g.cancelTransaction(uuid));
1004
- }
1005
- catch (e) {
1006
- Log === null || Log === void 0 ? void 0 : Log.debug('release: cancel transaction error (ignored): ', (e === null || e === void 0 ? void 0 : e.message) || e);
1007
- }
1104
+ yield this.runNativeTeardown(uuid, manager, () => __awaiter(this, void 0, void 0, function* () {
1105
+ const operations = [
1106
+ this.runBestEffortNativeOperation('release: restore connection priority', () => this.restoreAndroidConnectionPriority(uuid, transport)),
1107
+ ];
1108
+ if ((transport === null || transport === void 0 ? void 0 : transport.notifyTransactionId) && manager) {
1109
+ operations.push(this.runBestEffortNativeOperation('release: cancel notify transaction', () => manager.cancelTransaction(transport.notifyTransactionId)));
1110
+ }
1111
+ if (manager) {
1112
+ operations.push(this.runBestEffortNativeOperation('release: cancel transaction', () => manager.cancelTransaction(uuid)));
1113
+ }
1114
+ yield Promise.all(operations);
1115
+ }));
1008
1116
  return Promise.resolve(true);
1009
1117
  });
1010
1118
  }
1011
1119
  post(session, name, data) {
1012
1120
  return __awaiter(this, void 0, void 0, function* () {
1121
+ if (this.getProtocolType(session) === 'V2') {
1122
+ yield this.protocolV2Links.sendFlowControl(session, () => this.createProtocolV2Adapter(session), name, data);
1123
+ return;
1124
+ }
1013
1125
  yield this.call(session, name, data);
1014
1126
  });
1015
1127
  }
@@ -1025,7 +1137,6 @@ class ReactNativeBleTransport {
1025
1137
  if (!protocol) {
1026
1138
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `Device protocol has not been detected for ${uuid}`);
1027
1139
  }
1028
- Log === null || Log === void 0 ? void 0 : Log.debug('transport call', createTransportCallLog(name, protocol, data));
1029
1140
  if (protocol === 'V2') {
1030
1141
  return this.callProtocolV2(uuid, name, data, options);
1031
1142
  }
@@ -1044,7 +1155,19 @@ class ReactNativeBleTransport {
1044
1155
  const transport = this.getCachedTransport(uuid);
1045
1156
  const runPromise = hdShared.createDeferred();
1046
1157
  runPromise.promise.catch(() => undefined);
1158
+ const supersededRunPromise = this.runPromise;
1159
+ if (supersededRunPromise) {
1160
+ supersededRunPromise.reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleForceCleanRunPromise));
1161
+ }
1047
1162
  this.runPromise = runPromise;
1163
+ this.runPromiseDeviceId = uuid;
1164
+ const releaseOwnershipIfCurrent = () => {
1165
+ if (this.runPromise === runPromise) {
1166
+ this.runPromise = null;
1167
+ this.runPromiseDeviceId = null;
1168
+ }
1169
+ };
1170
+ const isCurrentOwner = () => this.runPromise === runPromise;
1048
1171
  const messages = this._messages;
1049
1172
  const buffers = ProtocolV1.encodeTransportPackets(messages, name, data);
1050
1173
  let timeout;
@@ -1065,6 +1188,9 @@ class ReactNativeBleTransport {
1065
1188
  }
1066
1189
  catch (e) {
1067
1190
  onError(e);
1191
+ if (isWedgedWriteError(e)) {
1192
+ throw e;
1193
+ }
1068
1194
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError);
1069
1195
  }
1070
1196
  }
@@ -1092,6 +1218,9 @@ class ReactNativeBleTransport {
1092
1218
  }
1093
1219
  catch (e) {
1094
1220
  onError(e);
1221
+ if (isWedgedWriteError(e)) {
1222
+ throw e;
1223
+ }
1095
1224
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError);
1096
1225
  }
1097
1226
  }
@@ -1102,8 +1231,8 @@ class ReactNativeBleTransport {
1102
1231
  });
1103
1232
  }
1104
1233
  if (name === 'EmmcFileWrite') {
1105
- yield writeChunkedData(buffers, data => transport.writeWithRetry(data), e => {
1106
- this.runPromise = null;
1234
+ yield writeChunkedData(buffers, data => this.writeBlePacket(uuid, data, payload => transport.writeWithRetry(payload), isCurrentOwner), e => {
1235
+ releaseOwnershipIfCurrent();
1107
1236
  Log === null || Log === void 0 ? void 0 : Log.error('writeCharacteristic write error: ', e);
1108
1237
  });
1109
1238
  }
@@ -1119,7 +1248,7 @@ class ReactNativeBleTransport {
1119
1248
  let attempt = 0;
1120
1249
  while (true) {
1121
1250
  try {
1122
- yield transport.writeCharacteristic.writeWithoutResponse(data);
1251
+ yield this.writeBlePacket(uuid, data, payload => transport.writeWithRetry(payload), isCurrentOwner);
1123
1252
  return;
1124
1253
  }
1125
1254
  catch (error) {
@@ -1127,36 +1256,18 @@ class ReactNativeBleTransport {
1127
1256
  if (!retryType || attempt >= FIRMWARE_UPLOAD_WRITE_MAX_RETRIES) {
1128
1257
  throw error;
1129
1258
  }
1130
- const shouldReconnect = retryType === 'reconnectable';
1131
- const delayMs = shouldReconnect
1132
- ? FIRMWARE_UPLOAD_RECONNECT_RETRY_DELAY_MS
1133
- : resolveFirmwareUploadRetryDelay(attempt);
1259
+ const delayMs = resolveFirmwareUploadRetryDelay(attempt);
1134
1260
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] FirmwareUpload write retry:', {
1135
1261
  attempt: attempt + 1,
1136
1262
  delayMs,
1137
- reconnect: shouldReconnect,
1138
1263
  error,
1139
1264
  });
1140
- if (shouldReconnect) {
1141
- this.firmwareUploadWriteRecoveryIds.add(uuid);
1142
- }
1143
1265
  yield delay(delayMs);
1144
1266
  attempt += 1;
1145
- if (shouldReconnect) {
1146
- try {
1147
- yield this.reconnectFirmwareUploadTransport(uuid, transport);
1148
- }
1149
- catch (e) {
1150
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] FirmwareUpload reconnect error:', e);
1151
- if (attempt >= FIRMWARE_UPLOAD_WRITE_MAX_RETRIES) {
1152
- throw e;
1153
- }
1154
- }
1155
- }
1156
1267
  }
1157
1268
  }
1158
1269
  }), e => {
1159
- this.runPromise = null;
1270
+ releaseOwnershipIfCurrent();
1160
1271
  Log === null || Log === void 0 ? void 0 : Log.error('writeCharacteristic write error: ', e);
1161
1272
  });
1162
1273
  }
@@ -1164,11 +1275,17 @@ class ReactNativeBleTransport {
1164
1275
  for (const o of buffers) {
1165
1276
  const outData = o.toString('base64');
1166
1277
  try {
1167
- yield transport.writeCharacteristic.writeWithoutResponse(outData);
1278
+ const shouldUseWriteWithResponse = reactNative.Platform.OS === 'ios' && transport.writeCharacteristic.isWritableWithResponse;
1279
+ yield this.writeBlePacket(uuid, outData, payload => shouldUseWriteWithResponse
1280
+ ? transport.writeCharacteristic.writeWithResponse(payload)
1281
+ : transport.writeCharacteristic.writeWithoutResponse(payload), isCurrentOwner);
1168
1282
  }
1169
1283
  catch (e) {
1170
1284
  Log === null || Log === void 0 ? void 0 : Log.debug('writeCharacteristic write error: ', e);
1171
- this.runPromise = null;
1285
+ releaseOwnershipIfCurrent();
1286
+ if (isWedgedWriteError(e)) {
1287
+ throw e;
1288
+ }
1172
1289
  if (e.errorCode === reactNativeBlePlx.BleErrorCode.DeviceDisconnected) {
1173
1290
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceNotBonded);
1174
1291
  }
@@ -1201,12 +1318,19 @@ class ReactNativeBleTransport {
1201
1318
  return check.call(jsonData);
1202
1319
  }
1203
1320
  catch (e) {
1204
- if (name === 'Initialize' && (options === null || options === void 0 ? void 0 : options.timeoutMs) === PROTOCOL_PROBE_TIMEOUT_MS) {
1205
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V1 Initialize probe call failed:', e);
1321
+ if (name === 'GetFeatures' && (options === null || options === void 0 ? void 0 : options.timeoutMs) === PROTOCOL_PROBE_TIMEOUT_MS) {
1322
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V1 GetFeatures probe call failed:', e);
1206
1323
  }
1207
1324
  else {
1208
1325
  Log === null || Log === void 0 ? void 0 : Log.error('call error: ', e);
1209
1326
  }
1327
+ const isProbeTimeout = name === 'GetFeatures' && (options === null || options === void 0 ? void 0 : options.timeoutMs) === PROTOCOL_PROBE_TIMEOUT_MS;
1328
+ const isStaleCall = this.runPromise !== runPromise;
1329
+ if (!isProbeTimeout &&
1330
+ !isStaleCall &&
1331
+ (e === null || e === void 0 ? void 0 : e.errorCode) === hdShared.HardwareErrorCode.BleTimeoutError) {
1332
+ yield this.disconnect(uuid);
1333
+ }
1210
1334
  throw e;
1211
1335
  }
1212
1336
  finally {
@@ -1214,6 +1338,7 @@ class ReactNativeBleTransport {
1214
1338
  clearTimeout(timeout);
1215
1339
  if (this.runPromise === runPromise) {
1216
1340
  this.runPromise = null;
1341
+ this.runPromiseDeviceId = null;
1217
1342
  }
1218
1343
  }
1219
1344
  });
@@ -1222,10 +1347,17 @@ class ReactNativeBleTransport {
1222
1347
  this.stopped = true;
1223
1348
  }
1224
1349
  disconnect(session) {
1225
- var _a, _b, _c, _d, _e;
1350
+ return __awaiter(this, void 0, void 0, function* () {
1351
+ return this.runLifecycleOperation(session, () => this.disconnectUnlocked(session));
1352
+ });
1353
+ }
1354
+ disconnectUnlocked(session) {
1355
+ var _a, _b, _c;
1226
1356
  return __awaiter(this, void 0, void 0, function* () {
1227
1357
  yield this.protocolV2Links.invalidateLink(session, 'React Native BLE transport disconnected');
1228
1358
  const transport = transportCache[session];
1359
+ const manager = this.blePlxManager;
1360
+ const monitorToken = (_a = transport === null || transport === void 0 ? void 0 : transport.monitorToken) !== null && _a !== void 0 ? _a : this.monitorTokens.get(session);
1229
1361
  if (transport === null || transport === void 0 ? void 0 : transport.disconnectSubscription) {
1230
1362
  try {
1231
1363
  Log === null || Log === void 0 ? void 0 : Log.debug('disconnect: removing disconnect subscription');
@@ -1238,7 +1370,7 @@ class ReactNativeBleTransport {
1238
1370
  }
1239
1371
  if (transport === null || transport === void 0 ? void 0 : transport.notifySubscription) {
1240
1372
  try {
1241
- Log === null || Log === void 0 ? void 0 : Log.debug('disconnect: removing notify subscription, characteristic: ', (_a = transport.notifyCharacteristic) === null || _a === void 0 ? void 0 : _a.uuid);
1373
+ Log === null || Log === void 0 ? void 0 : Log.debug('disconnect: removing notify subscription, characteristic: ', (_b = transport.notifyCharacteristic) === null || _b === void 0 ? void 0 : _b.uuid);
1242
1374
  transport.notifySubscription.remove();
1243
1375
  transport.notifySubscription = undefined;
1244
1376
  }
@@ -1246,52 +1378,201 @@ class ReactNativeBleTransport {
1246
1378
  Log === null || Log === void 0 ? void 0 : Log.error('disconnect: remove notify subscription error: ', e);
1247
1379
  }
1248
1380
  }
1249
- if (session) {
1250
- try {
1251
- yield ((_b = this.blePlxManager) === null || _b === void 0 ? void 0 : _b.cancelTransaction(session));
1252
- }
1253
- catch (e) {
1254
- Log === null || Log === void 0 ? void 0 : Log.debug('resetSession: cancel transaction error (ignored): ', (e === null || e === void 0 ? void 0 : e.message) || e);
1255
- }
1256
- }
1257
- if (transport === null || transport === void 0 ? void 0 : transport.device) {
1258
- try {
1259
- yield transport.device.cancelConnection();
1260
- }
1261
- catch (e) {
1262
- Log === null || Log === void 0 ? void 0 : Log.debug('resetSession: device.cancelConnection error (ignored): ', (e === null || e === void 0 ? void 0 : e.message) || e);
1263
- }
1264
- }
1265
- try {
1266
- yield ((_c = this.blePlxManager) === null || _c === void 0 ? void 0 : _c.cancelDeviceConnection(session));
1267
- }
1268
- catch (e) {
1269
- Log === null || Log === void 0 ? void 0 : Log.debug('resetSession: manager.cancelDeviceConnection error (ignored): ', (e === null || e === void 0 ? void 0 : e.message) || e);
1270
- }
1271
- if (transportCache[session]) {
1381
+ if (!transport || transportCache[session] === transport) {
1272
1382
  delete transportCache[session];
1273
1383
  }
1274
1384
  this.deviceProtocol.delete(session);
1385
+ this.probingProtocols.delete(session);
1275
1386
  this.deviceProtocolHints.delete(session);
1387
+ this.sessionProtocols.delete(session);
1388
+ this.protocolReprobeFailures.delete(session);
1276
1389
  this.protocolV2Assemblers.delete(session);
1277
1390
  this.resetProtocolV2Frames(session);
1278
1391
  try {
1279
- (_d = this.emitter) === null || _d === void 0 ? void 0 : _d.emit('device-disconnect', {
1280
- name: (_e = transport === null || transport === void 0 ? void 0 : transport.device) === null || _e === void 0 ? void 0 : _e.name,
1281
- id: session,
1282
- connectId: session,
1283
- });
1392
+ this.emitDeviceDisconnect(session, (_c = transport === null || transport === void 0 ? void 0 : transport.device) === null || _c === void 0 ? void 0 : _c.name, monitorToken);
1284
1393
  }
1285
1394
  catch (e) {
1286
1395
  Log === null || Log === void 0 ? void 0 : Log.error('resetSession: emit disconnect event error: ', e);
1287
1396
  }
1397
+ if (monitorToken !== undefined && this.monitorTokens.get(session) === monitorToken) {
1398
+ this.monitorTokens.delete(session);
1399
+ }
1400
+ yield this.runNativeTeardown(session, manager, () => __awaiter(this, void 0, void 0, function* () {
1401
+ const operations = [];
1402
+ if (manager) {
1403
+ operations.push(this.runBestEffortNativeOperation('disconnect: cancel transaction', () => manager.cancelTransaction(session)));
1404
+ operations.push(this.runBestEffortNativeOperation('disconnect: cancel device connection', () => manager.cancelDeviceConnection(session)));
1405
+ }
1406
+ if (transport === null || transport === void 0 ? void 0 : transport.device) {
1407
+ operations.push(this.runBestEffortNativeOperation('disconnect: device cancel connection', () => transport.device.cancelConnection()));
1408
+ }
1409
+ yield Promise.all(operations);
1410
+ }));
1288
1411
  yield new Promise(resolve => setTimeout(() => resolve(), 100));
1289
1412
  });
1290
1413
  }
1414
+ runNativeTeardown(uuid, manager, teardown) {
1415
+ return __awaiter(this, void 0, void 0, function* () {
1416
+ let timer;
1417
+ let timedOut = false;
1418
+ const pending = Promise.resolve()
1419
+ .then(teardown)
1420
+ .catch(error => {
1421
+ Log === null || Log === void 0 ? void 0 : Log.debug('BLE native teardown error (ignored): ', (error === null || error === void 0 ? void 0 : error.message) || error);
1422
+ });
1423
+ try {
1424
+ yield Promise.race([
1425
+ pending,
1426
+ new Promise(resolve => {
1427
+ timer = setTimeout(() => {
1428
+ timedOut = true;
1429
+ resolve();
1430
+ }, BLE_NATIVE_TEARDOWN_TIMEOUT_MS);
1431
+ }),
1432
+ ]);
1433
+ }
1434
+ finally {
1435
+ if (timer)
1436
+ clearTimeout(timer);
1437
+ }
1438
+ if (timedOut) {
1439
+ Log === null || Log === void 0 ? void 0 : Log.error('[ReactNativeBleTransport] BLE native teardown timed out:', uuid);
1440
+ if (this.blePlxManager === manager) {
1441
+ this.resetPlxManager();
1442
+ }
1443
+ }
1444
+ });
1445
+ }
1446
+ runBestEffortNativeOperation(label, operation) {
1447
+ return Promise.resolve()
1448
+ .then(operation)
1449
+ .catch(error => {
1450
+ Log === null || Log === void 0 ? void 0 : Log.debug(`${label} error (ignored): `, (error === null || error === void 0 ? void 0 : error.message) || error);
1451
+ });
1452
+ }
1453
+ runLifecycleOperation(uuid, operation) {
1454
+ var _a;
1455
+ return __awaiter(this, void 0, void 0, function* () {
1456
+ const previousOperation = (_a = this.lifecycleOperations.get(uuid)) !== null && _a !== void 0 ? _a : Promise.resolve();
1457
+ let completeOperation;
1458
+ const operationGate = new Promise(resolve => {
1459
+ completeOperation = resolve;
1460
+ });
1461
+ const operationTail = previousOperation.catch(() => undefined).then(() => operationGate);
1462
+ this.lifecycleOperations.set(uuid, operationTail);
1463
+ yield previousOperation.catch(() => undefined);
1464
+ try {
1465
+ return yield operation();
1466
+ }
1467
+ finally {
1468
+ completeOperation();
1469
+ if (this.lifecycleOperations.get(uuid) === operationTail) {
1470
+ this.lifecycleOperations.delete(uuid);
1471
+ }
1472
+ }
1473
+ });
1474
+ }
1291
1475
  cancel() {
1292
1476
  Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native transport cancel');
1293
1477
  if (this.runPromise) ;
1294
1478
  this.runPromise = null;
1479
+ this.runPromiseDeviceId = null;
1480
+ }
1481
+ connectWithTimeout(uuid, connect) {
1482
+ return __awaiter(this, void 0, void 0, function* () {
1483
+ let timer;
1484
+ let timedOut = false;
1485
+ const pending = connect();
1486
+ pending.catch(() => undefined);
1487
+ try {
1488
+ const result = yield Promise.race([
1489
+ pending,
1490
+ new Promise((_, reject) => {
1491
+ timer = setTimeout(() => {
1492
+ timedOut = true;
1493
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, `BLE connect timeout after ${BLE_CONNECT_TIMEOUT_MS}ms for ${uuid}`));
1494
+ }, BLE_CONNECT_TIMEOUT_MS);
1495
+ }),
1496
+ ]);
1497
+ return result;
1498
+ }
1499
+ catch (error) {
1500
+ if (timedOut || isNativeOperationTimeoutError(error)) {
1501
+ const resetManager = this.abandonStalledConnection(uuid, timedOut ? 'connect-backstop' : 'connect-native');
1502
+ if (resetManager) {
1503
+ throw this.createWedgedBleSetupError();
1504
+ }
1505
+ }
1506
+ throw error;
1507
+ }
1508
+ finally {
1509
+ if (timer)
1510
+ clearTimeout(timer);
1511
+ }
1512
+ });
1513
+ }
1514
+ resolveCharacteristicsWithTimeout(uuid, device) {
1515
+ return __awaiter(this, void 0, void 0, function* () {
1516
+ let timer;
1517
+ let timedOut = false;
1518
+ const pending = this.resolveCharacteristics(device);
1519
+ pending.catch(() => undefined);
1520
+ try {
1521
+ const result = yield Promise.race([
1522
+ pending,
1523
+ new Promise((_, reject) => {
1524
+ timer = setTimeout(() => {
1525
+ timedOut = true;
1526
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, `BLE GATT setup timeout after ${BLE_GATT_SETUP_TIMEOUT_MS}ms for ${uuid}`));
1527
+ }, BLE_GATT_SETUP_TIMEOUT_MS);
1528
+ }),
1529
+ ]);
1530
+ this.connectionSetupTimeoutCounts.delete(uuid);
1531
+ return result;
1532
+ }
1533
+ catch (error) {
1534
+ if (timedOut || isNativeOperationTimeoutError(error)) {
1535
+ const resetManager = this.abandonStalledConnection(uuid, timedOut ? 'gatt-backstop' : 'gatt-native');
1536
+ if (resetManager) {
1537
+ throw this.createWedgedBleSetupError();
1538
+ }
1539
+ }
1540
+ throw error;
1541
+ }
1542
+ finally {
1543
+ if (timer)
1544
+ clearTimeout(timer);
1545
+ }
1546
+ });
1547
+ }
1548
+ abandonStalledConnection(uuid, stage) {
1549
+ var _a, _b;
1550
+ const timeouts = ((_a = this.connectionSetupTimeoutCounts.get(uuid)) !== null && _a !== void 0 ? _a : 0) + 1;
1551
+ this.connectionSetupTimeoutCounts.set(uuid, timeouts);
1552
+ Log === null || Log === void 0 ? void 0 : Log.error('[ReactNativeBleTransport] BLE setup timed out:', uuid, {
1553
+ stage,
1554
+ setupTimeoutsSinceSuccess: timeouts,
1555
+ });
1556
+ (_b = this.blePlxManager) === null || _b === void 0 ? void 0 : _b.cancelDeviceConnection(uuid).catch(() => {
1557
+ });
1558
+ const stalled = transportCache[uuid];
1559
+ if (stalled) {
1560
+ delete transportCache[uuid];
1561
+ }
1562
+ this.deviceProtocol.delete(uuid);
1563
+ this.probingProtocols.delete(uuid);
1564
+ this.protocolV2Assemblers.delete(uuid);
1565
+ this.resetProtocolV2Frames(uuid);
1566
+ if (timeouts >= BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD) {
1567
+ Log === null || Log === void 0 ? void 0 : Log.error('[ReactNativeBleTransport] BLE setup wedged repeatedly, resetting BLE manager');
1568
+ this.resetPlxManager();
1569
+ this.connectionSetupTimeoutCounts.delete(uuid);
1570
+ return true;
1571
+ }
1572
+ return false;
1573
+ }
1574
+ createWedgedBleSetupError() {
1575
+ return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.PollingTimeout, BLE_SETUP_WEDGED_MESSAGE);
1295
1576
  }
1296
1577
  getCachedTransport(uuid) {
1297
1578
  const transport = transportCache[uuid];
@@ -1300,22 +1581,146 @@ class ReactNativeBleTransport {
1300
1581
  }
1301
1582
  return transport;
1302
1583
  }
1303
- createProtocolMismatchError(expected) {
1304
- return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `Device protocol mismatch: expected ${expected}, but device did not respond to expected protocol`);
1584
+ writeBlePacket(uuid, data, write, isCurrentOwner) {
1585
+ return __awaiter(this, void 0, void 0, function* () {
1586
+ let timer;
1587
+ let timedOut = false;
1588
+ try {
1589
+ yield Promise.race([
1590
+ write(data),
1591
+ new Promise((_, reject) => {
1592
+ timer = setTimeout(() => {
1593
+ timedOut = true;
1594
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError, `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`));
1595
+ }, BLE_WRITE_PACKET_TIMEOUT_MS);
1596
+ }),
1597
+ ]);
1598
+ this.writeTimeoutCounts.delete(uuid);
1599
+ }
1600
+ catch (error) {
1601
+ if (timedOut) {
1602
+ if (isCurrentOwner && !isCurrentOwner()) {
1603
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] stale BLE write timed out, link kept:', uuid);
1604
+ }
1605
+ else {
1606
+ this.tearDownWedgedLink(uuid);
1607
+ }
1608
+ }
1609
+ throw error;
1610
+ }
1611
+ finally {
1612
+ if (timer)
1613
+ clearTimeout(timer);
1614
+ }
1615
+ });
1616
+ }
1617
+ tearDownWedgedLink(uuid) {
1618
+ var _a;
1619
+ const timeouts = ((_a = this.writeTimeoutCounts.get(uuid)) !== null && _a !== void 0 ? _a : 0) + 1;
1620
+ this.writeTimeoutCounts.set(uuid, timeouts);
1621
+ Log === null || Log === void 0 ? void 0 : Log.error('[ReactNativeBleTransport] BLE write timed out, tearing down link:', uuid, {
1622
+ consecutiveWriteTimeouts: timeouts,
1623
+ });
1624
+ const wedged = transportCache[uuid];
1625
+ this.disconnect(uuid).catch(error => {
1626
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
1627
+ });
1628
+ if (wedged && transportCache[uuid] === wedged) {
1629
+ delete transportCache[uuid];
1630
+ }
1631
+ this.deviceProtocol.delete(uuid);
1632
+ this.probingProtocols.delete(uuid);
1633
+ this.protocolV2Assemblers.delete(uuid);
1634
+ this.resetProtocolV2Frames(uuid);
1635
+ if (timeouts >= BLE_WRITE_TIMEOUT_MANAGER_RESET_THRESHOLD) {
1636
+ Log === null || Log === void 0 ? void 0 : Log.error('[ReactNativeBleTransport] BLE writes wedged repeatedly, resetting BLE manager');
1637
+ this.resetPlxManager();
1638
+ this.writeTimeoutCounts.delete(uuid);
1639
+ }
1640
+ }
1641
+ resetPlxManager() {
1642
+ const manager = this.blePlxManager;
1643
+ this.blePlxManager = undefined;
1644
+ const reason = 'React Native BLE manager reset';
1645
+ Object.entries(transportCache).forEach(([uuid, cachedTransport]) => {
1646
+ var _a, _b, _c, _d;
1647
+ try {
1648
+ (_a = cachedTransport.disconnectSubscription) === null || _a === void 0 ? void 0 : _a.remove();
1649
+ }
1650
+ catch (error) {
1651
+ Log === null || Log === void 0 ? void 0 : Log.debug('BLE manager reset disconnect subscription removal failed:', error);
1652
+ }
1653
+ cachedTransport.disconnectSubscription = undefined;
1654
+ try {
1655
+ (_b = cachedTransport.notifySubscription) === null || _b === void 0 ? void 0 : _b.remove();
1656
+ }
1657
+ catch (error) {
1658
+ Log === null || Log === void 0 ? void 0 : Log.debug('BLE manager reset notify subscription removal failed:', error);
1659
+ }
1660
+ cachedTransport.notifySubscription = undefined;
1661
+ this.rejectProtocolV2Frames(uuid, new Error(reason));
1662
+ try {
1663
+ this.emitDeviceDisconnect(uuid, (_c = cachedTransport.device) === null || _c === void 0 ? void 0 : _c.name, (_d = cachedTransport.monitorToken) !== null && _d !== void 0 ? _d : this.monitorTokens.get(uuid));
1664
+ }
1665
+ catch (error) {
1666
+ Log === null || Log === void 0 ? void 0 : Log.debug('BLE manager reset disconnect event failed:', error);
1667
+ }
1668
+ delete transportCache[uuid];
1669
+ });
1670
+ this.protocolV2Links.invalidateAllLinks(reason).catch(error => {
1671
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] BLE manager link invalidation failed:', error);
1672
+ });
1673
+ this.deviceProtocol.clear();
1674
+ this.probingProtocols.clear();
1675
+ this.sessionProtocols.clear();
1676
+ this.confirmedProtocolV2.clear();
1677
+ this.protocolReprobeFailures.clear();
1678
+ this.writeTimeoutCounts.clear();
1679
+ this.connectionSetupTimeoutCounts.clear();
1680
+ this.monitorTokens.clear();
1681
+ this.protocolV2Assemblers.clear();
1682
+ try {
1683
+ manager === null || manager === void 0 ? void 0 : manager.destroy();
1684
+ }
1685
+ catch (error) {
1686
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] BLE manager destroy failed (ignored):', error);
1687
+ }
1688
+ }
1689
+ createProtocolMismatchError(expected, uuid) {
1690
+ const isStaleV2Bond = expected === 'V2' && this.confirmedProtocolV2.has(uuid);
1691
+ return hdShared.ERRORS.TypedError(isStaleV2Bond ? hdShared.HardwareErrorCode.BleDeviceBondError : hdShared.HardwareErrorCode.RuntimeError, `Device protocol mismatch: expected ${expected}, but device did not respond to expected protocol`);
1305
1692
  }
1306
1693
  createProtocolDetectionError() {
1307
- return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleTimeoutError, 'Unable to detect BLE protocol: device did not respond to Protocol V1 Initialize or Protocol V2 Ping');
1694
+ return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleTimeoutError, 'Unable to detect BLE protocol: device did not respond to Protocol V1 GetFeatures or Protocol V2 Ping');
1308
1695
  }
1309
1696
  clearProbeProtocol(uuid, protocol) {
1697
+ if (this.probingProtocols.get(uuid) === protocol) {
1698
+ this.probingProtocols.delete(uuid);
1699
+ }
1310
1700
  if (this.deviceProtocol.get(uuid) === protocol) {
1311
1701
  this.deviceProtocol.delete(uuid);
1312
1702
  }
1313
1703
  }
1314
- detectProtocol(uuid, expectedProtocol, protocolHint) {
1704
+ getActiveProtocol(uuid) {
1705
+ var _a;
1706
+ return (_a = this.deviceProtocol.get(uuid)) !== null && _a !== void 0 ? _a : this.probingProtocols.get(uuid);
1707
+ }
1708
+ detectProtocol(uuid, expectedProtocol, protocolHint, rebuildTransport) {
1709
+ var _a;
1315
1710
  return __awaiter(this, void 0, void 0, function* () {
1711
+ if (reactNative.Platform.OS === 'ios' && expectedProtocol === 'V1') {
1712
+ this.deviceProtocol.set(uuid, expectedProtocol);
1713
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] protocol selected', {
1714
+ deviceId: uuid,
1715
+ protocol: expectedProtocol,
1716
+ source: 'expected',
1717
+ });
1718
+ return expectedProtocol;
1719
+ }
1316
1720
  if (expectedProtocol === 'V1') {
1317
1721
  if (yield this.probeProtocolV1(uuid)) {
1318
1722
  this.deviceProtocol.set(uuid, 'V1');
1723
+ this.sessionProtocols.set(uuid, 'V1');
1319
1724
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] protocol detected', {
1320
1725
  deviceId: uuid,
1321
1726
  protocol: 'V1',
@@ -1323,26 +1728,48 @@ class ReactNativeBleTransport {
1323
1728
  });
1324
1729
  return 'V1';
1325
1730
  }
1326
- throw this.createProtocolMismatchError(expectedProtocol);
1731
+ throw this.createProtocolMismatchError(expectedProtocol, uuid);
1327
1732
  }
1328
1733
  if (expectedProtocol === 'V2') {
1329
- this.deviceProtocol.set(uuid, 'V2');
1330
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] protocol detected', {
1331
- deviceId: uuid,
1332
- protocol: 'V2',
1333
- source: 'expected',
1334
- });
1335
- return 'V2';
1336
- }
1337
- const probeOrder = protocolHint === 'V2' || this.deviceProtocol.get(uuid) === 'V2' ? ['V2', 'V1'] : ['V1', 'V2'];
1734
+ if (yield this.probeProtocolV2(uuid)) {
1735
+ this.deviceProtocol.set(uuid, 'V2');
1736
+ this.sessionProtocols.set(uuid, 'V2');
1737
+ this.confirmedProtocolV2.add(uuid);
1738
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] protocol detected', {
1739
+ deviceId: uuid,
1740
+ protocol: 'V2',
1741
+ source: 'expected',
1742
+ });
1743
+ return 'V2';
1744
+ }
1745
+ throw this.createProtocolMismatchError(expectedProtocol, uuid);
1746
+ }
1747
+ const sessionProtocol = this.sessionProtocols.get(uuid);
1748
+ const reprobeFailures = (_a = this.protocolReprobeFailures.get(uuid)) !== null && _a !== void 0 ? _a : 0;
1749
+ const fullProbeOrder = protocolHint === 'V2' || this.deviceProtocol.get(uuid) === 'V2' ? ['V2', 'V1'] : ['V1', 'V2'];
1750
+ const trustSessionProtocol = sessionProtocol !== undefined &&
1751
+ !protocolHint &&
1752
+ reprobeFailures < PROTOCOL_REPROBE_FALLBACK_ATTEMPTS;
1753
+ const probeOrder = trustSessionProtocol ? [sessionProtocol] : fullProbeOrder;
1338
1754
  for (let i = 0; i < probeOrder.length; i += 1) {
1339
1755
  const protocol = probeOrder[i];
1340
1756
  if (i > 0) {
1341
1757
  yield this.resetProbeStateAfterProtocolProbe(uuid, probeOrder[i - 1]);
1758
+ if (!transportCache[uuid]) {
1759
+ if (!rebuildTransport) {
1760
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
1761
+ }
1762
+ yield rebuildTransport();
1763
+ }
1342
1764
  }
1343
1765
  const detected = protocol === 'V1' ? yield this.probeProtocolV1(uuid) : yield this.probeProtocolV2(uuid);
1344
1766
  if (detected) {
1345
1767
  this.deviceProtocol.set(uuid, protocol);
1768
+ this.sessionProtocols.set(uuid, protocol);
1769
+ if (protocol === 'V2') {
1770
+ this.confirmedProtocolV2.add(uuid);
1771
+ }
1772
+ this.protocolReprobeFailures.delete(uuid);
1346
1773
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] protocol detected', {
1347
1774
  deviceId: uuid,
1348
1775
  protocol,
@@ -1351,7 +1778,14 @@ class ReactNativeBleTransport {
1351
1778
  return protocol;
1352
1779
  }
1353
1780
  }
1781
+ if (trustSessionProtocol) {
1782
+ this.protocolReprobeFailures.set(uuid, reprobeFailures + 1);
1783
+ }
1784
+ else {
1785
+ this.protocolReprobeFailures.delete(uuid);
1786
+ }
1354
1787
  this.deviceProtocol.delete(uuid);
1788
+ this.probingProtocols.delete(uuid);
1355
1789
  throw this.createProtocolDetectionError();
1356
1790
  });
1357
1791
  }
@@ -1403,13 +1837,17 @@ class ReactNativeBleTransport {
1403
1837
  return false;
1404
1838
  }
1405
1839
  try {
1406
- this.deviceProtocol.set(uuid, 'V1');
1407
- yield this.callProtocolV1(uuid, 'Initialize', {}, { timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS });
1840
+ this.probingProtocols.set(uuid, 'V1');
1841
+ yield this.callProtocolV1(uuid, 'GetFeatures', {}, { timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS });
1842
+ this.probingProtocols.delete(uuid);
1408
1843
  return true;
1409
1844
  }
1410
1845
  catch (error) {
1411
1846
  this.clearProbeProtocol(uuid, 'V1');
1412
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V1 Initialize probe failed:', error);
1847
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V1 GetFeatures probe failed:', error);
1848
+ if (isWedgedWriteError(error)) {
1849
+ throw error;
1850
+ }
1413
1851
  return false;
1414
1852
  }
1415
1853
  });
@@ -1420,7 +1858,7 @@ class ReactNativeBleTransport {
1420
1858
  if (!this._messages || !this._messagesV2) {
1421
1859
  return false;
1422
1860
  }
1423
- this.deviceProtocol.set(uuid, 'V2');
1861
+ this.probingProtocols.set(uuid, 'V2');
1424
1862
  (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
1425
1863
  const detected = yield transport.probeProtocolV2({
1426
1864
  call: (name, data, options) => this.callProtocolV2(uuid, name, data, options),
@@ -1436,6 +1874,9 @@ class ReactNativeBleTransport {
1436
1874
  if (!detected) {
1437
1875
  this.clearProbeProtocol(uuid, 'V2');
1438
1876
  }
1877
+ else {
1878
+ this.probingProtocols.delete(uuid);
1879
+ }
1439
1880
  return detected;
1440
1881
  });
1441
1882
  }
@@ -1478,16 +1919,8 @@ class ReactNativeBleTransport {
1478
1919
  }
1479
1920
  this.getProtocolV2FrameQueue(uuid).push(frame);
1480
1921
  }
1481
- rejectAllProtocolV2Frames(error) {
1482
- this.protocolV2FrameQueues.clear();
1483
- for (const framePromise of this.protocolV2FramePromises.values()) {
1484
- framePromise.reject(error);
1485
- }
1486
- this.protocolV2FramePromises.clear();
1487
- }
1488
1922
  resetProtocolV2Frames(uuid) {
1489
- this.protocolV2FrameQueues.delete(uuid);
1490
- this.protocolV2FramePromises.delete(uuid);
1923
+ this.rejectProtocolV2Frames(uuid, new Error(`Protocol V2 frame state reset for ${uuid}`));
1491
1924
  }
1492
1925
  rejectProtocolV2Frames(uuid, error) {
1493
1926
  this.protocolV2FrameQueues.delete(uuid);
@@ -1515,20 +1948,70 @@ class ReactNativeBleTransport {
1515
1948
  }
1516
1949
  });
1517
1950
  }
1518
- writeProtocolV2Frame(transport, frame) {
1951
+ writeProtocolV2Packet(uuid, transport, base64, context, assertCurrentGeneration) {
1952
+ return __awaiter(this, void 0, void 0, function* () {
1953
+ const shouldUseWriteWithResponse = shouldWriteProtocolV2WithResponse({
1954
+ platform: reactNative.Platform.OS,
1955
+ highThroughput: context.highThroughput,
1956
+ requestedWithResponse: context.writeWithResponse,
1957
+ characteristic: transport.writeCharacteristic,
1958
+ });
1959
+ let attempt = 0;
1960
+ for (;;) {
1961
+ assertCurrentGeneration();
1962
+ if (context.signal.aborted) {
1963
+ throw new Error(`Protocol V2 BLE write aborted for ${context.messageName}`);
1964
+ }
1965
+ try {
1966
+ yield this.writeBlePacket(uuid, base64, payload => shouldUseWriteWithResponse
1967
+ ? transport.writeCharacteristic.writeWithResponse(payload)
1968
+ : transport.writeCharacteristic.writeWithoutResponse(payload), () => {
1969
+ try {
1970
+ assertCurrentGeneration();
1971
+ return !context.signal.aborted;
1972
+ }
1973
+ catch (_a) {
1974
+ return false;
1975
+ }
1976
+ });
1977
+ assertCurrentGeneration();
1978
+ return;
1979
+ }
1980
+ catch (error) {
1981
+ if (getFirmwareUploadWriteRetryType(error) !== 'congested' ||
1982
+ attempt >= FIRMWARE_UPLOAD_WRITE_MAX_RETRIES) {
1983
+ throw error;
1984
+ }
1985
+ const delayMs = resolveFirmwareUploadRetryDelay(attempt);
1986
+ attempt += 1;
1987
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 congested write retry:', {
1988
+ name: context.messageName,
1989
+ attempt,
1990
+ delayMs,
1991
+ });
1992
+ yield delay(delayMs);
1993
+ }
1994
+ }
1995
+ });
1996
+ }
1997
+ writeProtocolV2Frame(uuid, transport$1, frame, context, assertCurrentGeneration) {
1519
1998
  return __awaiter(this, void 0, void 0, function* () {
1520
1999
  const tuning = getProtocolV2BleTuning();
1521
2000
  const packetCapacity = resolveProtocolV2PacketCapacity({
1522
2001
  platform: reactNative.Platform.OS,
1523
2002
  iosPacketLength: tuning.iosPacketLength,
1524
2003
  androidPacketLength: tuning.androidPacketLength,
1525
- mtu: reactNative.Platform.OS === 'android' ? transport.mtuSize : undefined,
2004
+ mtu: transport$1.mtuSize,
2005
+ });
2006
+ yield transport.writeProtocolV2BleFrame({
2007
+ frame,
2008
+ packetCapacity,
2009
+ assertActive: assertCurrentGeneration,
2010
+ signal: context.signal,
2011
+ abortMessage: `Protocol V2 BLE write aborted for ${context.messageName}`,
2012
+ wait: delay,
2013
+ writePacket: packet => this.writeProtocolV2Packet(uuid, transport$1, buffer.Buffer.from(packet).toString('base64'), context, assertCurrentGeneration),
1526
2014
  });
1527
- for (let offset = 0; offset < frame.length; offset += packetCapacity) {
1528
- const chunk = frame.slice(offset, offset + packetCapacity);
1529
- const base64 = buffer.Buffer.from(chunk).toString('base64');
1530
- yield transport.writeCharacteristic.writeWithoutResponse(base64);
1531
- }
1532
2015
  });
1533
2016
  }
1534
2017
  callProtocolV2(uuid, name, data, options) {
@@ -1537,15 +2020,40 @@ class ReactNativeBleTransport {
1537
2020
  if (!this._messages || !this._messagesV2) {
1538
2021
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
1539
2022
  }
1540
- const callOptions = Object.assign(Object.assign({}, options), { timeoutMs: (_a = options === null || options === void 0 ? void 0 : options.timeoutMs) !== null && _a !== void 0 ? _a : BLE_RESPONSE_TIMEOUT_MS });
1541
- const highVolumeWrite = transport.LogBlockCommand.has(name);
1542
- if (highVolumeWrite) {
2023
+ const callOptions = options;
2024
+ const highThroughputWrite = transport.isProtocolV2HighThroughputCall(name);
2025
+ if (highThroughputWrite) {
2026
+ yield this.ensureProtocolV2HighThroughputMtu(uuid);
1543
2027
  const tuning = getProtocolV2BleTuning();
1544
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 high-volume write configured', {
1545
- name,
1546
- writeMode: 'withoutResponse',
1547
- packetCapacity: reactNative.Platform.OS === 'ios' ? tuning.iosPacketLength : tuning.androidPacketLength,
2028
+ const currentTransport = this.getCachedTransport(uuid);
2029
+ const writeWithResponse = shouldWriteProtocolV2WithResponse({
2030
+ platform: reactNative.Platform.OS,
2031
+ highThroughput: true,
2032
+ requestedWithResponse: options === null || options === void 0 ? void 0 : options.writeWithResponse,
2033
+ characteristic: currentTransport.writeCharacteristic,
2034
+ });
2035
+ const packetCapacity = resolveProtocolV2PacketCapacity({
2036
+ platform: reactNative.Platform.OS,
2037
+ iosPacketLength: tuning.iosPacketLength,
2038
+ androidPacketLength: tuning.androidPacketLength,
2039
+ mtu: currentTransport.mtuSize,
1548
2040
  });
2041
+ const writeMode = writeWithResponse ? 'withResponse' : 'withoutResponse';
2042
+ const logSignature = `${name}:${writeMode}:${String(currentTransport.mtuSize)}:${packetCapacity}`;
2043
+ const loggedSignatures = (_a = this.protocolV2HighVolumeLogSignatures.get(uuid)) !== null && _a !== void 0 ? _a : new Set();
2044
+ if (!loggedSignatures.has(logSignature)) {
2045
+ loggedSignatures.add(logSignature);
2046
+ this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
2047
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 high-volume write configured', {
2048
+ name,
2049
+ writeMode,
2050
+ reportedMtu: currentTransport.mtuSize,
2051
+ packetCapacity,
2052
+ });
2053
+ }
2054
+ }
2055
+ if (highThroughputWrite) {
2056
+ yield this.enableAndroidHighConnectionPriority(uuid);
1549
2057
  }
1550
2058
  try {
1551
2059
  return yield this.protocolV2Links.call(uuid, () => this.createProtocolV2Adapter(uuid), name, data, callOptions);
@@ -1554,6 +2062,85 @@ class ReactNativeBleTransport {
1554
2062
  Log === null || Log === void 0 ? void 0 : Log.error('[ReactNativeBleTransport] Protocol V2 call error:', e);
1555
2063
  throw e;
1556
2064
  }
2065
+ finally {
2066
+ if (highThroughputWrite) {
2067
+ this.scheduleAndroidBalancedConnectionPriority(uuid);
2068
+ }
2069
+ }
2070
+ });
2071
+ }
2072
+ ensureProtocolV2HighThroughputMtu(uuid) {
2073
+ return __awaiter(this, void 0, void 0, function* () {
2074
+ const transport = this.getCachedTransport(uuid);
2075
+ if (!shouldRefreshNegotiatedMtu(transport.mtuSize))
2076
+ return;
2077
+ const refreshedDevice = yield requestNegotiatedMtu(transport.device, 'highThroughput', 1);
2078
+ transport.device = refreshedDevice;
2079
+ transport.mtuSize =
2080
+ typeof refreshedDevice.mtu === 'number' ? refreshedDevice.mtu : transport.mtuSize;
2081
+ if (shouldRefreshNegotiatedMtu(transport.mtuSize)) {
2082
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, `Protocol V2 high-throughput BLE MTU unavailable: ${String(transport.mtuSize)}`);
2083
+ }
2084
+ });
2085
+ }
2086
+ clearAndroidPriorityResetTimer(uuid) {
2087
+ const timerId = this.androidPriorityResetTimers.get(uuid);
2088
+ if (timerId !== undefined) {
2089
+ clearTimeout(timerId);
2090
+ this.androidPriorityResetTimers.delete(uuid);
2091
+ }
2092
+ }
2093
+ enableAndroidHighConnectionPriority(uuid) {
2094
+ return __awaiter(this, void 0, void 0, function* () {
2095
+ if (reactNative.Platform.OS !== 'android')
2096
+ return;
2097
+ this.clearAndroidPriorityResetTimer(uuid);
2098
+ if (this.androidHighPriorityDevices.has(uuid))
2099
+ return;
2100
+ const transport = transportCache[uuid];
2101
+ if (!transport)
2102
+ return;
2103
+ try {
2104
+ transport.device = yield transport.device.requestConnectionPriority(reactNativeBlePlx.ConnectionPriority.High);
2105
+ this.androidHighPriorityDevices.add(uuid);
2106
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android BLE connection priority changed', {
2107
+ priority: 'high',
2108
+ });
2109
+ }
2110
+ catch (error) {
2111
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android BLE high priority request failed', {
2112
+ error: error instanceof Error ? error.message : String(error),
2113
+ });
2114
+ }
2115
+ });
2116
+ }
2117
+ scheduleAndroidBalancedConnectionPriority(uuid) {
2118
+ if (reactNative.Platform.OS !== 'android' || !this.androidHighPriorityDevices.has(uuid))
2119
+ return;
2120
+ this.clearAndroidPriorityResetTimer(uuid);
2121
+ const timerId = setTimeout(() => {
2122
+ this.androidPriorityResetTimers.delete(uuid);
2123
+ this.restoreAndroidConnectionPriority(uuid, transportCache[uuid]).catch(error => Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android BLE priority restore failed', error));
2124
+ }, ANDROID_HIGH_PRIORITY_IDLE_MS);
2125
+ this.androidPriorityResetTimers.set(uuid, timerId);
2126
+ }
2127
+ restoreAndroidConnectionPriority(uuid, transport) {
2128
+ return __awaiter(this, void 0, void 0, function* () {
2129
+ this.clearAndroidPriorityResetTimer(uuid);
2130
+ if (reactNative.Platform.OS !== 'android' || !this.androidHighPriorityDevices.delete(uuid) || !transport) {
2131
+ return;
2132
+ }
2133
+ try {
2134
+ transport.device = yield transport.device.requestConnectionPriority(reactNativeBlePlx.ConnectionPriority.Balanced);
2135
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android BLE connection priority changed', {
2136
+ priority: 'balanced',
2137
+ });
2138
+ }
2139
+ catch (error) {
2140
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android BLE balanced priority request failed', {
2141
+ error: error instanceof Error ? error.message : String(error),
2142
+ });
2143
+ }
1557
2144
  });
1558
2145
  }
1559
2146
  createProtocolV2Adapter(uuid) {
@@ -1574,10 +2161,10 @@ class ReactNativeBleTransport {
1574
2161
  (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
1575
2162
  this.resetProtocolV2Frames(uuid);
1576
2163
  },
1577
- writeFrame: (frame) => __awaiter(this, void 0, void 0, function* () {
2164
+ writeFrame: (frame, context) => __awaiter(this, void 0, void 0, function* () {
1578
2165
  assertCurrentGeneration();
1579
2166
  const currentTransport = this.getCachedTransport(uuid);
1580
- yield this.writeProtocolV2Frame(currentTransport, frame);
2167
+ yield this.writeProtocolV2Frame(uuid, currentTransport, frame, context, assertCurrentGeneration);
1581
2168
  }),
1582
2169
  readFrame: () => __awaiter(this, void 0, void 0, function* () {
1583
2170
  assertCurrentGeneration();
@@ -1589,6 +2176,8 @@ class ReactNativeBleTransport {
1589
2176
  }),
1590
2177
  reset: (reason) => {
1591
2178
  var _a;
2179
+ if (this.monitorTokens.get(uuid) !== generation)
2180
+ return;
1592
2181
  (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
1593
2182
  this.rejectProtocolV2Frames(uuid, new Error(reason));
1594
2183
  },
@@ -1598,11 +2187,20 @@ class ReactNativeBleTransport {
1598
2187
  };
1599
2188
  }
1600
2189
  getProtocolType(path) {
1601
- return this.deviceProtocol.get(path);
2190
+ return this.getActiveProtocol(path);
1602
2191
  }
1603
2192
  }
1604
2193
 
2194
+ exports.BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD = BLE_CONNECT_TIMEOUT_MANAGER_RESET_THRESHOLD;
2195
+ exports.BLE_CONNECT_TIMEOUT_MS = BLE_CONNECT_TIMEOUT_MS;
2196
+ exports.BLE_GATT_SETUP_TIMEOUT_MS = BLE_GATT_SETUP_TIMEOUT_MS;
2197
+ exports.BLE_NATIVE_TEARDOWN_TIMEOUT_MS = BLE_NATIVE_TEARDOWN_TIMEOUT_MS;
2198
+ exports.BLE_SETUP_WEDGED_MESSAGE = BLE_SETUP_WEDGED_MESSAGE;
2199
+ exports.BLE_WRITE_PACKET_TIMEOUT_MS = BLE_WRITE_PACKET_TIMEOUT_MS;
2200
+ exports.BLE_WRITE_TIMEOUT_MANAGER_RESET_THRESHOLD = BLE_WRITE_TIMEOUT_MANAGER_RESET_THRESHOLD;
2201
+ exports.PROTOCOL_REPROBE_FALLBACK_ATTEMPTS = PROTOCOL_REPROBE_FALLBACK_ATTEMPTS;
1605
2202
  exports.configureProtocolV2BleTuning = configureProtocolV2BleTuning;
1606
2203
  exports["default"] = ReactNativeBleTransport;
2204
+ exports.getFirmwareUploadWriteRetryType = getFirmwareUploadWriteRetryType;
1607
2205
  exports.getProtocolV2BleTuning = getProtocolV2BleTuning;
1608
2206
  exports.resetProtocolV2BleTuning = resetProtocolV2BleTuning;