@onekeyfe/hd-transport-react-native 1.1.27-alpha.34 → 1.1.27-alpha.4

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
@@ -1,13 +1,12 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
3
  var reactNative = require('react-native');
6
4
  var buffer = require('buffer');
7
5
  var reactNativeBlePlx = require('react-native-ble-plx');
8
6
  var ByteBuffer = require('bytebuffer');
9
7
  var transport = require('@onekeyfe/hd-transport');
10
8
  var hdShared = require('@onekeyfe/hd-shared');
9
+ var hdCore = require('@onekeyfe/hd-core');
11
10
  var BleUtils = require('@onekeyfe/react-native-ble-utils');
12
11
 
13
12
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
@@ -46,17 +45,7 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
46
45
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
47
46
  };
48
47
 
49
- let activeLogger;
50
- const setBleLogger = (logger) => {
51
- activeLogger = logger;
52
- };
53
- const bleLogger = {
54
- debug: (...args) => { var _a; return (_a = activeLogger === null || activeLogger === void 0 ? void 0 : activeLogger.debug) === null || _a === void 0 ? void 0 : _a.call(activeLogger, ...args); },
55
- error: (...args) => { var _a; return (_a = activeLogger === null || activeLogger === void 0 ? void 0 : activeLogger.error) === null || _a === void 0 ? void 0 : _a.call(activeLogger, ...args); },
56
- warn: (...args) => { var _a; return (_a = activeLogger === null || activeLogger === void 0 ? void 0 : activeLogger.warn) === null || _a === void 0 ? void 0 : _a.call(activeLogger, ...args); },
57
- };
58
-
59
- const Logger = bleLogger;
48
+ const Logger = hdCore.getLogger(hdCore.LoggerNames.HdBleTransport);
60
49
  const getConnectedDeviceIds = (serviceUuids) => BleUtils__default["default"].getConnectedPeripherals(serviceUuids);
61
50
  const pairDevice = (macAddress) => BleUtils__default["default"].pairDevice(macAddress);
