@onekeyfe/hd-transport-react-native 1.1.34-alpha.3 → 1.1.34-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,116 +45,44 @@ 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) => {
63
- const cleanup = () => {
52
+ let timeout;
53
+ const cleanup = (cleanupListener) => {
64
54
  if (timeout) {
65
55
  clearTimeout(timeout);
66
56
  }
67
57
  if (cleanupListener)
68
58
  cleanupListener();
69
59
  };
70
- const timeout = setTimeout(() => {
71
- cleanup();
72
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceNotBonded, 'device is not bonded'));
73
- }, 60 * 1000);
74
60
  const cleanupListener = BleUtils__default["default"].onDeviceBondState(peripheral => {
75
61
  var _a;
76
62
  if (((_a = peripheral.id) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== bleMacAddress.toLowerCase()) {
77
63
  return;
78
64
  }
79
65
  const { bondState } = peripheral;
66
+ if (bondState.preState === 'BOND_NONE' && bondState.state === 'BOND_BONDING') {
67
+ timeout = setTimeout(() => {
68
+ cleanup(cleanupListener);
69
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceNotBonded, 'device is not bonded'));
70
+ }, 60 * 1000);
71
+ }
80
72
  const hasBonded = bondState.preState === 'BOND_BONDING' && bondState.state === 'BOND_BONDED';
81
73
  const hasCanceled = bondState.preState === 'BOND_BONDING' && bondState.state === 'BOND_NONE';
82
74
  Logger.debug('onDeviceBondState bondState:', bondState);
83
75
  if (hasBonded) {
84
- cleanup();
76
+ cleanup(cleanupListener);
85
77
  resolve(peripheral);
86
78
  }
87
79
  else if (hasCanceled) {
88
- cleanup();
80
+ cleanup(cleanupListener);
89
81
  reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceBondedCanceled, 'bonding canceled'));
90
82
  }
91
83
  });
92
84
  });
93
85
 
94
- const IOS_PACKET_LENGTH = 128;
95
- const ANDROID_PACKET_LENGTH = 192;
96
- const ANDROID_DEFAULT_MTU = 23;
97
- const normalizeBleUuid = (uuid) => (uuid !== null && uuid !== void 0 ? uuid : '').replace(/-/g, '').toLowerCase();
98
- const getBleUuidKey = (uuid) => {
99
- const normalized = normalizeBleUuid(uuid);
100
- return normalized.length >= 8 ? normalized.substring(4, 8) : normalized;
101
- };
102
- const ClassicServiceUUID = '00000001-0000-1000-8000-00805f9b34fb';
103
- const Pro2ServiceUUID = 'fffd';
104
- const OneKeyServices = {
105
- classic: {
106
- [ClassicServiceUUID]: {
107
- serviceUuid: ClassicServiceUUID,
108
- writeUuid: '00000002-0000-1000-8000-00805f9b34fb',
109
- notifyUuid: '00000003-0000-1000-8000-00805f9b34fb',
110
- },
111
- [Pro2ServiceUUID]: {
112
- serviceUuid: Pro2ServiceUUID,
113
- writeUuid: '00000002-0000-1000-8000-00805f9b34fb',
114
- notifyUuid: '00000003-0000-1000-8000-00805f9b34fb',
115
- },
116
- },
117
- };
118
- const bluetoothServices = [];
119
- for (const deviceType of Object.keys(OneKeyServices)) {
120
- const services = OneKeyServices[deviceType];
121
- bluetoothServices.push(...Object.keys(services));
122
- }
123
- const getBluetoothServiceUuids = () => bluetoothServices;
124
- const getInfosForServiceUuid = (serviceUuid, deviceType) => {
125
- var _a;
126
- const services = OneKeyServices[deviceType];
127
- if (!services) {
128
- return null;
129
- }
130
- const normalizedServiceUuid = normalizeBleUuid(serviceUuid);
131
- const service = (_a = services[serviceUuid]) !== null && _a !== void 0 ? _a : Object.values(services).find(item => normalizeBleUuid(item.serviceUuid) === normalizedServiceUuid ||
132
- getBleUuidKey(item.serviceUuid) === getBleUuidKey(serviceUuid));
133
- if (!service) {
134
- return null;
135
- }
136
- return service;
137
- };
138
- const isSameBleUuid = (left, right) => {
139
- const normalizedLeft = normalizeBleUuid(left);
140
- const normalizedRight = normalizeBleUuid(right);
141
- return (normalizedLeft === normalizedRight ||
142
- (getBleUuidKey(left) !== '' && getBleUuidKey(left) === getBleUuidKey(right)));
143
- };
144
-
145
- function hasWritableCapability(characteristic) {
146
- return !!(characteristic.isWritableWithResponse || characteristic.isWritableWithoutResponse);
147
- }
148
- function resolveProtocolV2PacketCapacity({ platform, iosPacketLength = IOS_PACKET_LENGTH, androidPacketLength = ANDROID_PACKET_LENGTH, mtu, }) {
149
- if (platform === 'ios') {
150
- return iosPacketLength;
151
- }
152
- if (platform === 'android') {
153
- const payloadLength = Math.max((mtu !== null && mtu !== void 0 ? mtu : ANDROID_DEFAULT_MTU) - 3, 1);
154
- return Math.min(androidPacketLength, payloadLength);
155
- }
156
- return androidPacketLength;
157
- }
158
-
159
86
  const timer = process.env.NODE_ENV === 'development'