62
51
  const onDeviceBondState = (bleMacAddress) => new Promise((resolve, reject) => {
@@ -156,43 +145,30 @@ for (const deviceType of Object.keys(OneKeyServices)) {
156
145
  }
157
146
  const getBluetoothServiceUuids = () => bluetoothServices;
158
147
  const getInfosForServiceUuid = (serviceUuid, deviceType) => {
159
- var _a;
160
148
  const services = OneKeyServices[deviceType];
161
149
  if (!services) {
162
150
  return null;
163
151
  }
164
- const normalizedServiceUuid = normalizeBleUuid(serviceUuid);
165
- const service = (_a = services[serviceUuid]) !== null && _a !== void 0 ? _a : Object.values(services).find(item => normalizeBleUuid(item.serviceUuid) === normalizedServiceUuid);
152
+ const service = services[serviceUuid];
166
153
  if (!service) {
167
154
  return null;
168
155
  }
169
156
  return service;
170
157
  };
171
- const normalizeBleUuid = (uuid) => (uuid !== null && uuid !== void 0 ? uuid : '').replace(/-/g, '').toLowerCase();
172
- const getBleUuidKey = (uuid) => {
173
- const normalized = normalizeBleUuid(uuid);
174
- return normalized.length >= 8 ? normalized.substring(4, 8) : normalized;
175
- };
176
- const isSameBleUuid = (left, right) => {
177
- const normalizedLeft = normalizeBleUuid(left);
178
- const normalizedRight = normalizeBleUuid(right);
179
- return (normalizedLeft === normalizedRight ||
180
- (getBleUuidKey(left) !== '' && getBleUuidKey(left) === getBleUuidKey(right)));
181
- };
182
158
 
183
159
  const isHeaderChunk = (chunk) => {
184
160
  if (chunk.length < 9)
185
161
  return false;
186
162
  const [MagicQuestionMark, sharp1, sharp2] = chunk;
187
- if (String.fromCharCode(MagicQuestionMark) === String.fromCharCode(transport.PROTOCOL_V1_REPORT_ID) &&
188
- String.fromCharCode(sharp1) === String.fromCharCode(transport.PROTOCOL_V1_HEADER_BYTE) &&
189
- String.fromCharCode(sharp2) === String.fromCharCode(transport.PROTOCOL_V1_HEADER_BYTE)) {
163
+ if (String.fromCharCode(MagicQuestionMark) === String.fromCharCode(transport.MESSAGE_TOP_CHAR) &&
164
+ String.fromCharCode(sharp1) === String.fromCharCode(transport.MESSAGE_HEADER_BYTE) &&
165
+ String.fromCharCode(sharp2) === String.fromCharCode(transport.MESSAGE_HEADER_BYTE)) {
190
166
  return true;
191
167
  }
192
168
  return false;
193
169
  };
194
170
 
195
- const Log$1 = bleLogger;
171
+ const Log$1 = hdCore.getLogger(hdCore.LoggerNames.HdBleTransport);
196
172
  class BleTransport {
197
173
  constructor(device, writeCharacteristic, notifyCharacteristic) {
198
174
  this.name = 'ReactNativeBleTransport';
@@ -211,7 +187,7 @@ class BleTransport {
211
187
  catch (error) {
212
188
  Log$1 === null || Log$1 === void 0 ? void 0 : Log$1.debug(`Write retry attempt ${BleTransport.MAX_RETRIES - retryCount + 1}, error: ${error}`);
213
189
  if (retryCount > 0) {
214
- yield hdShared.wait(BleTransport.RETRY_DELAY);
190
+ yield hdCore.wait(BleTransport.RETRY_DELAY);
215
191
  if (error.errorCode === reactNativeBlePlx.BleErrorCode.DeviceDisconnected ||
216
192
  error.errorCode === reactNativeBlePlx.BleErrorCode.CharacteristicNotFound) {
217
193
  try {
@@ -235,67 +211,9 @@ class BleTransport {
235
211
  BleTransport.MAX_RETRIES = 5;
236
212
  BleTransport.RETRY_DELAY = 2000;
237
213
 
238
- const { check, ProtocolV1, parseConfigure } = transport__default["default"];
239
- const Log = bleLogger;
214
+ const { check, buildBuffers, receiveOne, parseConfigure } = transport__default["default"];
215
+ const Log = hdCore.getLogger(hdCore.LoggerNames.HdBleTransport);
240
216
  const transportCache = {};
241
- const BLE_RESPONSE_TIMEOUT_MS = 30000;
242
- const PROTOCOL_PROBE_TIMEOUT_MS = 1000;
243
- const PROTOCOL_V2_PROBE_TIMEOUT_MS = 5000;
244
- const DEVICE_SCAN_TIMEOUT_MS = 8000;
245
- const IOS_NOTIFY_READY_DELAY_MS = 150;
246
- const HIGH_VOLUME_WRITE_BURST_SIZE = reactNative.Platform.OS === 'ios' ? 4 : 6;
247
- const HIGH_VOLUME_WRITE_PAUSE_MS = reactNative.Platform.OS === 'ios' ? 6 : 2;
248
- const HIGH_VOLUME_WRITE_FLUSH_DELAY_MS = reactNative.Platform.OS === 'ios' ? 20 : 8;
249
- const delay = (ms) => new Promise(resolve => {
250
- setTimeout(resolve, ms);
251
- });
252
- const DEFAULT_PROTOCOL_V2_BLE_TUNING = {
253
- iosPacketLength: IOS_PACKET_LENGTH,
254
- androidPacketLength: ANDROID_PACKET_LENGTH,
255
- highVolumeWriteBurstSize: HIGH_VOLUME_WRITE_BURST_SIZE,
256
- highVolumeWritePauseMs: HIGH_VOLUME_WRITE_PAUSE_MS,
257
- highVolumeWriteFlushDelayMs: HIGH_VOLUME_WRITE_FLUSH_DELAY_MS,
258
- highVolumeWriteWithResponse: false,
259
- };
260
- let protocolV2BleTuning = Object.assign({}, DEFAULT_PROTOCOL_V2_BLE_TUNING);
261
- const normalizePositiveInteger = (value, fallback) => {
262
- const normalized = Number(value);
263
- if (!Number.isFinite(normalized) || normalized <= 0)
264
- return fallback;
265
- return Math.floor(normalized);
266
- };
267
- function configureProtocolV2BleTuning(tuning = {}) {
268
- var _a;
269
- protocolV2BleTuning = {
270
- iosPacketLength: normalizePositiveInteger(tuning.iosPacketLength, protocolV2BleTuning.iosPacketLength),
271
- androidPacketLength: normalizePositiveInteger(tuning.androidPacketLength, protocolV2BleTuning.androidPacketLength),
272
- highVolumeWriteBurstSize: normalizePositiveInteger(tuning.highVolumeWriteBurstSize, protocolV2BleTuning.highVolumeWriteBurstSize),
273
- highVolumeWritePauseMs: normalizePositiveInteger(tuning.highVolumeWritePauseMs, protocolV2BleTuning.highVolumeWritePauseMs),
274
- highVolumeWriteFlushDelayMs: normalizePositiveInteger(tuning.highVolumeWriteFlushDelayMs, protocolV2BleTuning.highVolumeWriteFlushDelayMs),
275
- highVolumeWriteWithResponse: (_a = tuning.highVolumeWriteWithResponse) !== null && _a !== void 0 ? _a : protocolV2BleTuning.highVolumeWriteWithResponse,
276
- };
277
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 BLE tuning configured:', protocolV2BleTuning);
278
- }
279
- function resetProtocolV2BleTuning() {
280
- protocolV2BleTuning = Object.assign({}, DEFAULT_PROTOCOL_V2_BLE_TUNING);
281
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 BLE tuning reset:', protocolV2BleTuning);
282
- }
283
- function getProtocolV2BleTuning() {
284
- return Object.assign({}, protocolV2BleTuning);
285
- }
286
- function inferProtocolHintFromDeviceName(name) {
287
- return /\bpro\s*2\b/i.test(name !== null && name !== void 0 ? name : '') ? 'V2' : undefined;
288
- }
289
- function getDeviceDisplayName(device) {
290
- return (device === null || device === void 0 ? void 0 : device.name) || (device === null || device === void 0 ? void 0 : device.localName) || null;
291
- }
292
- function isGenericBleService(uuid) {
293
- return ['1800', '1801', '180a'].includes(getBleUuidKey(uuid));
294
- }
295
- function hasKnownOneKeyService(device) {
296
- var _a;
297
- return ((_a = device === null || device === void 0 ? void 0 : device.serviceUUIDs) !== null && _a !== void 0 ? _a : []).some(serviceUuid => getInfosForServiceUuid(serviceUuid, 'classic'));
298
- }
299
217
  let connectOptions = {
300
218
  requestMTU: 256,
301
219
  timeout: 3000,
@@ -304,9 +222,7 @@ let connectOptions = {
304
222
  const tryToGetConfiguration = (device) => {
305
223
  if (!device || !device.serviceUUIDs)
306
224
  return null;
307
- const serviceUUID = device.serviceUUIDs.find(uuid => getInfosForServiceUuid(uuid, 'classic'));
308
- if (!serviceUUID)
309
- return null;
225
+ const [serviceUUID] = device.serviceUUIDs;
310
226
  const infos = getInfosForServiceUuid(serviceUUID, 'classic');
311
227
  if (!infos)
312
228
  return null;
@@ -336,21 +252,11 @@ class ReactNativeBleTransport {
336
252
  this.name = 'ReactNativeBleTransport';
337
253
  this.configured = false;
338
254
  this.stopped = false;
339
- this.scanTimeout = DEVICE_SCAN_TIMEOUT_MS;
255
+ this.scanTimeout = 3000;
340
256
  this.runPromise = null;
341
- this.deviceProtocol = new Map();
342
- this.deviceProtocolHints = new Map();
343
- this.protocolV2Assemblers = new Map();
344
- this.protocolV2FrameQueues = new Map();
345
- this.protocolV2FramePromises = new Map();
346
- this.activeProtocolV2Call = null;
347
- this.nextProtocolV2CallToken = 1;
348
- this.monitorTokens = new Map();
349
- this.nextMonitorToken = 1;
350
- this.scanTimeout = (_a = options.scanTimeout) !== null && _a !== void 0 ? _a : DEVICE_SCAN_TIMEOUT_MS;
257
+ this.scanTimeout = (_a = options.scanTimeout) !== null && _a !== void 0 ? _a : 3000;
351
258
  }
352
- init(logger, emitter) {
353
- setBleLogger(logger);
259
+ init(_logger, emitter) {
354
260
  this.emitter = emitter;
355
261
  }
356
262
  configure(signedData) {
@@ -358,10 +264,6 @@ class ReactNativeBleTransport {
358
264
  this.configured = true;
359
265
  this._messages = messages;
360
266
  }
361
- configureProtocolV2(signedData) {
362
- this._messagesV2 = parseConfigure(signedData);
363
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 schema configured');
364
- }
365
267
  listen() {
366
268
  }
367
269
  getPlxManager() {
@@ -397,10 +299,9 @@ class ReactNativeBleTransport {
397
299
  }
398
300
  }
399
301
  blePlxManager.startDeviceScan(null, {
400
- allowDuplicates: true,
401
302
  scanMode: reactNativeBlePlx.ScanMode.LowLatency,
402
303
  }, (error, device) => {
403
- var _a, _b, _c;
304
+ var _a, _b;
404
305
  if (error) {
405
306
  Log === null || Log === void 0 ? void 0 : Log.debug('ble scan manager: ', blePlxManager);
406
307
  Log === null || Log === void 0 ? void 0 : Log.debug('ble scan error: ', error);
@@ -421,35 +322,13 @@ class ReactNativeBleTransport {
421
322
  }
422
323
  return;
423
324
  }
424
- const displayName = getDeviceDisplayName(device);
425
- 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) ||
426
- 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) ||
427
- hasKnownOneKeyService(device);
428
- const shouldTraceCandidate = !!displayName && /onekey|bixinkey|pro\s*2|pro\b|touch|^k\d|^t\d/i.test(displayName);
429
- if (shouldTraceCandidate) {
430
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] scan candidate', {
431
- name: device === null || device === void 0 ? void 0 : device.name,
432
- localName: device === null || device === void 0 ? void 0 : device.localName,
433
- id: device === null || device === void 0 ? void 0 : device.id,
434
- serviceUUIDs: device === null || device === void 0 ? void 0 : device.serviceUUIDs,
435
- accepted: isOneKey,
436
- });
437
- }
438
- if (isOneKey) {
325
+ if (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)) {
439
326
  Log === null || Log === void 0 ? void 0 : Log.debug('search device start ======================');
440
- const { name, localName, id, serviceUUIDs } = device !== null && device !== void 0 ? device : {};
441
- Log === null || Log === void 0 ? void 0 : Log.debug(`device name: ${name !== null && name !== void 0 ? name : ''}\nlocalName: ${localName !== null && localName !== void 0 ? localName : ''}\nid: ${id !== null && id !== void 0 ? id : ''}\nserviceUUIDs: ${(serviceUUIDs !== null && serviceUUIDs !== void 0 ? serviceUUIDs : []).join(',')}`);
327
+ const { name, localName, id } = device !== null && device !== void 0 ? device : {};
328
+ Log === null || Log === void 0 ? void 0 : Log.debug(`device name: ${name !== null && name !== void 0 ? name : ''}\nlocalName: ${localName !== null && localName !== void 0 ? localName : ''}\nid: ${id !== null && id !== void 0 ? id : ''}`);
442
329
  addDevice(device);
443
330
  Log === null || Log === void 0 ? void 0 : Log.debug('search device end ======================\n');
444
331
  }
445
- else if (displayName && /\bpro\s*2\b/i.test(displayName)) {
446
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Pro2-like BLE device was not accepted:', {
447
- name: device === null || device === void 0 ? void 0 : device.name,
448
- localName: device === null || device === void 0 ? void 0 : device.localName,
449
- id: device === null || device === void 0 ? void 0 : device.id,
450
- serviceUUIDs: device === null || device === void 0 ? void 0 : device.serviceUUIDs,
451
- });
452
- }
453
332
  });
454
333
  getConnectedDeviceIds(getBluetoothServiceUuids()).then(devices => {
455
334
  for (const device of devices) {
@@ -458,14 +337,8 @@ class ReactNativeBleTransport {
458
337
  }
459
338
  });
460
339
  const addDevice = (device) => {
461
- var _a;
462
340
  if (deviceList.every(d => d.id !== device.id)) {
463
- const displayName = (_a = getDeviceDisplayName(device)) !== null && _a !== void 0 ? _a : 'Unknown BLE Device';
464
- const protocolHint = inferProtocolHintFromDeviceName(displayName);
465
- if (protocolHint) {
466
- this.deviceProtocolHints.set(device.id, protocolHint);
467
- }
468
- deviceList.push(Object.assign(Object.assign({}, device), { name: displayName, commType: 'ble' }));
341
+ deviceList.push(Object.assign(Object.assign({}, device), { commType: 'ble' }));
469
342
  }
470
343
  };
471
344
  timer.timeout(() => {
@@ -476,9 +349,9 @@ class ReactNativeBleTransport {
476
349
  });
477
350
  }
478
351
  acquire(input) {
479
- var _a, _b, _c, _d, _e, _f;
352
+ var _a;
480
353
  return __awaiter(this, void 0, void 0, function* () {
481
- const { uuid, forceCleanRunPromise, expectedProtocol } = input;
354
+ const { uuid, forceCleanRunPromise } = input;
482
355
  if (!uuid) {
483
356
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleRequiredUUID);
484
357
  }
@@ -488,11 +361,7 @@ class ReactNativeBleTransport {
488
361
  yield this.release(uuid);
489
362
  }
490
363
  if (forceCleanRunPromise && this.runPromise) {
491
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleForceCleanRunPromise);
492
- this.runPromise.reject(error);
493
- this.rejectAllProtocolV2Frames(error);
494
- this.runPromise = null;
495
- this.activeProtocolV2Call = null;
364
+ this.runPromise.reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleForceCleanRunPromise));
496
365
  Log === null || Log === void 0 ? void 0 : Log.debug('Force clean Bluetooth run promise, forceCleanRunPromise: ', forceCleanRunPromise);
497
366
  }
498
367
  const blePlxManager = yield this.getPlxManager();
@@ -547,7 +416,7 @@ class ReactNativeBleTransport {
547
416
  if (!(yield device.isConnected())) {
548
417
  Log === null || Log === void 0 ? void 0 : Log.debug('not connected, try to connect to device: ', uuid);
549
418
  try {
550
- device = yield device.connect(connectOptions);
419
+ yield device.connect(connectOptions);
551
420
  }
552
421
  catch (e) {
553
422
  Log === null || Log === void 0 ? void 0 : Log.debug('not connected, try to connect to device has error: ', e);
@@ -556,14 +425,14 @@ class ReactNativeBleTransport {
556
425
  connectOptions = {};
557
426
  Log === null || Log === void 0 ? void 0 : Log.debug('second try to reconnect without params');
558
427
  try {
559
- device = yield device.connect();
428
+ yield device.connect();
560
429
  }
561
430
  catch (e) {
562
431
  Log === null || Log === void 0 ? void 0 : Log.debug('last try to reconnect error: ', e);
563
432
  if (e.errorCode === reactNativeBlePlx.BleErrorCode.OperationCancelled) {
564
433
  Log === null || Log === void 0 ? void 0 : Log.debug('last try to reconnect');
565
434
  yield device.cancelConnection();
566
- device = yield device.connect();
435
+ yield device.connect();
567
436
  }
568
437
  }
569
438
  }
@@ -575,7 +444,6 @@ class ReactNativeBleTransport {
575
444
  yield device.discoverAllServicesAndCharacteristics();
576
445
  let infos = tryToGetConfiguration(device);
577
446
  let characteristics;
578
- let fallbackServiceUuid;
579
447
  if (!infos) {
580
448
  for (const serviceUuid of getBluetoothServiceUuids()) {
581
449
  try {
@@ -589,34 +457,16 @@ class ReactNativeBleTransport {
589
457
  }
590
458
  }
591
459
  if (!infos) {
592
- const services = yield device.services();
593
- 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));
594
- const knownService = services.find(service => getInfosForServiceUuid(service.uuid, 'classic'));
595
- const fallbackService = (_a = knownService !== null && knownService !== void 0 ? knownService : services.find(service => !isGenericBleService(service.uuid))) !== null && _a !== void 0 ? _a : services[0];
596
- if (fallbackService) {
597
- fallbackServiceUuid = fallbackService.uuid;
598
- characteristics = yield device.characteristicsForService(fallbackService.uuid);
599
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Using fallback BLE service:', fallbackService.uuid);
460
+ try {
461
+ Log === null || Log === void 0 ? void 0 : Log.debug('cancel connection when service not found');
462
+ yield device.cancelConnection();
600
463
  }
601
- }
602
- if (!infos) {
603
- if (!fallbackServiceUuid) {
604
- try {
605
- Log === null || Log === void 0 ? void 0 : Log.debug('cancel connection when service not found');
606
- yield device.cancelConnection();
607
- }
608
- catch (e) {
609
- Log === null || Log === void 0 ? void 0 : Log.debug('cancel connection error when service not found: ', e.message || e.reason);
610
- }
611
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound);
464
+ catch (e) {
465
+ Log === null || Log === void 0 ? void 0 : Log.debug('cancel connection error when service not found: ', e.message || e.reason);
612
466
  }
613
- }
614
- const serviceUuid = (_b = infos === null || infos === void 0 ? void 0 : infos.serviceUuid) !== null && _b !== void 0 ? _b : fallbackServiceUuid;
615
- const writeUuid = (_c = infos === null || infos === void 0 ? void 0 : infos.writeUuid) !== null && _c !== void 0 ? _c : '00000002-0000-1000-8000-00805f9b34fb';
616
- const notifyUuid = (_d = infos === null || infos === void 0 ? void 0 : infos.notifyUuid) !== null && _d !== void 0 ? _d : '00000003-0000-1000-8000-00805f9b34fb';
617
- if (!serviceUuid) {
618
467
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound);
619
468
  }
469
+ const { serviceUuid, writeUuid, notifyUuid } = infos;
620
470
  if (!characteristics) {
621
471
  characteristics = yield device.characteristicsForService(serviceUuid);
622
472
  }
@@ -626,10 +476,10 @@ class ReactNativeBleTransport {
626
476
  let writeCharacteristic;
627
477
  let notifyCharacteristic;
628
478
  for (const c of characteristics) {
629
- if (isSameBleUuid(c.uuid, writeUuid)) {
479
+ if (c.uuid === writeUuid) {
630
480
  writeCharacteristic = c;
631
481
  }
632
- else if (isSameBleUuid(c.uuid, notifyUuid)) {
482
+ else if (c.uuid === notifyUuid) {
633
483
  notifyCharacteristic = c;
634
484
  }
635
485
  }
@@ -645,40 +495,17 @@ class ReactNativeBleTransport {
645
495
  if (!notifyCharacteristic.isNotifiable) {
646
496
  throw hdShared.ERRORS.TypedError('BLECharacteristicNotNotifiable: notify characteristic not notifiable');
647
497
  }
648
- const protocolHint = expectedProtocol
649
- ? undefined
650
- : (_e = this.deviceProtocolHints.get(uuid)) !== null && _e !== void 0 ? _e : inferProtocolHintFromDeviceName(getDeviceDisplayName(device));
651
498
  yield this.release(uuid);
652
- if (protocolHint) {
653
- this.deviceProtocolHints.set(uuid, protocolHint);
654
- }
655
- const transport$1 = new BleTransport(device, writeCharacteristic, notifyCharacteristic);
656
- const monitorToken = this.nextMonitorToken;
657
- this.nextMonitorToken += 1;
658
- const notifyTransactionId = `${uuid}:notify:${monitorToken}`;
659
- transport$1.monitorToken = monitorToken;
660
- transport$1.notifyTransactionId = notifyTransactionId;
661
- this.monitorTokens.set(uuid, monitorToken);
662
- transport$1.notifySubscription = this._monitorCharacteristic(transport$1.notifyCharacteristic, uuid, monitorToken, notifyTransactionId);
663
- transportCache[uuid] = transport$1;
664
- this.protocolV2Assemblers.set(uuid, new transport.ProtocolV2FrameAssembler());
665
- if (reactNative.Platform.OS === 'ios') {
666
- yield new Promise(resolve => {
667
- setTimeout(resolve, IOS_NOTIFY_READY_DELAY_MS);
668
- });
669
- }
670
- const protocolType = yield this.detectProtocol(uuid, expectedProtocol, protocolHint);
671
- (_f = this.emitter) === null || _f === void 0 ? void 0 : _f.emit('device-connect', {
499
+ const transport = new BleTransport(device, writeCharacteristic, notifyCharacteristic);
500
+ transport.notifySubscription = this._monitorCharacteristic(transport.notifyCharacteristic, uuid);
501
+ transportCache[uuid] = transport;
502
+ (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit('device-connect', {
672
503
  name: device.name,
673
504
  id: device.id,
674
505
  connectId: device.id,
675
506
  });
676
- transport$1.disconnectSubscription = device.onDisconnected(() => {
507
+ transport.disconnectSubscription = device.onDisconnected(() => {
677
508
  var _a;
678
- if (transportCache[uuid] !== transport$1) {
679
- Log === null || Log === void 0 ? void 0 : Log.debug('device disconnect ignored for stale transport: ', device === null || device === void 0 ? void 0 : device.id);
680
- return;
681
- }
682
509
  try {
683
510
  Log === null || Log === void 0 ? void 0 : Log.debug('device disconnect: ', device === null || device === void 0 ? void 0 : device.id);
684
511
  (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit('device-disconnect', {
@@ -687,9 +514,7 @@ class ReactNativeBleTransport {
687
514
  connectId: device === null || device === void 0 ? void 0 : device.id,
688
515
  });
689
516
  if (this.runPromise) {
690
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError);
691
- this.runPromise.reject(error);
692
- this.rejectAllProtocolV2Frames(error);
517
+ this.runPromise.reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError));
693
518
  }
694
519
  }
695
520
  catch (e) {
@@ -699,21 +524,16 @@ class ReactNativeBleTransport {
699
524
  this.release(uuid);
700
525
  }
701
526
  });
702
- return { uuid, protocolType };
527
+ return { uuid };
703
528
  });
704
529
  }
705
- _monitorCharacteristic(characteristic, uuid, monitorToken, notifyTransactionId) {
530
+ _monitorCharacteristic(characteristic, uuid) {
706
531
  let bufferLength = 0;
707
532
  let buffer$1 = [];
708
533
  const subscription = characteristic.monitor((error, c) => {
709
534
  var _a, _b, _c, _d, _e, _f, _g, _h, _j;
710
- const isCurrentMonitor = this.monitorTokens.get(uuid) === monitorToken;
711
535
  if (error) {
712
536
  Log === null || Log === void 0 ? void 0 : Log.debug(`error monitor ${characteristic.uuid}, deviceId: ${characteristic.deviceID}: ${error}`);
713
- if (!isCurrentMonitor) {
714
- Log === null || Log === void 0 ? void 0 : Log.debug('monitor error ignored for stale transport: ', uuid, notifyTransactionId);
715
- return;
716
- }
717
537
  if (this.runPromise) {
718
538
  let ERROR = hdShared.HardwareErrorCode.BleCharacteristicNotifyError;
719
539
  if ((_a = error.reason) === null || _a === void 0 ? void 0 : _a.includes('The connection has timed out unexpectedly')) {
@@ -727,32 +547,20 @@ class ReactNativeBleTransport {
727
547
  ((_e = error.reason) === null || _e === void 0 ? void 0 : _e.includes('The handle is invalid')) ||
728
548
  ((_f = error.reason) === null || _f === void 0 ? void 0 : _f.includes('Writing is not permitted')) ||
729
549
  ((_g = error.reason) === null || _g === void 0 ? void 0 : _g.includes('notify change failed for device'))) {
730
- const notifyError = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleCharacteristicNotifyChangeFailure);
731
- this.runPromise.reject(notifyError);
732
- this.rejectAllProtocolV2Frames(notifyError);
550
+ this.runPromise.reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleCharacteristicNotifyChangeFailure));
733
551
  Log === null || Log === void 0 ? void 0 : Log.debug(`${hdShared.HardwareErrorCode.BleCharacteristicNotifyChangeFailure} ${error.message} ${error.reason}`);
734
552
  return;
735
553
  }
736
- const notifyError = hdShared.ERRORS.TypedError(ERROR);
737
- this.runPromise.reject(notifyError);
738
- this.rejectAllProtocolV2Frames(notifyError);
554
+ this.runPromise.reject(hdShared.ERRORS.TypedError(ERROR));
739
555
  Log === null || Log === void 0 ? void 0 : Log.debug(': monitor notify error, and has unreleased Promise', Error);
740
556
  }
741
557
  return;
742
558
  }
743
- if (!isCurrentMonitor) {
744
- Log === null || Log === void 0 ? void 0 : Log.debug('monitor data ignored for stale transport: ', uuid, notifyTransactionId);
745
- return;
746
- }
747
559
  if (!c) {
748
560
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleMonitorError);
749
561
  }
750
562
  try {
751
563
  const data = buffer.Buffer.from(c.value, 'base64');
752
- if (this.deviceProtocol.get(uuid) === 'V2') {
753
- this.handleProtocolV2Notification(uuid, new Uint8Array(data));
754
- return;
755
- }
756
564
  if (isHeaderChunk(data)) {
757
565
  bufferLength = data.readInt32BE(5);
758
566
  buffer$1 = [...data.subarray(3)];
@@ -760,7 +568,7 @@ class ReactNativeBleTransport {
760
568
  else {
761
569
  buffer$1 = buffer$1.concat([...data]);
762
570
  }
763
- if (buffer$1.length - transport.PROTOCOL_V1_MESSAGE_HEADER_SIZE >= bufferLength) {
571
+ if (buffer$1.length - transport.COMMON_HEADER_SIZE >= bufferLength) {
764
572
  const value = buffer.Buffer.from(buffer$1);
765
573
  bufferLength = 0;
766
574
  buffer$1 = [];
@@ -769,57 +577,24 @@ class ReactNativeBleTransport {
769
577
  }
770
578
  catch (error) {
771
579
  Log === null || Log === void 0 ? void 0 : Log.debug('monitor data error: ', error);
772
- const notifyError = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError);
773
- (_j = this.runPromise) === null || _j === void 0 ? void 0 : _j.reject(notifyError);
774
- this.rejectAllProtocolV2Frames(notifyError);
580
+ (_j = this.runPromise) === null || _j === void 0 ? void 0 : _j.reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError));
775
581
  }
776
- }, notifyTransactionId);
582
+ }, uuid);
777
583
  return subscription;
778
584
  }
779
585
  release(uuid) {
780
- var _a, _b, _c, _d, _e, _f;
586
+ var _a, _b, _c;
781
587
  return __awaiter(this, void 0, void 0, function* () {
782
588
  const transport = transportCache[uuid];
783
- if (this.runPromise) {
784
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleForceCleanRunPromise);
785
- this.runPromise.reject(error);
786
- this.runPromise = null;
787
- this.rejectAllProtocolV2Frames(error);
788
- this.activeProtocolV2Call = null;
789
- }
790
- else {
791
- this.resetProtocolV2Frames(uuid);
792
- }
793
589
  if (transport) {
794
- if (this.monitorTokens.get(uuid) === transport.monitorToken) {
795
- this.monitorTokens.delete(uuid);
796
- }
797
590
  Log === null || Log === void 0 ? void 0 : Log.debug('release: removing disconnect subscription for device: ', uuid);
798
591
  (_a = transport.disconnectSubscription) === null || _a === void 0 ? void 0 : _a.remove();
799
592
  transport.disconnectSubscription = undefined;
800
593
  Log === null || Log === void 0 ? void 0 : Log.debug('release: removing notify subscription, characteristic: ', (_b = transport.notifyCharacteristic) === null || _b === void 0 ? void 0 : _b.uuid);
801
594
  (_c = transport.notifySubscription) === null || _c === void 0 ? void 0 : _c.remove();
802
595
  transport.notifySubscription = undefined;
803
- if (transport.notifyTransactionId) {
804
- try {
805
- yield ((_d = this.blePlxManager) === null || _d === void 0 ? void 0 : _d.cancelTransaction(transport.notifyTransactionId));
806
- }
807
- catch (e) {
808
- 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);
809
- }
810
- }
811
596
  delete transportCache[uuid];
812
- }
813
- this.deviceProtocol.delete(uuid);
814
- this.deviceProtocolHints.delete(uuid);
815
- (_e = this.protocolV2Assemblers.get(uuid)) === null || _e === void 0 ? void 0 : _e.reset();
816
- this.protocolV2Assemblers.delete(uuid);
817
- this.resetProtocolV2Frames(uuid);
818
- try {
819
- yield ((_f = this.blePlxManager) === null || _f === void 0 ? void 0 : _f.cancelTransaction(uuid));
820
- }
821
- catch (e) {
822
- Log === null || Log === void 0 ? void 0 : Log.debug('release: cancel transaction error (ignored): ', (e === null || e === void 0 ? void 0 : e.message) || e);
597
+ if (reactNative.Platform.OS === 'android') ;
823
598
  }
824
599
  return Promise.resolve(true);
825
600
  });
@@ -829,7 +604,7 @@ class ReactNativeBleTransport {
829
604
  yield this.call(session, name, data);
830
605
  });
831
606
  }
832
- call(uuid, name, data, options) {
607
+ call(uuid, name, data) {
833
608
  return __awaiter(this, void 0, void 0, function* () {
834
609
  if (this.stopped) {
835
610
  return Promise.reject(hdShared.ERRORS.TypedError('Transport stopped.'));
@@ -842,7 +617,12 @@ class ReactNativeBleTransport {
842
617
  if (this.runPromise && !forceRun) {
843
618
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportCallInProgress);
844
619
  }
845
- const protocol = this.getProtocolType(uuid);
620
+ const transport$1 = transportCache[uuid];
621
+ if (!transport$1) {
622
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
623
+ }
624
+ this.runPromise = hdShared.createDeferred();
625
+ const messages = this._messages;
846
626
  if (name === 'ResourceUpdate' || name === 'ResourceAck') {
847
627
  Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native', 'call-', ' name: ', name, ' data: ', {
848
628
  file_name: data === null || data === void 0 ? void 0 : data.file_name,
@@ -850,29 +630,12 @@ class ReactNativeBleTransport {
850
630
  });
851
631
  }
852
632
  else if (transport.LogBlockCommand.has(name)) {
853
- Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native', 'call-', ' name: ', name, ' protocol: ', protocol);
633
+ Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native', 'call-', ' name: ', name);
854
634
  }
855
635
  else {
856
- Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native', 'call-', ' name: ', name, ' data: ', data, ' protocol: ', protocol);
857
- }
858
- if (protocol === 'V2') {
859
- return this.callProtocolV2(uuid, name, data, options);
860
- }
861
- return this.callProtocolV1(uuid, name, data, options);
862
- });
863
- }
864
- callProtocolV1(uuid, name, data, options) {
865
- return __awaiter(this, void 0, void 0, function* () {
866
- if (!this._messages) {
867
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
636
+ Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native', 'call-', ' name: ', name, ' data: ', data);
868
637
  }
869
- const transport = this.getCachedTransport(uuid);
870
- const runPromise = hdShared.createDeferred();
871
- runPromise.promise.catch(() => undefined);
872
- this.runPromise = runPromise;
873
- const messages = this._messages;
874
- const buffers = ProtocolV1.encodeTransportPackets(messages, name, data);
875
- let timeout;
638
+ const buffers = buildBuffers(messages, name, data);
876
639
  function writeChunkedData(buffers, writeFunction, onError) {
877
640
  return __awaiter(this, void 0, void 0, function* () {
878
641
  const packetCapacity = reactNative.Platform.OS === 'ios' ? IOS_PACKET_LENGTH : ANDROID_PACKET_LENGTH;
@@ -897,14 +660,14 @@ class ReactNativeBleTransport {
897
660
  });
898
661
  }
899
662
  if (name === 'EmmcFileWrite') {
900
- yield writeChunkedData(buffers, data => transport.writeWithRetry(data), e => {
663
+ yield writeChunkedData(buffers, data => transport$1.writeWithRetry(data), e => {
901
664
  this.runPromise = null;
902
665
  Log === null || Log === void 0 ? void 0 : Log.error('writeCharacteristic write error: ', e);
903
666
  });
904
667
  }
905
668
  else if (name === 'FirmwareUpload') {
906
669
  yield writeChunkedData(buffers, (data) => __awaiter(this, void 0, void 0, function* () {
907
- yield transport.writeCharacteristic.writeWithoutResponse(data);
670
+ yield transport$1.writeCharacteristic.writeWithoutResponse(data);
908
671
  }), e => {
909
672
  this.runPromise = null;
910
673
  Log === null || Log === void 0 ? void 0 : Log.error('writeCharacteristic write error: ', e);
@@ -914,7 +677,7 @@ class ReactNativeBleTransport {
914
677
  for (const o of buffers) {
915
678
  const outData = o.toString('base64');
916
679
  try {
917
- yield transport.writeCharacteristic.writeWithoutResponse(outData);
680
+ yield transport$1.writeCharacteristic.writeWithoutResponse(outData);
918
681
  }
919
682
  catch (e) {
920
683
  Log === null || Log === void 0 ? void 0 : Log.debug('writeCharacteristic write error: ', e);
@@ -932,40 +695,20 @@ class ReactNativeBleTransport {
932
695
  }
933
696
  }
934
697
  try {
935
- const response = yield Promise.race([
936
- runPromise.promise,
937
- new Promise((_, reject) => {
938
- if (options === null || options === void 0 ? void 0 : options.timeoutMs) {
939
- timeout = setTimeout(() => {
940
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleTimeoutError, `BLE response timeout after ${options.timeoutMs}ms for ${name}`);
941
- runPromise.reject(error);
942
- reject(error);
943
- }, options.timeoutMs);
944
- }
945
- }),
946
- ]);
698
+ const response = yield this.runPromise.promise;
947
699
  if (typeof response !== 'string') {
948
700
  throw new Error('Returning data is not string.');
949
701
  }
950
702
  Log === null || Log === void 0 ? void 0 : Log.debug('receive data: ', response);
951
- const jsonData = ProtocolV1.decodeMessage(messages, response);
703
+ const jsonData = receiveOne(messages, response);
952
704
  return check.call(jsonData);
953
705
  }
954
706
  catch (e) {
955
- if (name === 'Initialize' && (options === null || options === void 0 ? void 0 : options.timeoutMs) === PROTOCOL_PROBE_TIMEOUT_MS) {
956
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V1 Initialize probe call failed:', e);
957
- }
958
- else {
959
- Log === null || Log === void 0 ? void 0 : Log.error('call error: ', e);
960
- }
707
+ Log === null || Log === void 0 ? void 0 : Log.error('call error: ', e);
961
708
  throw e;
962
709
  }
963
710
  finally {
964
- if (timeout)
965
- clearTimeout(timeout);
966
- if (this.runPromise === runPromise) {
967
- this.runPromise = null;
968
- }
711
+ this.runPromise = null;
969
712
  }
970
713
  });
971
714
  }
@@ -973,7 +716,7 @@ class ReactNativeBleTransport {
973
716
  this.stopped = true;
974
717
  }
975
718
  disconnect(session) {
976
- var _a, _b, _c, _d, _e, _f;
719
+ var _a, _b, _c, _d, _e;
977
720
  return __awaiter(this, void 0, void 0, function* () {
978
721
  Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native transport resetSession: ', session);
979
722
  const transport = transportCache[session];
@@ -1022,16 +765,9 @@ class ReactNativeBleTransport {
1022
765
  if (transportCache[session]) {
1023
766
  delete transportCache[session];
1024
767
  }
1025
- this.deviceProtocol.delete(session);
1026
- this.deviceProtocolHints.delete(session);
1027
- this.protocolV2Assemblers.delete(session);
1028
- this.resetProtocolV2Frames(session);
1029
- if (((_d = this.activeProtocolV2Call) === null || _d === void 0 ? void 0 : _d.uuid) === session) {
1030
- this.activeProtocolV2Call = null;
1031
- }
1032
768
  try {
1033
- (_e = this.emitter) === null || _e === void 0 ? void 0 : _e.emit('device-disconnect', {
1034
- name: (_f = transport === null || transport === void 0 ? void 0 : transport.device) === null || _f === void 0 ? void 0 : _f.name,
769
+ (_d = this.emitter) === null || _d === void 0 ? void 0 : _d.emit('device-disconnect', {
770
+ name: (_e = transport === null || transport === void 0 ? void 0 : transport.device) === null || _e === void 0 ? void 0 : _e.name,
1035
771
  id: session,
1036
772
  connectId: session,
1037
773
  });
@@ -1047,345 +783,6 @@ class ReactNativeBleTransport {
1047
783
  if (this.runPromise) ;
1048
784
  this.runPromise = null;
1049
785
  }
1050
- getCachedTransport(uuid) {
1051
- const transport = transportCache[uuid];
1052
- if (!transport) {
1053
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
1054
- }
1055
- return transport;
1056
- }
1057
- createProtocolMismatchError(expected) {
1058
- return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `Device protocol mismatch: expected ${expected}, but device did not respond to expected protocol`);
1059
- }
1060
- detectProtocol(uuid, expectedProtocol, protocolHint) {
1061
- return __awaiter(this, void 0, void 0, function* () {
1062
- if (expectedProtocol === 'V1') {
1063
- if (yield this.probeProtocolV1(uuid)) {
1064
- this.deviceProtocol.set(uuid, 'V1');
1065
- Log === null || Log === void 0 ? void 0 : Log.debug(`[ReactNativeBleTransport] detectProtocol: uuid=${uuid} -> V1 (expected)`);
1066
- return 'V1';
1067
- }
1068
- throw this.createProtocolMismatchError(expectedProtocol);
1069
- }
1070
- if (expectedProtocol === 'V2') {
1071
- if (yield this.probeProtocolV2(uuid)) {
1072
- this.deviceProtocol.set(uuid, 'V2');
1073
- Log === null || Log === void 0 ? void 0 : Log.debug(`[ReactNativeBleTransport] detectProtocol: uuid=${uuid} -> V2 (expected)`);
1074
- return 'V2';
1075
- }
1076
- throw this.createProtocolMismatchError(expectedProtocol);
1077
- }
1078
- if (protocolHint === 'V2' && (yield this.probeProtocolV2(uuid))) {
1079
- this.deviceProtocol.set(uuid, 'V2');
1080
- Log === null || Log === void 0 ? void 0 : Log.debug(`[ReactNativeBleTransport] detectProtocol: uuid=${uuid} -> V2 (hint)`);
1081
- return 'V2';
1082
- }
1083
- if (this.deviceProtocol.get(uuid) === 'V2' && (yield this.probeProtocolV2(uuid))) {
1084
- this.deviceProtocol.set(uuid, 'V2');
1085
- Log === null || Log === void 0 ? void 0 : Log.debug(`[ReactNativeBleTransport] detectProtocol: uuid=${uuid} -> V2 (cached)`);
1086
- return 'V2';
1087
- }
1088
- let protocol = 'V1';
1089
- const protocolV1Detected = yield this.probeProtocolV1(uuid);
1090
- if (!protocolV1Detected) {
1091
- yield this.resetProbeStateAfterProtocolProbe(uuid, 'V1');
1092
- if (yield this.probeProtocolV2(uuid)) {
1093
- protocol = 'V2';
1094
- }
1095
- }
1096
- this.deviceProtocol.set(uuid, protocol);
1097
- Log === null || Log === void 0 ? void 0 : Log.debug(`[ReactNativeBleTransport] detectProtocol: uuid=${uuid} -> ${protocol}`);
1098
- return protocol;
1099
- });
1100
- }
1101
- resetProbeStateAfterProtocolProbe(uuid, protocol) {
1102
- var _a, _b, _c, _d;
1103
- return __awaiter(this, void 0, void 0, function* () {
1104
- const transport = transportCache[uuid];
1105
- (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
1106
- this.resetProtocolV2Frames(uuid);
1107
- if (((_b = this.activeProtocolV2Call) === null || _b === void 0 ? void 0 : _b.uuid) === uuid) {
1108
- this.activeProtocolV2Call = null;
1109
- }
1110
- if (this.runPromise) {
1111
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleForceCleanRunPromise);
1112
- this.runPromise.reject(error);
1113
- this.runPromise = null;
1114
- }
1115
- if (!transport)
1116
- return;
1117
- const previousNotifyTransactionId = transport.notifyTransactionId;
1118
- if (this.monitorTokens.get(uuid) === transport.monitorToken) {
1119
- this.monitorTokens.delete(uuid);
1120
- }
1121
- (_c = transport.notifySubscription) === null || _c === void 0 ? void 0 : _c.remove();
1122
- transport.notifySubscription = undefined;
1123
- if (previousNotifyTransactionId) {
1124
- try {
1125
- yield ((_d = this.blePlxManager) === null || _d === void 0 ? void 0 : _d.cancelTransaction(previousNotifyTransactionId));
1126
- }
1127
- catch (error) {
1128
- Log === null || Log === void 0 ? void 0 : Log.debug(`[ReactNativeBleTransport] cancel notify after Protocol ${protocol} probe failed:`, (error === null || error === void 0 ? void 0 : error.message) || error);
1129
- }
1130
- }
1131
- const monitorToken = this.nextMonitorToken;
1132
- this.nextMonitorToken += 1;
1133
- const notifyTransactionId = `${uuid}:notify:${monitorToken}`;
1134
- transport.monitorToken = monitorToken;
1135
- transport.notifyTransactionId = notifyTransactionId;
1136
- this.monitorTokens.set(uuid, monitorToken);
1137
- transport.notifySubscription = this._monitorCharacteristic(transport.notifyCharacteristic, uuid, monitorToken, notifyTransactionId);
1138
- if (reactNative.Platform.OS === 'ios') {
1139
- yield new Promise(resolve => {
1140
- setTimeout(resolve, IOS_NOTIFY_READY_DELAY_MS);
1141
- });
1142
- }
1143
- });
1144
- }
1145
- probeProtocolV1(uuid) {
1146
- return __awaiter(this, void 0, void 0, function* () {
1147
- if (!this._messages) {
1148
- return false;
1149
- }
1150
- try {
1151
- this.deviceProtocol.set(uuid, 'V1');
1152
- yield this.callProtocolV1(uuid, 'Initialize', {}, { timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS });
1153
- return true;
1154
- }
1155
- catch (error) {
1156
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V1 Initialize probe failed:', error);
1157
- return false;
1158
- }
1159
- });
1160
- }
1161
- probeProtocolV2(uuid) {
1162
- var _a;
1163
- return __awaiter(this, void 0, void 0, function* () {
1164
- if (!this._messages || !this._messagesV2) {
1165
- return false;
1166
- }
1167
- this.deviceProtocol.set(uuid, 'V2');
1168
- (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
1169
- return transport.probeProtocolV2({
1170
- call: (name, data, options) => this.callProtocolV2(uuid, name, data, options),
1171
- timeoutMs: PROTOCOL_V2_PROBE_TIMEOUT_MS,
1172
- logger: Log,
1173
- logPrefix: 'ProtocolV2 RN-BLE',
1174
- onProbeFailed: () => {
1175
- var _a;
1176
- (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
1177
- this.resetProtocolV2Frames(uuid);
1178
- },
1179
- });
1180
- });
1181
- }
1182
- handleProtocolV2Notification(uuid, data) {
1183
- var _a, _b, _c;
1184
- try {
1185
- if (!this.runPromise || ((_a = this.activeProtocolV2Call) === null || _a === void 0 ? void 0 : _a.uuid) !== uuid) {
1186
- (_b = this.protocolV2Assemblers.get(uuid)) === null || _b === void 0 ? void 0 : _b.reset();
1187
- this.resetProtocolV2Frames(uuid);
1188
- return;
1189
- }
1190
- if (data.length === 0)
1191
- return;
1192
- const assembler = this.protocolV2Assemblers.get(uuid);
1193
- if (!assembler)
1194
- return;
1195
- let frameData = assembler.push(data);
1196
- while (frameData) {
1197
- this.resolveProtocolV2Frame(uuid, frameData);
1198
- frameData = assembler.push(new Uint8Array(0));
1199
- }
1200
- }
1201
- catch (error) {
1202
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 notification error:', error);
1203
- const notifyError = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError);
1204
- (_c = this.runPromise) === null || _c === void 0 ? void 0 : _c.reject(notifyError);
1205
- this.rejectAllProtocolV2Frames(notifyError);
1206
- }
1207
- }
1208
- getProtocolV2FrameQueue(uuid) {
1209
- let queue = this.protocolV2FrameQueues.get(uuid);
1210
- if (!queue) {
1211
- queue = [];
1212
- this.protocolV2FrameQueues.set(uuid, queue);
1213
- }
1214
- return queue;
1215
- }
1216
- resolveProtocolV2Frame(uuid, frame) {
1217
- const framePromise = this.protocolV2FramePromises.get(uuid);
1218
- if (framePromise) {
1219
- framePromise.resolve(frame);
1220
- this.protocolV2FramePromises.delete(uuid);
1221
- return;
1222
- }
1223
- this.getProtocolV2FrameQueue(uuid).push(frame);
1224
- }
1225
- rejectAllProtocolV2Frames(error) {
1226
- this.protocolV2FrameQueues.clear();
1227
- for (const framePromise of this.protocolV2FramePromises.values()) {
1228
- framePromise.reject(error);
1229
- }
1230
- this.protocolV2FramePromises.clear();
1231
- }
1232
- resetProtocolV2Frames(uuid) {
1233
- this.protocolV2FrameQueues.delete(uuid);
1234
- this.protocolV2FramePromises.delete(uuid);
1235
- }
1236
- isActiveProtocolV2Call(uuid, token) {
1237
- var _a;
1238
- return ((_a = this.activeProtocolV2Call) === null || _a === void 0 ? void 0 : _a.uuid) === uuid && this.activeProtocolV2Call.token === token;
1239
- }
1240
- readProtocolV2Frame(uuid) {
1241
- return __awaiter(this, void 0, void 0, function* () {
1242
- const queuedFrame = this.getProtocolV2FrameQueue(uuid).shift();
1243
- if (queuedFrame) {
1244
- return queuedFrame;
1245
- }
1246
- const framePromise = hdShared.createDeferred();
1247
- this.protocolV2FramePromises.set(uuid, framePromise);
1248
- try {
1249
- return yield framePromise.promise;
1250
- }
1251
- finally {
1252
- if (this.protocolV2FramePromises.get(uuid) === framePromise) {
1253
- this.protocolV2FramePromises.delete(uuid);
1254
- }
1255
- }
1256
- });
1257
- }
1258
- writeProtocolV2Frame(transport, frame, options) {
1259
- return __awaiter(this, void 0, void 0, function* () {
1260
- const tuning = getProtocolV2BleTuning();
1261
- const packetCapacity = reactNative.Platform.OS === 'ios' ? tuning.iosPacketLength : tuning.androidPacketLength;
1262
- const writeWithResponse = !!(options === null || options === void 0 ? void 0 : options.writeWithResponse) || (!!(options === null || options === void 0 ? void 0 : options.highVolume) && tuning.highVolumeWriteWithResponse);
1263
- const shouldThrottle = !!(options === null || options === void 0 ? void 0 : options.highVolume) && !writeWithResponse;
1264
- let packetsWritten = 0;
1265
- try {
1266
- for (let offset = 0; offset < frame.length; offset += packetCapacity) {
1267
- const chunk = frame.slice(offset, offset + packetCapacity);
1268
- const base64 = buffer.Buffer.from(chunk).toString('base64');
1269
- if (writeWithResponse) {
1270
- yield transport.writeCharacteristic.writeWithResponse(base64);
1271
- }
1272
- else {
1273
- yield transport.writeCharacteristic.writeWithoutResponse(base64);
1274
- }
1275
- packetsWritten += 1;
1276
- if (shouldThrottle &&
1277
- packetsWritten % tuning.highVolumeWriteBurstSize === 0 &&
1278
- offset + packetCapacity < frame.length) {
1279
- yield delay(tuning.highVolumeWritePauseMs);
1280
- }
1281
- }
1282
- if (shouldThrottle) {
1283
- yield delay(tuning.highVolumeWriteFlushDelayMs);
1284
- }
1285
- }
1286
- catch (error) {
1287
- if ((options === null || options === void 0 ? void 0 : options.highVolume) && !writeWithResponse && packetsWritten === 0) {
1288
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 high-volume writeWithoutResponse failed before data was sent, fallback to writeWithResponse:', error);
1289
- yield this.writeProtocolV2Frame(transport, frame, {
1290
- highVolume: true,
1291
- writeWithResponse: true,
1292
- });
1293
- return;
1294
- }
1295
- throw error;
1296
- }
1297
- });
1298
- }
1299
- callProtocolV2(uuid, name, data, options) {
1300
- var _a, _b, _c, _d;
1301
- return __awaiter(this, void 0, void 0, function* () {
1302
- if (!this._messages || !this._messagesV2) {
1303
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
1304
- }
1305
- const forceRun = name === 'Initialize' || name === 'Cancel' || name === 'GetProtoVersion';
1306
- if (this.runPromise) {
1307
- if (!forceRun) {
1308
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportCallInProgress);
1309
- }
1310
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleForceCleanRunPromise);
1311
- this.runPromise.reject(error);
1312
- this.rejectAllProtocolV2Frames(error);
1313
- this.runPromise = null;
1314
- this.activeProtocolV2Call = null;
1315
- }
1316
- const transport$1 = this.getCachedTransport(uuid);
1317
- const runPromise = hdShared.createDeferred();
1318
- runPromise.promise.catch(() => undefined);
1319
- this.runPromise = runPromise;
1320
- const callToken = this.nextProtocolV2CallToken++;
1321
- this.activeProtocolV2Call = { uuid, token: callToken };
1322
- (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
1323
- this.resetProtocolV2Frames(uuid);
1324
- let completed = false;
1325
- const callOptions = Object.assign(Object.assign({}, options), { timeoutMs: (_b = options === null || options === void 0 ? void 0 : options.timeoutMs) !== null && _b !== void 0 ? _b : BLE_RESPONSE_TIMEOUT_MS });
1326
- const highVolumeWrite = transport.LogBlockCommand.has(name);
1327
- if (highVolumeWrite) {
1328
- const tuning = getProtocolV2BleTuning();
1329
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 high-volume write uses throttled writeWithoutResponse:', name, {
1330
- packetCapacity: reactNative.Platform.OS === 'ios' ? tuning.iosPacketLength : tuning.androidPacketLength,
1331
- burstSize: tuning.highVolumeWriteBurstSize,
1332
- pauseMs: tuning.highVolumeWritePauseMs,
1333
- flushDelayMs: tuning.highVolumeWriteFlushDelayMs,
1334
- writeWithResponse: tuning.highVolumeWriteWithResponse,
1335
- });
1336
- }
1337
- try {
1338
- const session = new transport.ProtocolV2Session({
1339
- schemas: {
1340
- protocolV1: this._messages,
1341
- protocolV2: this._messagesV2,
1342
- },
1343
- router: transport.PROTOCOL_V2_CHANNEL_BLE_UART,
1344
- writeFrame: (frame) => this.writeProtocolV2Frame(transport$1, frame, { highVolume: highVolumeWrite }),
1345
- readFrame: () => __awaiter(this, void 0, void 0, function* () {
1346
- const rxFrame = yield this.readProtocolV2Frame(uuid);
1347
- if (!(rxFrame instanceof Uint8Array)) {
1348
- throw new Error('Protocol V2 response is not Uint8Array');
1349
- }
1350
- return rxFrame;
1351
- }),
1352
- logger: Log,
1353
- logPrefix: 'ProtocolV2 RN-BLE',
1354
- createTimeoutError: (_messageName, timeout) => hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleTimeoutError, `BLE response timeout after ${timeout}ms for ${name}`),
1355
- });
1356
- const result = yield session.call(name, data, callOptions);
1357
- completed = true;
1358
- return result;
1359
- }
1360
- catch (e) {
1361
- if (this.isActiveProtocolV2Call(uuid, callToken)) {
1362
- (_c = this.protocolV2Assemblers.get(uuid)) === null || _c === void 0 ? void 0 : _c.reset();
1363
- this.resetProtocolV2Frames(uuid);
1364
- }
1365
- Log === null || Log === void 0 ? void 0 : Log.error('[ReactNativeBleTransport] Protocol V2 call error:', e);
1366
- throw e;
1367
- }
1368
- finally {
1369
- if (this.isActiveProtocolV2Call(uuid, callToken)) {
1370
- if (!completed) {
1371
- (_d = this.protocolV2Assemblers.get(uuid)) === null || _d === void 0 ? void 0 : _d.reset();
1372
- }
1373
- this.resetProtocolV2Frames(uuid);
1374
- this.activeProtocolV2Call = null;
1375
- }
1376
- if (this.runPromise === runPromise) {
1377
- this.runPromise = null;
1378
- }
1379
- }
1380
- });
1381
- }
1382
- getProtocolType(path) {
1383
- var _a;
1384
- return (_a = this.deviceProtocol.get(path)) !== null && _a !== void 0 ? _a : 'V1';
1385
- }
1386
786
  }
1387
787
 
1388
- exports.configureProtocolV2BleTuning = configureProtocolV2BleTuning;
1389
- exports["default"] = ReactNativeBleTransport;
1390
- exports.getProtocolV2BleTuning = getProtocolV2BleTuning;
1391
- exports.resetProtocolV2BleTuning = resetProtocolV2BleTuning;
788
+ module.exports = ReactNativeBleTransport;