160
87
  ? {
161
88
  timeout: (fn, ms) => {
@@ -181,6 +108,7 @@ const timer = process.env.NODE_ENV === 'development'
181
108
  const subscribeBleOn = (bleManager, ms = 1000) => new Promise((resolve, reject) => {
182
109
  let done = false;
183
110
  const subscription = bleManager.onStateChange(state => {
111
+ console.log('ble state -> ', state);
184
112
  if (state === 'PoweredOn') {
185
113
  if (done)
186
114
  return;
@@ -198,27 +126,58 @@ const subscribeBleOn = (bleManager, ms = 1000) => new Promise((resolve, reject)
198
126
  }, ms);
199
127
  });
200
128
 
129
+ const IOS_PACKET_LENGTH = 128;
130
+ const ANDROID_PACKET_LENGTH = 192;
131
+ const ClassicServiceUUID = '00000001-0000-1000-8000-00805f9b34fb';
132
+ const OneKeyServices = {
133
+ classic: {
134
+ [ClassicServiceUUID]: {
135
+ serviceUuid: ClassicServiceUUID,
136
+ writeUuid: '00000002-0000-1000-8000-00805f9b34fb',
137
+ notifyUuid: '00000003-0000-1000-8000-00805f9b34fb',
138
+ },
139
+ },
140
+ };
141
+ const bluetoothServices = [];
142
+ for (const deviceType of Object.keys(OneKeyServices)) {
143
+ const services = OneKeyServices[deviceType];
144
+ bluetoothServices.push(...Object.keys(services));
145
+ }
146
+ const getBluetoothServiceUuids = () => bluetoothServices;
147
+ const getInfosForServiceUuid = (serviceUuid, deviceType) => {
148
+ const services = OneKeyServices[deviceType];
149
+ if (!services) {
150
+ return null;
151
+ }
152
+ const service = services[serviceUuid];
153
+ if (!service) {
154
+ return null;
155
+ }
156
+ return service;
157
+ };
158
+
201
159
  const isHeaderChunk = (chunk) => {
202
160
  if (chunk.length < 9)
203
161
  return false;
204
162
  const [MagicQuestionMark, sharp1, sharp2] = chunk;
205
- if (String.fromCharCode(MagicQuestionMark) === String.fromCharCode(transport.PROTOCOL_V1_REPORT_ID) &&
206
- String.fromCharCode(sharp1) === String.fromCharCode(transport.PROTOCOL_V1_HEADER_BYTE) &&
207
- 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)) {
208
166
  return true;
209
167
  }
210
168
  return false;
211
169
  };
212
170
 
213
- const Log$1 = bleLogger;
171
+ const Log$1 = hdCore.getLogger(hdCore.LoggerNames.HdBleTransport);
214
172
  class BleTransport {
215
173
  constructor(device, writeCharacteristic, notifyCharacteristic) {
216
174
  this.name = 'ReactNativeBleTransport';
217
- this.mtuSize = 23;
175
+ this.mtuSize = 20;
218
176
  this.id = device.id;
219
177
  this.device = device;
220
178
  this.writeCharacteristic = writeCharacteristic;
221
179
  this.notifyCharacteristic = notifyCharacteristic;
180
+ console.log(`BleTransport(${String(this.id)}) new instance`);
222
181
  }
223
182
  writeWithRetry(data, retryCount = BleTransport.MAX_RETRIES) {
224
183
  return __awaiter(this, void 0, void 0, function* () {
@@ -228,7 +187,7 @@ class BleTransport {
228
187
  catch (error) {
229
188
  Log$1 === null || Log$1 === void 0 ? void 0 : Log$1.debug(`Write retry attempt ${BleTransport.MAX_RETRIES - retryCount + 1}, error: ${error}`);
230
189
  if (retryCount > 0) {
231
- yield hdShared.wait(BleTransport.RETRY_DELAY);
190
+ yield hdCore.wait(BleTransport.RETRY_DELAY);
232
191
  if (error.errorCode === reactNativeBlePlx.BleErrorCode.DeviceDisconnected ||
233
192
  error.errorCode === reactNativeBlePlx.BleErrorCode.CharacteristicNotFound) {
234
193
  try {
@@ -252,20 +211,8 @@ class BleTransport {
252
211
  BleTransport.MAX_RETRIES = 5;
253
212
  BleTransport.RETRY_DELAY = 2000;
254
213
 
255
- function createTransportCallLog(name, protocol, data) {
256
- if (name === 'ResourceUpdate' || name === 'ResourceAck') {
257
- return {
258
- name,
259
- protocol,
260
- file_name: data.file_name,
261
- hash: data.hash,
262
- };
263
- }
264
- return { name, protocol };
265
- }
266
-
267
- const { check, ProtocolV1, parseConfigure } = transport__default["default"];
268
- const Log = bleLogger;
214
+ const { check, buildBuffers, receiveOne, parseConfigure } = transport__default["default"];
215
+ const Log = hdCore.getLogger(hdCore.LoggerNames.HdBleTransport);
269
216
  const transportCache = {};
270
217
  const FIRMWARE_UPLOAD_WRITE_BURST_SIZE = reactNative.Platform.OS === 'ios' ? 4 : 5;
271
218
  const FIRMWARE_UPLOAD_WRITE_PAUSE_MS = reactNative.Platform.OS === 'ios' ? 8 : 10;
@@ -275,6 +222,11 @@ const FIRMWARE_UPLOAD_RECONNECT_RETRY_DELAY_MS = 2000;
275
222
  const ANDROID_FIRMWARE_UPLOAD_PACKET_LENGTH = 192;
276
223
  const FIRMWARE_UPLOAD_WRITE_PACKET_CAPACITY = reactNative.Platform.OS === 'ios' ? IOS_PACKET_LENGTH : ANDROID_FIRMWARE_UPLOAD_PACKET_LENGTH;
277
224
  const ANDROID_GATT_CONGESTED_STATUS = 143;
225
+ const getBleIdentityName = (device) => {
226
+ var _a, _b;
227
+ const localName = device === null || device === void 0 ? void 0 : device.localName;
228
+ return (_b = (_a = device === null || device === void 0 ? void 0 : device.name) !== null && _a !== void 0 ? _a : localName) !== null && _b !== void 0 ? _b : null;
229
+ };
278
230
  const delay = (ms) => new Promise(resolve => {
279
231
  setTimeout(resolve, ms);
280
232
  });
@@ -296,83 +248,20 @@ const getFirmwareUploadWriteRetryType = (error) => {
296
248
  return /GATT_CONGESTED|status\s*[:=]?\s*143/.test(text) ? 'congested' : null;
297
249
  };
298
250
  const resolveFirmwareUploadRetryDelay = (attempt, baseDelayMs = 200, maxDelayMs = 1200) => Math.min(baseDelayMs * Math.pow(2, attempt), maxDelayMs);
299
- const PROTOCOL_PROBE_TIMEOUT_MS = 1000;
300
- const PROTOCOL_V2_PROBE_TIMEOUT_MS = 10000;
301
- const DEVICE_SCAN_TIMEOUT_MS = 8000;
302
- const IOS_NOTIFY_READY_DELAY_MS = 150;
303
- const ANDROID_NOTIFY_READY_DELAY_MS = 300;
304
- const DEFAULT_PROTOCOL_V2_BLE_TUNING = {
305
- iosPacketLength: IOS_PACKET_LENGTH,
306
- androidPacketLength: ANDROID_PACKET_LENGTH,
307
- };
308
- let protocolV2BleTuning = Object.assign({}, DEFAULT_PROTOCOL_V2_BLE_TUNING);
309
- const normalizePositiveInteger = (value, fallback) => {
310
- const normalized = Number(value);
311
- if (!Number.isFinite(normalized) || normalized <= 0)
312
- return fallback;
313
- return Math.floor(normalized);
314
- };
315
- function configureProtocolV2BleTuning(tuning = {}) {
316
- protocolV2BleTuning = {
317
- iosPacketLength: normalizePositiveInteger(tuning.iosPacketLength, protocolV2BleTuning.iosPacketLength),
318
- androidPacketLength: normalizePositiveInteger(tuning.androidPacketLength, protocolV2BleTuning.androidPacketLength),
319
- };
320
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] BLE tuning configured', protocolV2BleTuning);
321
- }
322
- function resetProtocolV2BleTuning() {
323
- protocolV2BleTuning = Object.assign({}, DEFAULT_PROTOCOL_V2_BLE_TUNING);
324
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] BLE tuning reset', protocolV2BleTuning);
325
- }
326
- function getProtocolV2BleTuning() {
327
- return Object.assign({}, protocolV2BleTuning);
328
- }
329
- function inferProtocolHintFromDeviceName(name) {
330
- return /\bpro\s*2\b/i.test(name !== null && name !== void 0 ? name : '') ? 'V2' : undefined;
331
- }
332
- function getDeviceDisplayName(device) {
333
- return (device === null || device === void 0 ? void 0 : device.name) || (device === null || device === void 0 ? void 0 : device.localName) || null;
334
- }
335
- function isGenericBleService(uuid) {
336
- return ['1800', '1801', '180a'].includes(getBleUuidKey(uuid));
337
- }
338
- function hasKnownOneKeyService(device) {
339
- var _a;
340
- return ((_a = device === null || device === void 0 ? void 0 : device.serviceUUIDs) !== null && _a !== void 0 ? _a : []).some(serviceUuid => getInfosForServiceUuid(serviceUuid, 'classic'));
341
- }
342
- const ANDROID_REQUEST_MTU = 256;
343
- const connectOptions = {
344
- requestMTU: ANDROID_REQUEST_MTU,
251
+ let connectOptions = {
252
+ requestMTU: 256,
345
253
  timeout: 3000,
346
254
  refreshGatt: 'OnConnected',
347
255
  };
348
256
  const tryToGetConfiguration = (device) => {
349
257
  if (!device || !device.serviceUUIDs)
350
258
  return null;
351
- const serviceUUID = device.serviceUUIDs.find(uuid => getInfosForServiceUuid(uuid, 'classic'));
352
- if (!serviceUUID)
353
- return null;
259
+ const [serviceUUID] = device.serviceUUIDs;
354
260
  const infos = getInfosForServiceUuid(serviceUUID, 'classic');
355
261
  if (!infos)
356
262
  return null;
357
263
  return infos;
358
264
  };
359
- const requestAndroidMtu = (device) => __awaiter(void 0, void 0, void 0, function* () {
360
- if (reactNative.Platform.OS !== 'android')
361
- return device;
362
- try {
363
- const mtuDevice = yield device.requestMTU(ANDROID_REQUEST_MTU);
364
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] MTU configured', {
365
- deviceId: device.id,
366
- requested: ANDROID_REQUEST_MTU,
367
- actual: mtuDevice.mtu,
368
- });
369
- return mtuDevice;
370
- }
371
- catch (error) {
372
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Android MTU request failed:', error);
373
- return device;
374
- }
375
- });
376
265
  function remapError(error) {
377
266
  var _a;
378
267
  if (error instanceof reactNativeBlePlx.BleError) {
@@ -397,41 +286,12 @@ class ReactNativeBleTransport {
397
286
  this.name = 'ReactNativeBleTransport';
398
287
  this.configured = false;
399
288
  this.stopped = false;
400
- this.scanTimeout = DEVICE_SCAN_TIMEOUT_MS;
289
+ this.scanTimeout = 3000;
401
290
  this.runPromise = null;
402
291
  this.firmwareUploadWriteRecoveryIds = new Set();
403
- this.deviceProtocol = new Map();
404
- this.deviceProtocolHints = new Map();
405
- this.protocolV2Assemblers = new Map();
406
- this.protocolV2FrameQueues = new Map();
407
- this.protocolV2FramePromises = new Map();
408
- this.protocolV2Links = new transport.ProtocolV2LinkManager({
409
- getSchemas: () => {
410
- if (!this._messages || !this._messagesV2) {
411
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
412
- }
413
- return {
414
- protocolV1: this._messages,
415
- protocolV2: this._messagesV2,
416
- };
417
- },
418
- classifyError: () => 'link-fatal',
419
- onLinkInvalidated: (uuid, reason) => __awaiter(this, void 0, void 0, function* () {
420
- var _b;
421
- (_b = this.protocolV2Assemblers.get(uuid)) === null || _b === void 0 ? void 0 : _b.reset();
422
- this.rejectProtocolV2Frames(uuid, new Error(reason));
423
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 link invalidated:', uuid, reason);
424
- if (reason.startsWith('Protocol V2 link-fatal error:')) {
425
- yield this.release(uuid, true);
426
- }
427
- }),
428
- });
429
- this.monitorTokens = new Map();
430
- this.nextMonitorToken = 1;
431
- this.scanTimeout = (_a = options.scanTimeout) !== null && _a !== void 0 ? _a : DEVICE_SCAN_TIMEOUT_MS;
292
+ this.scanTimeout = (_a = options.scanTimeout) !== null && _a !== void 0 ? _a : 3000;
432
293
  }
433
- init(logger, emitter) {
434
- setBleLogger(logger);
294
+ init(_logger, emitter) {
435
295
  this.emitter = emitter;
436
296
  }
437
297
  configure(signedData) {
@@ -439,12 +299,6 @@ class ReactNativeBleTransport {
439
299
  this.configured = true;
440
300
  this._messages = messages;
441
301
  }
442
- configureProtocolV2(signedData) {
443
- this._messagesV2 = parseConfigure(signedData);
444
- this.protocolV2Links
445
- .invalidateAllLinks('Protocol V2 schema reconfigured')
446
- .catch(error => Log === null || Log === void 0 ? void 0 : Log.debug('Protocol V2 schema link cleanup failed:', error));
447
- }
448
302
  listen() {
449
303
  }
450
304
  getPlxManager() {
@@ -454,7 +308,6 @@ class ReactNativeBleTransport {
454
308
  return Promise.resolve(this.blePlxManager);
455
309
  }
456
310
  resolveCharacteristics(device) {
457
- var _a, _b, _c, _d;
458
311
  return __awaiter(this, void 0, void 0, function* () {
459
312
  yield device.discoverAllServicesAndCharacteristics();
460
313
  let infos = tryToGetConfiguration(device);
@@ -471,19 +324,7 @@ class ReactNativeBleTransport {
471
324
  }
472
325
  }
473
326
  }
474
- let fallbackServiceUuid;
475
327
  if (!infos) {
476
- const services = yield device.services();
477
- 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));
478
- const knownService = services.find(service => getInfosForServiceUuid(service.uuid, 'classic'));
479
- const fallbackService = (_a = knownService !== null && knownService !== void 0 ? knownService : services.find(service => !isGenericBleService(service.uuid))) !== null && _a !== void 0 ? _a : services[0];
480
- if (fallbackService) {
481
- fallbackServiceUuid = fallbackService.uuid;
482
- characteristics = yield device.characteristicsForService(fallbackService.uuid);
483
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Using fallback BLE service:', fallbackService.uuid);
484
- }
485
- }
486
- if (!infos && !fallbackServiceUuid) {
487
328
  try {
488
329
  Log === null || Log === void 0 ? void 0 : Log.debug('cancel connection when service not found');
489
330
  yield device.cancelConnection();
@@ -493,12 +334,7 @@ class ReactNativeBleTransport {
493
334
  }
494
335
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound);
495
336
  }
496
- const serviceUuid = (_b = infos === null || infos === void 0 ? void 0 : infos.serviceUuid) !== null && _b !== void 0 ? _b : fallbackServiceUuid;
497
- const writeUuid = (_c = infos === null || infos === void 0 ? void 0 : infos.writeUuid) !== null && _c !== void 0 ? _c : '00000002-0000-1000-8000-00805f9b34fb';
498
- const notifyUuid = (_d = infos === null || infos === void 0 ? void 0 : infos.notifyUuid) !== null && _d !== void 0 ? _d : '00000003-0000-1000-8000-00805f9b34fb';
499
- if (!serviceUuid) {
500
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound);
501
- }
337
+ const { serviceUuid, writeUuid, notifyUuid } = infos;
502
338
  if (!characteristics) {
503
339
  characteristics = yield device.characteristicsForService(serviceUuid);
504
340
  }
@@ -508,10 +344,10 @@ class ReactNativeBleTransport {
508
344
  let writeCharacteristic;
509
345
  let notifyCharacteristic;
510
346
  for (const c of characteristics) {
511
- if (isSameBleUuid(c.uuid, writeUuid)) {
347
+ if (c.uuid === writeUuid) {
512
348
  writeCharacteristic = c;
513
349
  }
514
- else if (isSameBleUuid(c.uuid, notifyUuid)) {
350
+ else if (c.uuid === notifyUuid) {
515
351
  notifyCharacteristic = c;
516
352
  }
517
353
  }
@@ -521,7 +357,7 @@ class ReactNativeBleTransport {
521
357
  if (!notifyCharacteristic) {
522
358
  throw hdShared.ERRORS.TypedError('BLECharacteristicNotFound: notify characteristic not found');
523
359
  }
524
- if (!hasWritableCapability(writeCharacteristic)) {
360
+ if (!writeCharacteristic.isWritableWithResponse) {
525
361
  throw hdShared.ERRORS.TypedError('BLECharacteristicNotWritable: write characteristic not writable');
526
362
  }
527
363
  if (!notifyCharacteristic.isNotifiable) {
@@ -542,10 +378,6 @@ class ReactNativeBleTransport {
542
378
  Log === null || Log === void 0 ? void 0 : Log.debug('device disconnect ignored during FirmwareUpload write recovery: ', uuid);
543
379
  return;
544
380
  }
545
- if (transportCache[uuid] !== transport) {
546
- Log === null || Log === void 0 ? void 0 : Log.debug('device disconnect ignored for stale transport: ', device === null || device === void 0 ? void 0 : device.id);
547
- return;
548
- }
549
381
  try {
550
382
  Log === null || Log === void 0 ? void 0 : Log.debug('device disconnect: ', device === null || device === void 0 ? void 0 : device.id);
551
383
  (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit('device-disconnect', {
@@ -554,16 +386,14 @@ class ReactNativeBleTransport {
554
386
  connectId: device === null || device === void 0 ? void 0 : device.id,
555
387
  });
556
388
  if (this.runPromise) {
557
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError);
558
- this.runPromise.reject(error);
559
- this.rejectAllProtocolV2Frames(error);
389
+ this.runPromise.reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError));
560
390
  }
561
391
  }
562
392
  catch (e) {
563
393
  Log === null || Log === void 0 ? void 0 : Log.debug('device disconnect error: ', e);
564
394
  }
565
395
  finally {
566
- this.release(uuid, true);
396
+ this.release(uuid);
567
397
  }
568
398
  });
569
399
  }
@@ -585,6 +415,7 @@ class ReactNativeBleTransport {
585
415
  catch (e) {
586
416
  if (e.errorCode === reactNativeBlePlx.BleErrorCode.DeviceMTUChangeFailed ||
587
417
  e.errorCode === reactNativeBlePlx.BleErrorCode.OperationCancelled) {
418
+ connectOptions = {};
588
419
  device = yield device.connect();
589
420
  }
590
421
  else if (e.errorCode !== reactNativeBlePlx.BleErrorCode.DeviceAlreadyConnected) {
@@ -596,13 +427,7 @@ class ReactNativeBleTransport {
596
427
  transport.device = device;
597
428
  transport.writeCharacteristic = writeCharacteristic;
598
429
  transport.notifyCharacteristic = notifyCharacteristic;
599
- const monitorToken = this.nextMonitorToken;
600
- this.nextMonitorToken += 1;
601
- const notifyTransactionId = `${uuid}:notify:${monitorToken}`;
602
- transport.monitorToken = monitorToken;
603
- transport.notifyTransactionId = notifyTransactionId;
604
- this.monitorTokens.set(uuid, monitorToken);
605
- transport.notifySubscription = this._monitorCharacteristic(notifyCharacteristic, uuid, monitorToken, notifyTransactionId);
430
+ transport.notifySubscription = this._monitorCharacteristic(notifyCharacteristic, uuid);
606
431
  this.attachDisconnectSubscription(transport, device, uuid);
607
432
  }
608
433
  finally {
@@ -637,11 +462,11 @@ class ReactNativeBleTransport {
637
462
  }
638
463
  }
639
464
  blePlxManager.startDeviceScan(getBluetoothServiceUuids(), {
640
- allowDuplicates: true,
641
465
  scanMode: reactNativeBlePlx.ScanMode.LowLatency,
642
466
  }, (error, device) => {
643
- var _a, _b, _c;
467
+ var _a;
644
468
  if (error) {
469
+ Log === null || Log === void 0 ? void 0 : Log.debug('ble scan manager: ', blePlxManager);
645
470
  Log === null || Log === void 0 ? void 0 : Log.debug('ble scan error: ', error);
646
471
  if ([reactNativeBlePlx.BleErrorCode.BluetoothPoweredOff, reactNativeBlePlx.BleErrorCode.BluetoothInUnknownState].includes(error.errorCode)) {
647
472
  reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePermissionError));
@@ -660,20 +485,12 @@ class ReactNativeBleTransport {
660
485
  }
661
486
  return;
662
487
  }
663
- const displayName = getDeviceDisplayName(device);
664
- 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) ||
665
- 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) ||
666
- hasKnownOneKeyService(device);
667
- if (isOneKey) {
488
+ if (hdShared.isOnekeyDevice(getBleIdentityName(device), device === null || device === void 0 ? void 0 : device.id)) {
489
+ Log === null || Log === void 0 ? void 0 : Log.debug('search device start ======================');
490
+ const { name, localName, id } = device !== null && device !== void 0 ? device : {};
491
+ 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 : ''}`);
668
492
  addDevice(device);
669
- }
670
- else if (displayName && /\bpro\s*2\b/i.test(displayName)) {
671
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Pro2-like BLE device was not accepted:', {
672
- name: device === null || device === void 0 ? void 0 : device.name,
673
- localName: device === null || device === void 0 ? void 0 : device.localName,
674
- id: device === null || device === void 0 ? void 0 : device.id,
675
- serviceUUIDs: device === null || device === void 0 ? void 0 : device.serviceUUIDs,
676
- });
493
+ Log === null || Log === void 0 ? void 0 : Log.debug('search device end ======================\n');
677
494
  }
678
495
  });
679
496
  getConnectedDeviceIds(reactNative.Platform.OS === 'ios' ? getBluetoothServiceUuids() : []).then(devices => {
@@ -682,25 +499,14 @@ class ReactNativeBleTransport {
682
499
  const hasCachedServiceUuid = Boolean(serviceUUIDs === null || serviceUUIDs === void 0 ? void 0 : serviceUUIDs.length);
683
500
  const keepDevice = reactNative.Platform.OS === 'ios' || hasCachedServiceUuid;
684
501
  if (keepDevice) {
502
+ Log === null || Log === void 0 ? void 0 : Log.debug('search connected peripheral: ', device.id);
685
503
  addDevice(device);
686
504
  }
687
505
  }
688
506
  });
689
507
  const addDevice = (device) => {
690
- var _a;
691
508
  if (deviceList.every(d => d.id !== device.id)) {
692
- const displayName = (_a = getDeviceDisplayName(device)) !== null && _a !== void 0 ? _a : 'Unknown BLE Device';
693
- const protocolHint = inferProtocolHintFromDeviceName(displayName);
694
- if (protocolHint) {
695
- this.deviceProtocolHints.set(device.id, protocolHint);
696
- }
697
- deviceList.push(Object.assign(Object.assign({}, device), { name: displayName, commType: 'ble' }));
698
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] OneKey BLE device discovered', {
699
- deviceId: device.id,
700
- name: displayName,
701
- serviceUUIDs: device.serviceUUIDs,
702
- protocolHint,
703
- });
509
+ deviceList.push(Object.assign(Object.assign({}, device), { commType: 'ble' }));
704
510
  }
705
511
  };
706
512
  timer.timeout(() => {
@@ -711,31 +517,19 @@ class ReactNativeBleTransport {
711
517
  });
712
518
  }
713
519
  acquire(input) {
714
- var _a, _b;
520
+ var _a;
715
521
  return __awaiter(this, void 0, void 0, function* () {
716
- const { uuid, forceCleanRunPromise, expectedProtocol } = input;
522
+ const { uuid, forceCleanRunPromise } = input;
717
523
  if (!uuid) {
718
524
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleRequiredUUID);
719
525
  }
720
- const cachedTransport = transportCache[uuid];
721
- if (cachedTransport) {
722
- const cachedProtocol = this.deviceProtocol.get(uuid);
723
- const isCachedDeviceConnected = yield cachedTransport.device.isConnected().catch(() => false);
724
- if (isCachedDeviceConnected &&
725
- cachedProtocol &&
726
- (!expectedProtocol || cachedProtocol === expectedProtocol)) {
727
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] reuse cached BLE transport:', uuid, cachedProtocol);
728
- return { uuid, protocolType: cachedProtocol };
729
- }
730
- Log === null || Log === void 0 ? void 0 : Log.debug('transport not reusable, will release: ', uuid);
731
- yield this.release(uuid, true);
732
- }
733
526
  let device = null;
527
+ if (transportCache[uuid]) {
528
+ Log === null || Log === void 0 ? void 0 : Log.debug('transport not be released, will release: ', uuid);
529
+ yield this.release(uuid);
530
+ }
734
531
  if (forceCleanRunPromise && this.runPromise) {
735
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleForceCleanRunPromise);
736
- this.runPromise.reject(error);
737
- this.rejectAllProtocolV2Frames(error);
738
- this.runPromise = null;
532
+ this.runPromise.reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleForceCleanRunPromise));
739
533
  Log === null || Log === void 0 ? void 0 : Log.debug('Force clean Bluetooth run promise, forceCleanRunPromise: ', forceCleanRunPromise);
740
534
  }
741
535
  const blePlxManager = yield this.getPlxManager();
@@ -751,9 +545,6 @@ class ReactNativeBleTransport {
751
545
  if (bondState.bonding) {
752
546
  yield onDeviceBondState(uuid);
753
547
  }
754
- else if (!bondState.bonded) {
755
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceNotBonded, 'device is not bonded');
756
- }
757
548
  }
758
549
  if (!device) {
759
550
  const devices = yield blePlxManager.devices([uuid]);
@@ -774,6 +565,7 @@ class ReactNativeBleTransport {
774
565
  Log === null || Log === void 0 ? void 0 : Log.debug('try to connect to device has error: ', e);
775
566
  if (e.errorCode === reactNativeBlePlx.BleErrorCode.DeviceMTUChangeFailed ||
776
567
  e.errorCode === reactNativeBlePlx.BleErrorCode.OperationCancelled) {
568
+ connectOptions = {};
777
569
  Log === null || Log === void 0 ? void 0 : Log.debug('first try to reconnect without params');
778
570
  device = yield blePlxManager.connectToDevice(uuid);
779
571
  }
@@ -792,22 +584,23 @@ class ReactNativeBleTransport {
792
584
  if (!(yield device.isConnected())) {
793
585
  Log === null || Log === void 0 ? void 0 : Log.debug('not connected, try to connect to device: ', uuid);
794
586
  try {
795
- device = yield device.connect(connectOptions);
587
+ yield device.connect(connectOptions);
796
588
  }
797
589
  catch (e) {
798
590
  Log === null || Log === void 0 ? void 0 : Log.debug('not connected, try to connect to device has error: ', e);
799
591
  if (e.errorCode === reactNativeBlePlx.BleErrorCode.DeviceMTUChangeFailed ||
800
592
  e.errorCode === reactNativeBlePlx.BleErrorCode.OperationCancelled) {
593
+ connectOptions = {};
801
594
  Log === null || Log === void 0 ? void 0 : Log.debug('second try to reconnect without params');
802
595
  try {
803
- device = yield device.connect();
596
+ yield device.connect();
804
597
  }
805
598
  catch (e) {
806
599
  Log === null || Log === void 0 ? void 0 : Log.debug('last try to reconnect error: ', e);
807
600
  if (e.errorCode === reactNativeBlePlx.BleErrorCode.OperationCancelled) {
808
601
  Log === null || Log === void 0 ? void 0 : Log.debug('last try to reconnect');
809
602
  yield device.cancelConnection();
810
- device = yield device.connect();
603
+ yield device.connect();
811
604
  }
812
605
  }
813
606
  }
@@ -816,124 +609,58 @@ class ReactNativeBleTransport {
816
609
  }
817
610
  }
818
611
  }
819
- device = yield requestAndroidMtu(device);
820
612
  const { writeCharacteristic, notifyCharacteristic } = yield this.resolveCharacteristics(device);
821
- const protocolHint = expectedProtocol
822
- ? undefined
823
- : (_a = this.deviceProtocolHints.get(uuid)) !== null && _a !== void 0 ? _a : inferProtocolHintFromDeviceName(getDeviceDisplayName(device));
824
- yield this.release(uuid, true);
825
- if (protocolHint) {
826
- this.deviceProtocolHints.set(uuid, protocolHint);
827
- }
828
- const transport$1 = new BleTransport(device, writeCharacteristic, notifyCharacteristic);
829
- if (reactNative.Platform.OS === 'android') {
830
- transport$1.mtuSize = typeof device.mtu === 'number' ? device.mtu : transport$1.mtuSize;
831
- }
832
- const monitorToken = this.nextMonitorToken;
833
- this.nextMonitorToken += 1;
834
- const notifyTransactionId = `${uuid}:notify:${monitorToken}`;
835
- transport$1.monitorToken = monitorToken;
836
- transport$1.notifyTransactionId = notifyTransactionId;
837
- this.monitorTokens.set(uuid, monitorToken);
838
- transport$1.notifySubscription = this._monitorCharacteristic(transport$1.notifyCharacteristic, uuid, monitorToken, notifyTransactionId);
839
- transportCache[uuid] = transport$1;
840
- this.protocolV2Assemblers.set(uuid, new transport.ProtocolV2FrameAssembler());
841
- if (reactNative.Platform.OS === 'ios') {
842
- yield new Promise(resolve => {
843
- setTimeout(resolve, IOS_NOTIFY_READY_DELAY_MS);
844
- });
845
- }
846
- else if (reactNative.Platform.OS === 'android') {
847
- yield delay(ANDROID_NOTIFY_READY_DELAY_MS);
848
- }
849
- const protocolType = yield this.detectProtocol(uuid, expectedProtocol, protocolHint);
850
- (_b = this.emitter) === null || _b === void 0 ? void 0 : _b.emit('device-connect', {
613
+ yield this.release(uuid);
614
+ const transport = new BleTransport(device, writeCharacteristic, notifyCharacteristic);
615
+ transport.notifySubscription = this._monitorCharacteristic(transport.notifyCharacteristic, uuid);
616
+ transportCache[uuid] = transport;
617
+ (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit('device-connect', {
851
618
  name: device.name,
852
619
  id: device.id,
853
620
  connectId: device.id,
854
621
  });
855
- this.attachDisconnectSubscription(transport$1, device, uuid);
856
- return { uuid, protocolType };
622
+ this.attachDisconnectSubscription(transport, device, uuid);
623
+ return { uuid };
857
624
  });
858
625
  }
859
- _monitorCharacteristic(characteristic, uuid, monitorToken, notifyTransactionId) {
626
+ _monitorCharacteristic(characteristic, uuid) {
860
627
  let bufferLength = 0;
861
628
  let buffer$1 = [];
862
629
  const subscription = characteristic.monitor((error, c) => {
863
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
864
- const isCurrentMonitor = this.monitorTokens.get(uuid) === monitorToken;
630
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
865
631
  if (error) {
866
632
  Log === null || Log === void 0 ? void 0 : Log.debug(`error monitor ${characteristic.uuid}, deviceId: ${characteristic.deviceID}: ${error}`);
867
633
  if (this.firmwareUploadWriteRecoveryIds.has(uuid)) {
868
634
  Log === null || Log === void 0 ? void 0 : Log.debug('notify error ignored during FirmwareUpload write recovery: ', uuid);
869
635
  return;
870
636
  }
871
- if (!isCurrentMonitor) {
872
- Log === null || Log === void 0 ? void 0 : Log.debug('monitor error ignored for stale transport: ', uuid, notifyTransactionId);
873
- return;
874
- }
875
- if (this.deviceProtocol.get(uuid) === 'V2') {
876
- let errorCode = hdShared.HardwareErrorCode.BleCharacteristicNotifyError;
637
+ if (this.runPromise) {
638
+ let ERROR = hdShared.HardwareErrorCode.BleCharacteristicNotifyError;
877
639
  if ((_a = error.reason) === null || _a === void 0 ? void 0 : _a.includes('The connection has timed out unexpectedly')) {
878
- errorCode = hdShared.HardwareErrorCode.BleTimeoutError;
640
+ ERROR = hdShared.HardwareErrorCode.BleTimeoutError;
879
641
  }
880
- else if ((_b = error.reason) === null || _b === void 0 ? void 0 : _b.includes('Encryption is insufficient')) {
881
- errorCode = hdShared.HardwareErrorCode.BleDeviceBondError;
642
+ if ((_b = error.reason) === null || _b === void 0 ? void 0 : _b.includes('Encryption is insufficient')) {
643
+ ERROR = hdShared.HardwareErrorCode.BleDeviceBondError;
882
644
  }
883
- else if (((_c = error.reason) === null || _c === void 0 ? void 0 : _c.includes('Cannot write client characteristic config descriptor')) ||
645
+ if (((_c = error.reason) === null || _c === void 0 ? void 0 : _c.includes('Cannot write client characteristic config descriptor')) ||
884
646
  ((_d = error.reason) === null || _d === void 0 ? void 0 : _d.includes('Cannot find client characteristic config descriptor')) ||
885
647
  ((_e = error.reason) === null || _e === void 0 ? void 0 : _e.includes('The handle is invalid')) ||
886
648
  ((_f = error.reason) === null || _f === void 0 ? void 0 : _f.includes('Writing is not permitted')) ||
887
649
  ((_g = error.reason) === null || _g === void 0 ? void 0 : _g.includes('notify change failed for device'))) {
888
- errorCode = hdShared.HardwareErrorCode.BleCharacteristicNotifyChangeFailure;
889
- }
890
- this.rejectProtocolV2Frames(uuid, hdShared.ERRORS.TypedError(errorCode));
891
- return;
892
- }
893
- if (this.runPromise) {
894
- let ERROR = hdShared.HardwareErrorCode.BleCharacteristicNotifyError;
895
- if ((_h = error.reason) === null || _h === void 0 ? void 0 : _h.includes('The connection has timed out unexpectedly')) {
896
- ERROR = hdShared.HardwareErrorCode.BleTimeoutError;
897
- }
898
- if ((_j = error.reason) === null || _j === void 0 ? void 0 : _j.includes('Encryption is insufficient')) {
899
- ERROR = hdShared.HardwareErrorCode.BleDeviceBondError;
900
- }
901
- if (((_k = error.reason) === null || _k === void 0 ? void 0 : _k.includes('Cannot write client characteristic config descriptor')) ||
902
- ((_l = error.reason) === null || _l === void 0 ? void 0 : _l.includes('Cannot find client characteristic config descriptor')) ||
903
- ((_m = error.reason) === null || _m === void 0 ? void 0 : _m.includes('The handle is invalid')) ||
904
- ((_o = error.reason) === null || _o === void 0 ? void 0 : _o.includes('Writing is not permitted')) ||
905
- ((_p = error.reason) === null || _p === void 0 ? void 0 : _p.includes('notify change failed for device'))) {
906
- const notifyError = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleCharacteristicNotifyChangeFailure);
907
- this.runPromise.reject(notifyError);
908
- this.rejectAllProtocolV2Frames(notifyError);
650
+ this.runPromise.reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleCharacteristicNotifyChangeFailure));
909
651
  Log === null || Log === void 0 ? void 0 : Log.debug(`${hdShared.HardwareErrorCode.BleCharacteristicNotifyChangeFailure} ${error.message} ${error.reason}`);
910
652
  return;
911
653
  }
912
- const notifyError = hdShared.ERRORS.TypedError(ERROR);
913
- this.runPromise.reject(notifyError);
914
- this.rejectAllProtocolV2Frames(notifyError);
654
+ this.runPromise.reject(hdShared.ERRORS.TypedError(ERROR));
915
655
  Log === null || Log === void 0 ? void 0 : Log.debug(': monitor notify error, and has unreleased Promise', Error);
916
656
  }
917
657
  return;
918
658
  }
919
- if (!isCurrentMonitor) {
920
- Log === null || Log === void 0 ? void 0 : Log.debug('monitor data ignored for stale transport: ', uuid, notifyTransactionId);
921
- return;
922
- }
923
659
  if (!c) {
924
660
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleMonitorError);
925
661
  }
926
662
  try {
927
663
  const data = buffer.Buffer.from(c.value, 'base64');
928
- const protocol = this.deviceProtocol.get(uuid);
929
- if (!protocol) {
930
- Log === null || Log === void 0 ? void 0 : Log.debug('monitor data ignored before protocol detection: ', uuid);
931
- return;
932
- }
933
- if (protocol === 'V2') {
934
- this.handleProtocolV2Notification(uuid, monitorToken, new Uint8Array(data));
935
- return;
936
- }
937
664
  if (isHeaderChunk(data)) {
938
665
  bufferLength = data.readInt32BE(5);
939
666
  buffer$1 = [...data.subarray(3)];
@@ -941,74 +668,33 @@ class ReactNativeBleTransport {
941
668
  else {
942
669
  buffer$1 = buffer$1.concat([...data]);
943
670
  }
944
- if (buffer$1.length - transport.PROTOCOL_V1_MESSAGE_HEADER_SIZE >= bufferLength) {
671
+ if (buffer$1.length - transport.COMMON_HEADER_SIZE >= bufferLength) {
945
672
  const value = buffer.Buffer.from(buffer$1);
946
673
  bufferLength = 0;
947
674
  buffer$1 = [];
948
- (_q = this.runPromise) === null || _q === void 0 ? void 0 : _q.resolve(value.toString('hex'));
675
+ (_h = this.runPromise) === null || _h === void 0 ? void 0 : _h.resolve(value.toString('hex'));
949
676
  }
950
677
  }
951
678
  catch (error) {
952
679
  Log === null || Log === void 0 ? void 0 : Log.debug('monitor data error: ', error);
953
- const notifyError = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError);
954
- if (this.deviceProtocol.get(uuid) === 'V2') {
955
- this.rejectProtocolV2Frames(uuid, notifyError);
956
- }
957
- else {
958
- (_r = this.runPromise) === null || _r === void 0 ? void 0 : _r.reject(notifyError);
959
- }
680
+ (_j = this.runPromise) === null || _j === void 0 ? void 0 : _j.reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError));
960
681
  }
961
- }, notifyTransactionId);
682
+ }, uuid);
962
683
  return subscription;
963
684
  }
964
- release(uuid, onclose = false) {
965
- var _a, _b, _c, _d, _e, _f, _g;
685
+ release(uuid) {
686
+ var _a, _b, _c;
966
687
  return __awaiter(this, void 0, void 0, function* () {
967
688
  const transport = transportCache[uuid];
968
- yield this.protocolV2Links.invalidateLink(uuid, 'React Native BLE transport released');
969
- if (this.runPromise) {
970
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleForceCleanRunPromise);
971
- this.runPromise.reject(error);
972
- this.runPromise = null;
973
- this.rejectAllProtocolV2Frames(error);
974
- }
975
- else {
976
- this.resetProtocolV2Frames(uuid);
977
- }
978
- if (reactNative.Platform.OS === 'android' && !onclose && transport) {
979
- (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
980
- this.resetProtocolV2Frames(uuid);
981
- return Promise.resolve(true);
982
- }
983
689
  if (transport) {
984
- if (this.monitorTokens.get(uuid) === transport.monitorToken) {
985
- this.monitorTokens.delete(uuid);
986
- }
987
690
  Log === null || Log === void 0 ? void 0 : Log.debug('release: removing disconnect subscription for device: ', uuid);
988
- (_b = transport.disconnectSubscription) === null || _b === void 0 ? void 0 : _b.remove();
691
+ (_a = transport.disconnectSubscription) === null || _a === void 0 ? void 0 : _a.remove();
989
692
  transport.disconnectSubscription = undefined;
990
- 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);
991
- (_d = transport.notifySubscription) === null || _d === void 0 ? void 0 : _d.remove();
693
+ 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);
694
+ (_c = transport.notifySubscription) === null || _c === void 0 ? void 0 : _c.remove();
992
695
  transport.notifySubscription = undefined;
993
- if (transport.notifyTransactionId) {
994
- try {
995
- yield ((_e = this.blePlxManager) === null || _e === void 0 ? void 0 : _e.cancelTransaction(transport.notifyTransactionId));
996
- }
997
- catch (e) {
998
- 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);
999
- }
1000
- }
1001
696
  delete transportCache[uuid];
1002
- }
1003
- this.deviceProtocol.delete(uuid);
1004
- (_f = this.protocolV2Assemblers.get(uuid)) === null || _f === void 0 ? void 0 : _f.reset();
1005
- this.protocolV2Assemblers.delete(uuid);
1006
- this.resetProtocolV2Frames(uuid);
1007
- try {
1008
- yield ((_g = this.blePlxManager) === null || _g === void 0 ? void 0 : _g.cancelTransaction(uuid));
1009
- }
1010
- catch (e) {
1011
- Log === null || Log === void 0 ? void 0 : Log.debug('release: cancel transaction error (ignored): ', (e === null || e === void 0 ? void 0 : e.message) || e);
697
+ if (reactNative.Platform.OS === 'android') ;
1012
698
  }
1013
699
  return Promise.resolve(true);
1014
700
  });
@@ -1018,7 +704,7 @@ class ReactNativeBleTransport {
1018
704
  yield this.call(session, name, data);
1019
705
  });
1020
706
  }
1021
- call(uuid, name, data, options) {
707
+ call(uuid, name, data) {
1022
708
  return __awaiter(this, void 0, void 0, function* () {
1023
709
  if (this.stopped) {
1024
710
  return Promise.reject(hdShared.ERRORS.TypedError('Transport stopped.'));
@@ -1026,33 +712,30 @@ class ReactNativeBleTransport {
1026
712
  if (this._messages == null) {
1027
713
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
1028
714
  }
1029
- const protocol = this.getProtocolType(uuid);
1030
- if (!protocol) {
1031
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `Device protocol has not been detected for ${uuid}`);
1032
- }
1033
- Log === null || Log === void 0 ? void 0 : Log.debug('transport call', createTransportCallLog(name, protocol, data));
1034
- if (protocol === 'V2') {
1035
- return this.callProtocolV2(uuid, name, data, options);
1036
- }
1037
715
  const forceRun = name === 'Initialize' || name === 'Cancel';
716
+ Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native call this.runPromise', this.runPromise);
1038
717
  if (this.runPromise && !forceRun) {
1039
718
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportCallInProgress);
1040
719
  }
1041
- return this.callProtocolV1(uuid, name, data, options);
1042
- });
1043
- }
1044
- callProtocolV1(uuid, name, data, options) {
1045
- return __awaiter(this, void 0, void 0, function* () {
1046
- if (!this._messages) {
1047
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
720
+ const transport$1 = transportCache[uuid];
721
+ if (!transport$1) {
722
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
1048
723
  }
1049
- const transport = this.getCachedTransport(uuid);
1050
- const runPromise = hdShared.createDeferred();
1051
- runPromise.promise.catch(() => undefined);
1052
- this.runPromise = runPromise;
724
+ this.runPromise = hdShared.createDeferred();
1053
725
  const messages = this._messages;
1054
- const buffers = ProtocolV1.encodeTransportPackets(messages, name, data);
1055
- let timeout;
726
+ if (name === 'ResourceUpdate' || name === 'ResourceAck') {
727
+ Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native', 'call-', ' name: ', name, ' data: ', {
728
+ file_name: data === null || data === void 0 ? void 0 : data.file_name,
729
+ hash: data === null || data === void 0 ? void 0 : data.hash,
730
+ });
731
+ }
732
+ else if (transport.LogBlockCommand.has(name)) {
733
+ Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native', 'call-', ' name: ', name);
734
+ }
735
+ else {
736
+ Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native', 'call-', ' name: ', name, ' data: ', data);
737
+ }
738
+ const buffers = buildBuffers(messages, name, data);
1056
739
  function writeChunkedData(buffers, writeFunction, onError) {
1057
740
  return __awaiter(this, void 0, void 0, function* () {
1058
741
  const packetCapacity = reactNative.Platform.OS === 'ios' ? IOS_PACKET_LENGTH : ANDROID_PACKET_LENGTH;
@@ -1107,13 +790,13 @@ class ReactNativeBleTransport {
1107
790
  });
1108
791
  }
1109
792
  if (name === 'EmmcFileWrite') {
1110
- yield writeChunkedData(buffers, data => transport.writeWithRetry(data), e => {
793
+ yield writeChunkedData(buffers, data => transport$1.writeWithRetry(data), e => {
1111
794
  this.runPromise = null;
1112
795
  Log === null || Log === void 0 ? void 0 : Log.error('writeCharacteristic write error: ', e);
1113
796
  });
1114
797
  }
1115
798
  else if (name === 'FirmwareUpload') {
1116
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Firmware upload transport configured', {
799
+ Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] FirmwareUpload write uses throttled BLE packets:', {
1117
800
  packetCapacity: FIRMWARE_UPLOAD_WRITE_PACKET_CAPACITY,
1118
801
  burstSize: FIRMWARE_UPLOAD_WRITE_BURST_SIZE,
1119
802
  pauseMs: FIRMWARE_UPLOAD_WRITE_PAUSE_MS,
@@ -1124,7 +807,7 @@ class ReactNativeBleTransport {
1124
807
  let attempt = 0;
1125
808
  while (true) {
1126
809
  try {
1127
- yield transport.writeCharacteristic.writeWithoutResponse(data);
810
+ yield transport$1.writeCharacteristic.writeWithoutResponse(data);
1128
811
  return;
1129
812
  }
1130
813
  catch (error) {
@@ -1149,7 +832,7 @@ class ReactNativeBleTransport {
1149
832
  attempt += 1;
1150
833
  if (shouldReconnect) {
1151
834
  try {
1152
- yield this.reconnectFirmwareUploadTransport(uuid, transport);
835
+ yield this.reconnectFirmwareUploadTransport(uuid, transport$1);
1153
836
  }
1154
837
  catch (e) {
1155
838
  Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] FirmwareUpload reconnect error:', e);
@@ -1169,7 +852,7 @@ class ReactNativeBleTransport {
1169
852
  for (const o of buffers) {
1170
853
  const outData = o.toString('base64');
1171
854
  try {
1172
- yield transport.writeCharacteristic.writeWithoutResponse(outData);
855
+ yield transport$1.writeCharacteristic.writeWithoutResponse(outData);
1173
856
  }
1174
857
  catch (e) {
1175
858
  Log === null || Log === void 0 ? void 0 : Log.debug('writeCharacteristic write error: ', e);
@@ -1187,39 +870,20 @@ class ReactNativeBleTransport {
1187
870
  }
1188
871
  }
1189
872
  try {
1190
- const response = yield Promise.race([
1191
- runPromise.promise,
1192
- new Promise((_, reject) => {
1193
- if (options === null || options === void 0 ? void 0 : options.timeoutMs) {
1194
- timeout = setTimeout(() => {
1195
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleTimeoutError, `BLE response timeout after ${options.timeoutMs}ms for ${name}`);
1196
- runPromise.reject(error);
1197
- reject(error);
1198
- }, options.timeoutMs);
1199
- }
1200
- }),
1201
- ]);
873
+ const response = yield this.runPromise.promise;
1202
874
  if (typeof response !== 'string') {
1203
875
  throw new Error('Returning data is not string.');
1204
876
  }
1205
- const jsonData = ProtocolV1.decodeMessage(messages, response);
877
+ Log === null || Log === void 0 ? void 0 : Log.debug('receive data: ', response);
878
+ const jsonData = receiveOne(messages, response);
1206
879
  return check.call(jsonData);
1207
880
  }
1208
881
  catch (e) {
1209
- if (name === 'Initialize' && (options === null || options === void 0 ? void 0 : options.timeoutMs) === PROTOCOL_PROBE_TIMEOUT_MS) {
1210
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V1 Initialize probe call failed:', e);
1211
- }
1212
- else {
1213
- Log === null || Log === void 0 ? void 0 : Log.error('call error: ', e);
1214
- }
882
+ Log === null || Log === void 0 ? void 0 : Log.error('call error: ', e);
1215
883
  throw e;
1216
884
  }
1217
885
  finally {
1218
- if (timeout)
1219
- clearTimeout(timeout);
1220
- if (this.runPromise === runPromise) {
1221
- this.runPromise = null;
1222
- }
886
+ this.runPromise = null;
1223
887
  }
1224
888
  });
1225
889
  }
@@ -1229,7 +893,7 @@ class ReactNativeBleTransport {
1229
893
  disconnect(session) {
1230
894
  var _a, _b, _c, _d, _e;
1231
895
  return __awaiter(this, void 0, void 0, function* () {
1232
- yield this.protocolV2Links.invalidateLink(session, 'React Native BLE transport disconnected');
896
+ Log === null || Log === void 0 ? void 0 : Log.debug('transport-react-native transport resetSession: ', session);
1233
897
  const transport = transportCache[session];
1234
898
  if (transport === null || transport === void 0 ? void 0 : transport.disconnectSubscription) {
1235
899
  try {
@@ -1276,10 +940,6 @@ class ReactNativeBleTransport {
1276
940
  if (transportCache[session]) {
1277
941
  delete transportCache[session];
1278
942
  }
1279
- this.deviceProtocol.delete(session);
1280
- this.deviceProtocolHints.delete(session);
1281
- this.protocolV2Assemblers.delete(session);
1282
- this.resetProtocolV2Frames(session);
1283
943
  try {
1284
944
  (_d = this.emitter) === null || _d === void 0 ? void 0 : _d.emit('device-disconnect', {
1285
945
  name: (_e = transport === null || transport === void 0 ? void 0 : transport.device) === null || _e === void 0 ? void 0 : _e.name,
@@ -1298,315 +958,6 @@ class ReactNativeBleTransport {
1298
958
  if (this.runPromise) ;
1299
959
  this.runPromise = null;
1300
960
  }
1301
- getCachedTransport(uuid) {
1302
- const transport = transportCache[uuid];
1303
- if (!transport) {
1304
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
1305
- }
1306
- return transport;
1307
- }
1308
- createProtocolMismatchError(expected) {
1309
- return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `Device protocol mismatch: expected ${expected}, but device did not respond to expected protocol`);
1310
- }
1311
- createProtocolDetectionError() {
1312
- return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleTimeoutError, 'Unable to detect BLE protocol: device did not respond to Protocol V1 Initialize or Protocol V2 Ping');
1313
- }
1314
- clearProbeProtocol(uuid, protocol) {
1315
- if (this.deviceProtocol.get(uuid) === protocol) {
1316
- this.deviceProtocol.delete(uuid);
1317
- }
1318
- }
1319
- detectProtocol(uuid, expectedProtocol, protocolHint) {
1320
- return __awaiter(this, void 0, void 0, function* () {
1321
- if (expectedProtocol === 'V1') {
1322
- if (yield this.probeProtocolV1(uuid)) {
1323
- this.deviceProtocol.set(uuid, 'V1');
1324
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] protocol detected', {
1325
- deviceId: uuid,
1326
- protocol: 'V1',
1327
- source: 'expected',
1328
- });
1329
- return 'V1';
1330
- }
1331
- throw this.createProtocolMismatchError(expectedProtocol);
1332
- }
1333
- if (expectedProtocol === 'V2') {
1334
- this.deviceProtocol.set(uuid, 'V2');
1335
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] protocol detected', {
1336
- deviceId: uuid,
1337
- protocol: 'V2',
1338
- source: 'expected',
1339
- });
1340
- return 'V2';
1341
- }
1342
- const probeOrder = protocolHint === 'V2' || this.deviceProtocol.get(uuid) === 'V2' ? ['V2', 'V1'] : ['V1', 'V2'];
1343
- for (let i = 0; i < probeOrder.length; i += 1) {
1344
- const protocol = probeOrder[i];
1345
- if (i > 0) {
1346
- yield this.resetProbeStateAfterProtocolProbe(uuid, probeOrder[i - 1]);
1347
- }
1348
- const detected = protocol === 'V1' ? yield this.probeProtocolV1(uuid) : yield this.probeProtocolV2(uuid);
1349
- if (detected) {
1350
- this.deviceProtocol.set(uuid, protocol);
1351
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] protocol detected', {
1352
- deviceId: uuid,
1353
- protocol,
1354
- source: 'probe',
1355
- });
1356
- return protocol;
1357
- }
1358
- }
1359
- this.deviceProtocol.delete(uuid);
1360
- throw this.createProtocolDetectionError();
1361
- });
1362
- }
1363
- resetProbeStateAfterProtocolProbe(uuid, protocol) {
1364
- var _a, _b, _c;
1365
- return __awaiter(this, void 0, void 0, function* () {
1366
- const transport = transportCache[uuid];
1367
- yield this.protocolV2Links.invalidateLink(uuid, `Reset notify state after Protocol ${protocol} probe`);
1368
- (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
1369
- this.resetProtocolV2Frames(uuid);
1370
- if (this.runPromise) {
1371
- const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleForceCleanRunPromise);
1372
- this.runPromise.reject(error);
1373
- this.runPromise = null;
1374
- }
1375
- if (!transport)
1376
- return;
1377
- const previousNotifyTransactionId = transport.notifyTransactionId;
1378
- if (this.monitorTokens.get(uuid) === transport.monitorToken) {
1379
- this.monitorTokens.delete(uuid);
1380
- }
1381
- (_b = transport.notifySubscription) === null || _b === void 0 ? void 0 : _b.remove();
1382
- transport.notifySubscription = undefined;
1383
- if (previousNotifyTransactionId) {
1384
- try {
1385
- yield ((_c = this.blePlxManager) === null || _c === void 0 ? void 0 : _c.cancelTransaction(previousNotifyTransactionId));
1386
- }
1387
- catch (error) {
1388
- 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);
1389
- }
1390
- }
1391
- const monitorToken = this.nextMonitorToken;
1392
- this.nextMonitorToken += 1;
1393
- const notifyTransactionId = `${uuid}:notify:${monitorToken}`;
1394
- transport.monitorToken = monitorToken;
1395
- transport.notifyTransactionId = notifyTransactionId;
1396
- this.monitorTokens.set(uuid, monitorToken);
1397
- transport.notifySubscription = this._monitorCharacteristic(transport.notifyCharacteristic, uuid, monitorToken, notifyTransactionId);
1398
- if (reactNative.Platform.OS === 'ios') {
1399
- yield new Promise(resolve => {
1400
- setTimeout(resolve, IOS_NOTIFY_READY_DELAY_MS);
1401
- });
1402
- }
1403
- });
1404
- }
1405
- probeProtocolV1(uuid) {
1406
- return __awaiter(this, void 0, void 0, function* () {
1407
- if (!this._messages) {
1408
- return false;
1409
- }
1410
- try {
1411
- this.deviceProtocol.set(uuid, 'V1');
1412
- yield this.callProtocolV1(uuid, 'Initialize', {}, { timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS });
1413
- return true;
1414
- }
1415
- catch (error) {
1416
- this.clearProbeProtocol(uuid, 'V1');
1417
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V1 Initialize probe failed:', error);
1418
- return false;
1419
- }
1420
- });
1421
- }
1422
- probeProtocolV2(uuid) {
1423
- var _a;
1424
- return __awaiter(this, void 0, void 0, function* () {
1425
- if (!this._messages || !this._messagesV2) {
1426
- return false;
1427
- }
1428
- this.deviceProtocol.set(uuid, 'V2');
1429
- (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
1430
- const detected = yield transport.probeProtocolV2({
1431
- call: (name, data, options) => this.callProtocolV2(uuid, name, data, options),
1432
- timeoutMs: PROTOCOL_V2_PROBE_TIMEOUT_MS,
1433
- logger: Log,
1434
- logPrefix: 'ProtocolV2 RN-BLE',
1435
- onProbeFailed: () => {
1436
- var _a;
1437
- (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
1438
- this.resetProtocolV2Frames(uuid);
1439
- },
1440
- });
1441
- if (!detected) {
1442
- this.clearProbeProtocol(uuid, 'V2');
1443
- }
1444
- return detected;
1445
- });
1446
- }
1447
- handleProtocolV2Notification(uuid, monitorToken, data) {
1448
- try {
1449
- if (this.monitorTokens.get(uuid) !== monitorToken)
1450
- return;
1451
- if (data.length === 0)
1452
- return;
1453
- const assembler = this.protocolV2Assemblers.get(uuid);
1454
- if (!assembler)
1455
- return;
1456
- for (const frameData of assembler.drain(data)) {
1457
- this.resolveProtocolV2Frame(uuid, frameData);
1458
- }
1459
- }
1460
- catch (error) {
1461
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 notification error:', error);
1462
- const notifyError = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleWriteCharacteristicError);
1463
- this.rejectProtocolV2Frames(uuid, notifyError);
1464
- this.protocolV2Links
1465
- .invalidateLink(uuid, `Protocol V2 notification error: ${error}`)
1466
- .catch(invalidateError => Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 notify cleanup failed:', invalidateError));
1467
- }
1468
- }
1469
- getProtocolV2FrameQueue(uuid) {
1470
- let queue = this.protocolV2FrameQueues.get(uuid);
1471
- if (!queue) {
1472
- queue = [];
1473
- this.protocolV2FrameQueues.set(uuid, queue);
1474
- }
1475
- return queue;
1476
- }
1477
- resolveProtocolV2Frame(uuid, frame) {
1478
- const framePromise = this.protocolV2FramePromises.get(uuid);
1479
- if (framePromise) {
1480
- framePromise.resolve(frame);
1481
- this.protocolV2FramePromises.delete(uuid);
1482
- return;
1483
- }
1484
- this.getProtocolV2FrameQueue(uuid).push(frame);
1485
- }
1486
- rejectAllProtocolV2Frames(error) {
1487
- this.protocolV2FrameQueues.clear();
1488
- for (const framePromise of this.protocolV2FramePromises.values()) {
1489
- framePromise.reject(error);
1490
- }
1491
- this.protocolV2FramePromises.clear();
1492
- }
1493
- resetProtocolV2Frames(uuid) {
1494
- this.protocolV2FrameQueues.delete(uuid);
1495
- this.protocolV2FramePromises.delete(uuid);
1496
- }
1497
- rejectProtocolV2Frames(uuid, error) {
1498
- this.protocolV2FrameQueues.delete(uuid);
1499
- const framePromise = this.protocolV2FramePromises.get(uuid);
1500
- if (framePromise) {
1501
- this.protocolV2FramePromises.delete(uuid);
1502
- framePromise.reject(error);
1503
- }
1504
- }
1505
- readProtocolV2Frame(uuid) {
1506
- return __awaiter(this, void 0, void 0, function* () {
1507
- const queuedFrame = this.getProtocolV2FrameQueue(uuid).shift();
1508
- if (queuedFrame) {
1509
- return queuedFrame;
1510
- }
1511
- const framePromise = hdShared.createDeferred();
1512
- this.protocolV2FramePromises.set(uuid, framePromise);
1513
- try {
1514
- return yield framePromise.promise;
1515
- }
1516
- finally {
1517
- if (this.protocolV2FramePromises.get(uuid) === framePromise) {
1518
- this.protocolV2FramePromises.delete(uuid);
1519
- }
1520
- }
1521
- });
1522
- }
1523
- writeProtocolV2Frame(transport, frame) {
1524
- return __awaiter(this, void 0, void 0, function* () {
1525
- const tuning = getProtocolV2BleTuning();
1526
- const packetCapacity = resolveProtocolV2PacketCapacity({
1527
- platform: reactNative.Platform.OS,
1528
- iosPacketLength: tuning.iosPacketLength,
1529
- androidPacketLength: tuning.androidPacketLength,
1530
- mtu: reactNative.Platform.OS === 'android' ? transport.mtuSize : undefined,
1531
- });
1532
- for (let offset = 0; offset < frame.length; offset += packetCapacity) {
1533
- const chunk = frame.slice(offset, offset + packetCapacity);
1534
- const base64 = buffer.Buffer.from(chunk).toString('base64');
1535
- yield transport.writeCharacteristic.writeWithoutResponse(base64);
1536
- }
1537
- });
1538
- }
1539
- callProtocolV2(uuid, name, data, options) {
1540
- return __awaiter(this, void 0, void 0, function* () {
1541
- if (!this._messages || !this._messagesV2) {
1542
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
1543
- }
1544
- const callOptions = Object.assign(Object.assign({}, options), { timeoutMs: options === null || options === void 0 ? void 0 : options.timeoutMs });
1545
- const highVolumeWrite = transport.LogBlockCommand.has(name);
1546
- if (highVolumeWrite) {
1547
- const tuning = getProtocolV2BleTuning();
1548
- Log === null || Log === void 0 ? void 0 : Log.debug('[ReactNativeBleTransport] Protocol V2 high-volume write configured', {
1549
- name,
1550
- writeMode: 'withoutResponse',
1551
- packetCapacity: reactNative.Platform.OS === 'ios' ? tuning.iosPacketLength : tuning.androidPacketLength,
1552
- });
1553
- }
1554
- try {
1555
- return yield this.protocolV2Links.call(uuid, () => this.createProtocolV2Adapter(uuid), name, data, callOptions);
1556
- }
1557
- catch (e) {
1558
- Log === null || Log === void 0 ? void 0 : Log.error('[ReactNativeBleTransport] Protocol V2 call error:', e);
1559
- throw e;
1560
- }
1561
- });
1562
- }
1563
- createProtocolV2Adapter(uuid) {
1564
- var _a;
1565
- const generation = (_a = this.monitorTokens.get(uuid)) !== null && _a !== void 0 ? _a : 0;
1566
- const assertCurrentGeneration = () => {
1567
- if (this.monitorTokens.get(uuid) !== generation) {
1568
- throw new Error(`Protocol V2 monitor generation changed for ${uuid}`);
1569
- }
1570
- };
1571
- return {
1572
- router: transport.PROTOCOL_V2_CHANNEL_BLE_UART,
1573
- maxFrameBytes: transport.PROTOCOL_V2_BLE_FRAME_MAX_BYTES,
1574
- generation,
1575
- prepareCall: () => {
1576
- var _a;
1577
- assertCurrentGeneration();
1578
- (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
1579
- this.resetProtocolV2Frames(uuid);
1580
- },
1581
- writeFrame: (frame) => __awaiter(this, void 0, void 0, function* () {
1582
- assertCurrentGeneration();
1583
- const currentTransport = this.getCachedTransport(uuid);
1584
- yield this.writeProtocolV2Frame(currentTransport, frame);
1585
- }),
1586
- readFrame: () => __awaiter(this, void 0, void 0, function* () {
1587
- assertCurrentGeneration();
1588
- const rxFrame = yield this.readProtocolV2Frame(uuid);
1589
- if (!(rxFrame instanceof Uint8Array)) {
1590
- throw new Error('Protocol V2 response is not Uint8Array');
1591
- }
1592
- return rxFrame;
1593
- }),
1594
- reset: (reason) => {
1595
- var _a;
1596
- (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
1597
- this.rejectProtocolV2Frames(uuid, new Error(reason));
1598
- },
1599
- logger: Log,
1600
- logPrefix: 'ProtocolV2 RN-BLE',
1601
- createTimeoutError: (messageName, timeout) => hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleTimeoutError, `BLE response timeout after ${timeout}ms for ${messageName}`),
1602
- };
1603
- }
1604
- getProtocolType(path) {
1605
- return this.deviceProtocol.get(path);
1606
- }
1607
961
  }
1608
962
 
1609
- exports.configureProtocolV2BleTuning = configureProtocolV2BleTuning;
1610
- exports["default"] = ReactNativeBleTransport;
1611
- exports.getProtocolV2BleTuning = getProtocolV2BleTuning;
1612
- exports.resetProtocolV2BleTuning = resetProtocolV2BleTuning;
963
+ module.exports = ReactNativeBleTransport;