@onekeyfe/hd-transport-react-native 0.1.5 → 0.1.8

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.
@@ -1,5 +1,3 @@
1
- export declare const PERMISSION_ERROR = "Bluetooth required to be turned on";
2
- export declare const LOCATION_ERROR = "Device is not authorized to use BluetoothLE";
3
1
  export declare const IOS_PACKET_LENGTH = 128;
4
2
  export declare const ANDROID_PACKET_LENGTH = 192;
5
3
  export declare const isOnekeyDevice: (name: string | null, id?: string | undefined) => boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,gBAAgB,uCAAuC,CAAC;AACrE,eAAO,MAAM,cAAc,gDAAgD,CAAC;AAE5E,eAAO,MAAM,iBAAiB,MAAM,CAAC;AACrC,eAAO,MAAM,qBAAqB,MAAM,CAAC;AAEzC,eAAO,MAAM,cAAc,SAAU,MAAM,GAAG,IAAI,8BAAgB,OAYjE,CAAC;AA8BF,eAAO,MAAM,wBAAwB,gBAA0B,CAAC;AAChE,eAAO,MAAM,sBAAsB,gBAAiB,MAAM,cAAc,SAAS;iBA1BhE,MAAM;;;QAoCtB,CAAC"}
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,iBAAiB,MAAM,CAAC;AACrC,eAAO,MAAM,qBAAqB,MAAM,CAAC;AAEzC,eAAO,MAAM,cAAc,SAAU,MAAM,GAAG,IAAI,8BAAgB,OAYjE,CAAC;AA8BF,eAAO,MAAM,wBAAwB,gBAA0B,CAAC;AAChE,eAAO,MAAM,sBAAsB,gBAAiB,MAAM,cAAc,SAAS;iBA1BhE,MAAM;;;QAoCtB,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,16 +1,6 @@
1
- import transport from '@onekeyfe/hd-transport';
2
1
  import { BleManager, Device, Characteristic } from 'react-native-ble-plx';
3
-
4
- declare const PERMISSION_ERROR = "Bluetooth required to be turned on";
5
- declare const LOCATION_ERROR = "Device is not authorized to use BluetoothLE";
6
-
7
- declare type Deferred<T, I = any, D = any> = {
8
- id?: I;
9
- data?: D;
10
- promise: Promise<T>;
11
- resolve: (t: T) => void;
12
- reject: (e: Error) => void;
13
- };
2
+ import transport from '@onekeyfe/hd-transport';
3
+ import { Deferred } from '@onekeyfe/hd-shared';
14
4
 
15
5
  declare type TransportOptions = {
16
6
  scanTimeout?: number;
@@ -42,4 +32,4 @@ declare class ReactNativeBleTransport {
42
32
  cancel(): void;
43
33
  }
44
34
 
45
- export { LOCATION_ERROR, PERMISSION_ERROR, ReactNativeBleTransport as default };
35
+ export { ReactNativeBleTransport as default };
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,SAAiC,MAAM,wBAAwB,CAAC;AACvE,OAAO,EACL,UAAU,IAAI,aAAa,EAC3B,MAAM,EAEN,cAAc,EAEf,MAAM,sBAAsB,CAAC;AAI9B,OAAO,EACL,gBAAgB,EAChB,cAAc,EAMf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,QAAQ,EAA4B,MAAM,kBAAkB,CAAC;AAItE,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAmBjE,MAAM,CAAC,OAAO,OAAO,uBAAuB;IAC1C,aAAa,EAAE,aAAa,GAAG,SAAS,CAAC;IAEzC,SAAS,EAAE,UAAU,CAAC,OAAO,SAAS,CAAC,cAAc,CAAC,GAAG,SAAS,CAAC;IAEnE,UAAU,UAAS;IAEnB,OAAO,UAAS;IAEhB,WAAW,SAAQ;IAEnB,UAAU,EAAE,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,CAAQ;gBAE5B,OAAO,EAAE,gBAAgB;IAIrC,IAAI;IAEJ,SAAS,CAAC,UAAU,EAAE,GAAG;IAMzB,MAAM;IAIN,aAAa,IAAI,OAAO,CAAC,aAAa,CAAC;IAYjC,SAAS;IAoET,OAAO,CAAC,KAAK,EAAE,eAAe;;;IA4JpC,sBAAsB,CAAC,cAAc,EAAE,cAAc;IAmD/C,OAAO,CAAC,IAAI,EAAE,MAAM;IAcpB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IA+EpE,IAAI;IAIJ,MAAM;CAOP;AAED,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,UAAU,IAAI,aAAa,EAC3B,MAAM,EAEN,cAAc,EAEf,MAAM,sBAAsB,CAAC;AAE9B,OAAO,SAAiC,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAkB,QAAQ,EAA6B,MAAM,qBAAqB,CAAC;AAa1F,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAmBjE,MAAM,CAAC,OAAO,OAAO,uBAAuB;IAC1C,aAAa,EAAE,aAAa,GAAG,SAAS,CAAC;IAEzC,SAAS,EAAE,UAAU,CAAC,OAAO,SAAS,CAAC,cAAc,CAAC,GAAG,SAAS,CAAC;IAEnE,UAAU,UAAS;IAEnB,OAAO,UAAS;IAEhB,WAAW,SAAQ;IAEnB,UAAU,EAAE,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,CAAQ;gBAE5B,OAAO,EAAE,gBAAgB;IAIrC,IAAI;IAEJ,SAAS,CAAC,UAAU,EAAE,GAAG;IAMzB,MAAM;IAIN,aAAa,IAAI,OAAO,CAAC,aAAa,CAAC;IAYjC,SAAS;IAsET,OAAO,CAAC,KAAK,EAAE,eAAe;;;IA+JpC,sBAAsB,CAAC,cAAc,EAAE,cAAc;IA4D/C,OAAO,CAAC,IAAI,EAAE,MAAM;IAcpB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IA+EpE,IAAI;IAIJ,MAAM;CAOP"}
package/dist/index.js CHANGED
@@ -1,18 +1,17 @@
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
- var transport = require('@onekeyfe/hd-transport');
8
5
  var reactNativeBlePlx = require('react-native-ble-plx');
9
6
  var ByteBuffer = require('bytebuffer');
7
+ var transport = require('@onekeyfe/hd-transport');
8
+ var hdShared = require('@onekeyfe/hd-shared');
10
9
  var BleManager = require('react-native-ble-manager');
11
10
 
12
11
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
13
12
 
14
- var transport__default = /*#__PURE__*/_interopDefaultLegacy(transport);
15
13
  var ByteBuffer__default = /*#__PURE__*/_interopDefaultLegacy(ByteBuffer);
14
+ var transport__default = /*#__PURE__*/_interopDefaultLegacy(transport);
16
15
  var BleManager__default = /*#__PURE__*/_interopDefaultLegacy(BleManager);
17
16
 
18
17
  /******************************************************************************
@@ -58,49 +57,6 @@ const getBondedDevices = () => __awaiter(void 0, void 0, void 0, function* () {
58
57
  });
59
58
  });
60
59
 
61
- const PERMISSION_ERROR = 'Bluetooth required to be turned on';
62
- const LOCATION_ERROR = 'Device is not authorized to use BluetoothLE';
63
- const IOS_PACKET_LENGTH = 128;
64
- const ANDROID_PACKET_LENGTH = 192;
65
- const isOnekeyDevice = (name, id) => {
66
- var _a;
67
- if ((_a = id === null || id === void 0 ? void 0 : id.startsWith) === null || _a === void 0 ? void 0 : _a.call(id, 'MI')) {
68
- return true;
69
- }
70
- const re = /(BixinKey\d{10})|(K\d{4})|(T\d{4})/i;
71
- if (name && re.exec(name)) {
72
- return true;
73
- }
74
- return false;
75
- };
76
- const ClassicServiceUUID = '00000001-0000-1000-8000-00805f9b34fb';
77
- const OneKeyServices = {
78
- classic: {
79
- [ClassicServiceUUID]: {
80
- serviceUuid: ClassicServiceUUID,
81
- writeUuid: '00000002-0000-1000-8000-00805f9b34fb',
82
- notifyUuid: '00000003-0000-1000-8000-00805f9b34fb',
83
- },
84
- },
85
- };
86
- const bluetoothServices = [];
87
- for (const deviceType of Object.keys(OneKeyServices)) {
88
- const services = OneKeyServices[deviceType];
89
- bluetoothServices.push(...Object.keys(services));
90
- }
91
- const getBluetoothServiceUuids = () => bluetoothServices;
92
- const getInfosForServiceUuid = (serviceUuid, deviceType) => {
93
- const services = OneKeyServices[deviceType];
94
- if (!services) {
95
- return null;
96
- }
97
- const service = services[serviceUuid];
98
- if (!service) {
99
- return null;
100
- }
101
- return service;
102
- };
103
-
104
60
  const timer = process.env.NODE_ENV === 'development'
105
61
  ? {
106
62
  timeout: (fn, ms) => {
@@ -140,36 +96,50 @@ const subscribeBleOn = (bleManager, ms = 1000) => new Promise((resolve, reject)
140
96
  if (done)
141
97
  return;
142
98
  subscription.remove();
143
- reject(new Error(PERMISSION_ERROR));
99
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePermissionError));
144
100
  }, ms);
145
101
  });
146
102
 
147
- function create(arg, data) {
148
- let localResolve = (_t) => { };
149
- let localReject = (_e) => { };
150
- let id;
151
- const promise = new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
152
- localResolve = resolve;
153
- localReject = reject;
154
- if (typeof arg === 'function') {
155
- try {
156
- yield arg();
157
- }
158
- catch (error) {
159
- reject(error);
160
- }
161
- }
162
- if (typeof arg === 'string')
163
- id = arg;
164
- }));
165
- return {
166
- id,
167
- data,
168
- resolve: localResolve,
169
- reject: localReject,
170
- promise,
171
- };
103
+ const IOS_PACKET_LENGTH = 128;
104
+ const ANDROID_PACKET_LENGTH = 192;
105
+ const isOnekeyDevice = (name, id) => {
106
+ var _a;
107
+ if ((_a = id === null || id === void 0 ? void 0 : id.startsWith) === null || _a === void 0 ? void 0 : _a.call(id, 'MI')) {
108
+ return true;
109
+ }
110
+ const re = /(BixinKey\d{10})|(K\d{4})|(T\d{4})/i;
111
+ if (name && re.exec(name)) {
112
+ return true;
113
+ }
114
+ return false;
115
+ };
116
+ const ClassicServiceUUID = '00000001-0000-1000-8000-00805f9b34fb';
117
+ const OneKeyServices = {
118
+ classic: {
119
+ [ClassicServiceUUID]: {
120
+ serviceUuid: ClassicServiceUUID,
121
+ writeUuid: '00000002-0000-1000-8000-00805f9b34fb',
122
+ notifyUuid: '00000003-0000-1000-8000-00805f9b34fb',
123
+ },
124
+ },
125
+ };
126
+ const bluetoothServices = [];
127
+ for (const deviceType of Object.keys(OneKeyServices)) {
128
+ const services = OneKeyServices[deviceType];
129
+ bluetoothServices.push(...Object.keys(services));
172
130
  }
131
+ const getBluetoothServiceUuids = () => bluetoothServices;
132
+ const getInfosForServiceUuid = (serviceUuid, deviceType) => {
133
+ const services = OneKeyServices[deviceType];
134
+ if (!services) {
135
+ return null;
136
+ }
137
+ const service = services[serviceUuid];
138
+ if (!service) {
139
+ return null;
140
+ }
141
+ return service;
142
+ };
173
143
 
174
144
  const isHeaderChunk = (chunk) => {
175
145
  if (chunk.length < 9)
@@ -249,19 +219,22 @@ class ReactNativeBleTransport {
249
219
  blePlxManager.startDeviceScan(null, {
250
220
  scanMode: reactNativeBlePlx.ScanMode.LowLatency,
251
221
  }, (error, device) => {
252
- var _a;
222
+ var _a, _b;
253
223
  if (error) {
254
224
  console.log('ble scan manager: ', blePlxManager);
255
225
  console.log('ble scan error: ', error);
256
226
  if ([reactNativeBlePlx.BleErrorCode.BluetoothPoweredOff, reactNativeBlePlx.BleErrorCode.BluetoothInUnknownState].includes(error.errorCode)) {
257
- reject(new Error(PERMISSION_ERROR));
227
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BlePermissionError));
228
+ }
229
+ else if (error.errorCode === reactNativeBlePlx.BleErrorCode.BluetoothUnauthorized) {
230
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleLocationError));
258
231
  }
259
232
  else {
260
- reject(error);
233
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleScanError, (_a = error.reason) !== null && _a !== void 0 ? _a : ''));
261
234
  }
262
235
  return;
263
236
  }
264
- if (isOnekeyDevice((_a = device === null || device === void 0 ? void 0 : device.name) !== null && _a !== void 0 ? _a : null, device === null || device === void 0 ? void 0 : device.id)) {
237
+ if (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)) {
265
238
  console.log('search device start ======================');
266
239
  const { name, localName, id } = device !== null && device !== void 0 ? device : {};
267
240
  console.log(`device name: ${name !== null && name !== void 0 ? name : ''}\nlocalName: ${localName !== null && localName !== void 0 ? localName : ''}\nid: ${id !== null && id !== void 0 ? id : ''}`);
@@ -288,10 +261,11 @@ class ReactNativeBleTransport {
288
261
  });
289
262
  }
290
263
  acquire(input) {
264
+ var _a, _b;
291
265
  return __awaiter(this, void 0, void 0, function* () {
292
266
  const { uuid } = input;
293
267
  if (!uuid) {
294
- throw new Error('uuid is required');
268
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleRequiredUUID);
295
269
  }
296
270
  let device = null;
297
271
  if (transportCache[uuid]) {
@@ -329,12 +303,12 @@ class ReactNativeBleTransport {
329
303
  device = yield blePlxManager.connectToDevice(uuid);
330
304
  }
331
305
  else {
332
- throw e;
306
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, (_a = e.reason) !== null && _a !== void 0 ? _a : e);
333
307
  }
334
308
  }
335
309
  }
336
310
  if (!device) {
337
- throw new Error('unable to connect to device');
311
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, 'unable to connect to device');
338
312
  }
339
313
  if (!(yield device.isConnected())) {
340
314
  console.log('not connected, try to connect to device: ', uuid);
@@ -349,7 +323,7 @@ class ReactNativeBleTransport {
349
323
  yield device.connect();
350
324
  }
351
325
  else {
352
- throw e;
326
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, (_b = e.reason) !== null && _b !== void 0 ? _b : e);
353
327
  }
354
328
  }
355
329
  }
@@ -357,7 +331,7 @@ class ReactNativeBleTransport {
357
331
  const bondedDevices = yield getBondedDevices();
358
332
  const hasBonded = !!bondedDevices.find(bondedDevice => bondedDevice.id === (device === null || device === void 0 ? void 0 : device.id));
359
333
  if (!hasBonded) {
360
- throw new Error('device is not bonded');
334
+ throw hdShared.ERRORS.TypedError('device is not bonded');
361
335
  }
362
336
  }
363
337
  yield device.discoverAllServicesAndCharacteristics();
@@ -371,18 +345,19 @@ class ReactNativeBleTransport {
371
345
  break;
372
346
  }
373
347
  catch (e) {
348
+ console.log(e);
374
349
  }
375
350
  }
376
351
  }
377
352
  if (!infos) {
378
- throw new Error('BLEServiceNotFound: service not found');
353
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound);
379
354
  }
380
355
  const { serviceUuid, writeUuid, notifyUuid } = infos;
381
356
  if (!characteristics) {
382
357
  characteristics = yield device.characteristicsForService(serviceUuid);
383
358
  }
384
359
  if (!characteristics) {
385
- throw new Error('BLEServiceNotFound: characteristics not found');
360
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleCharacteristicNotFound);
386
361
  }
387
362
  let writeCharacteristic;
388
363
  let notifyCharacteristic;
@@ -395,23 +370,24 @@ class ReactNativeBleTransport {
395
370
  }
396
371
  }
397
372
  if (!writeCharacteristic) {
398
- throw new Error('BLECharacteristicNotFound: write characteristic not found');
373
+ throw hdShared.ERRORS.TypedError('BLECharacteristicNotFound: write characteristic not found');
399
374
  }
400
375
  if (!notifyCharacteristic) {
401
- throw new Error('BLECharacteristicNotFound: notify characteristic not found');
376
+ throw hdShared.ERRORS.TypedError('BLECharacteristicNotFound: notify characteristic not found');
402
377
  }
403
378
  if (!writeCharacteristic.isWritableWithResponse) {
404
- throw new Error('BLECharacteristicNotWritable: write characteristic not writable');
379
+ throw hdShared.ERRORS.TypedError('BLECharacteristicNotWritable: write characteristic not writable');
405
380
  }
406
381
  if (!notifyCharacteristic.isNotifiable) {
407
- throw new Error('BLECharacteristicNotNotifiable: notify characteristic not notifiable');
382
+ throw hdShared.ERRORS.TypedError('BLECharacteristicNotNotifiable: notify characteristic not notifiable');
408
383
  }
409
384
  const transport = new BleTransport(device, writeCharacteristic, notifyCharacteristic);
410
385
  transport.nofitySubscription = this._monitorCharacteristic(transport.notifyCharacteristic);
411
386
  transportCache[uuid] = transport;
412
- device.onDisconnected(() => {
387
+ const disconnectSubscription = device.onDisconnected(() => {
413
388
  console.log('device disconnect: ', device === null || device === void 0 ? void 0 : device.id);
414
389
  this.release(uuid);
390
+ disconnectSubscription === null || disconnectSubscription === void 0 ? void 0 : disconnectSubscription.remove();
415
391
  });
416
392
  return { uuid };
417
393
  });
@@ -420,13 +396,17 @@ class ReactNativeBleTransport {
420
396
  let bufferLength = 0;
421
397
  let buffer$1 = [];
422
398
  const subscription = characteristic.monitor((error, c) => {
423
- var _a, _b;
399
+ var _a, _b, _c;
424
400
  if (error) {
425
401
  console.log(`error monitor ${characteristic.uuid}, deviceId: ${characteristic.deviceID}: ${error}`);
402
+ if (this.runPromise) {
403
+ this.runPromise.reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleCharacteristicNotifyError, (_a = error.reason) !== null && _a !== void 0 ? _a : error.message));
404
+ console.log('@onekey/hd-ble-sdk: monitor notify error, and has unreleased Promise');
405
+ }
426
406
  return;
427
407
  }
428
408
  if (!c) {
429
- throw new Error('Monitor Error: characteristic not found');
409
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleMonitorError);
430
410
  }
431
411
  try {
432
412
  const data = buffer.Buffer.from(c.value, 'base64');
@@ -441,12 +421,12 @@ class ReactNativeBleTransport {
441
421
  const value = buffer.Buffer.from(buffer$1);
442
422
  bufferLength = 0;
443
423
  buffer$1 = [];
444
- (_a = this.runPromise) === null || _a === void 0 ? void 0 : _a.resolve(value.toString('hex'));
424
+ (_b = this.runPromise) === null || _b === void 0 ? void 0 : _b.resolve(value.toString('hex'));
445
425
  }
446
426
  }
447
427
  catch (error) {
448
428
  console.log('monitor data error: ', error);
449
- (_b = this.runPromise) === null || _b === void 0 ? void 0 : _b.reject(error);
429
+ (_c = this.runPromise) === null || _c === void 0 ? void 0 : _c.reject(error);
450
430
  }
451
431
  });
452
432
  return () => {
@@ -471,19 +451,19 @@ class ReactNativeBleTransport {
471
451
  call(uuid, name, data) {
472
452
  return __awaiter(this, void 0, void 0, function* () {
473
453
  if (this.stopped) {
474
- return Promise.reject('Transport stopped.');
454
+ return Promise.reject(hdShared.ERRORS.TypedError('Transport stopped.'));
475
455
  }
476
456
  if (this._messages == null) {
477
- throw new Error('Transport not configured.');
457
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
478
458
  }
479
459
  if (this.runPromise) {
480
- throw new Error('Transport_CallInProgress');
460
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportCallInProgress);
481
461
  }
482
462
  const transport = transportCache[uuid];
483
463
  if (!transport) {
484
- throw new Error('Transport not found.');
464
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
485
465
  }
486
- this.runPromise = create();
466
+ this.runPromise = hdShared.createDeferred();
487
467
  const messages = this._messages;
488
468
  console.log('transport-react-native', 'call-', ' name: ', name, ' data: ', data);
489
469
  const buffers = buildBuffers(messages, name, data);
@@ -519,7 +499,7 @@ class ReactNativeBleTransport {
519
499
  }
520
500
  catch (e) {
521
501
  if (e.errorCode === reactNativeBlePlx.BleErrorCode.DeviceDisconnected) {
522
- throw new Error('device is not bonded');
502
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceNotBonded);
523
503
  }
524
504
  this.runPromise = null;
525
505
  console.log('writeCharacteristic write error: ', e);
@@ -555,6 +535,4 @@ class ReactNativeBleTransport {
555
535
  }
556
536
  }
557
537
 
558
- exports.LOCATION_ERROR = LOCATION_ERROR;
559
- exports.PERMISSION_ERROR = PERMISSION_ERROR;
560
- exports["default"] = ReactNativeBleTransport;
538
+ module.exports = ReactNativeBleTransport;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/hd-transport-react-native",
3
- "version": "0.1.5",
3
+ "version": "0.1.8",
4
4
  "homepage": "https://github.com/OneKeyHQ/hardware-js-sdk#readme",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",
@@ -20,9 +20,10 @@
20
20
  "lint:fix": "eslint . --fix"
21
21
  },
22
22
  "dependencies": {
23
- "@onekeyfe/hd-transport": "^0.1.5",
23
+ "@onekeyfe/hd-shared": "^0.1.8",
24
+ "@onekeyfe/hd-transport": "^0.1.8",
24
25
  "react-native-ble-manager": "^8.1.0",
25
26
  "react-native-ble-plx": "^2.0.3"
26
27
  },
27
- "gitHead": "26a2b960d5e1917d3f2217cef449269200a1a376"
28
+ "gitHead": "d9514ac6207a2561ad107910ab005b3f9e12d794"
28
29
  }
package/src/constants.ts CHANGED
@@ -1,6 +1,3 @@
1
- export const PERMISSION_ERROR = 'Bluetooth required to be turned on';
2
- export const LOCATION_ERROR = 'Device is not authorized to use BluetoothLE';
3
-
4
1
  export const IOS_PACKET_LENGTH = 128;
5
2
  export const ANDROID_PACKET_LENGTH = 192;
6
3
 
package/src/index.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { Platform } from 'react-native';
2
2
  import { Buffer } from 'buffer';
3
- import transport, { COMMON_HEADER_SIZE } from '@onekeyfe/hd-transport';
4
3
  import {
5
4
  BleManager as BlePlxManager,
6
5
  Device,
@@ -9,18 +8,17 @@ import {
9
8
  ScanMode,
10
9
  } from 'react-native-ble-plx';
11
10
  import ByteBuffer from 'bytebuffer';
11
+ import transport, { COMMON_HEADER_SIZE } from '@onekeyfe/hd-transport';
12
+ import { createDeferred, Deferred, ERRORS, HardwareErrorCode } from '@onekeyfe/hd-shared';
12
13
  import { initializeBleManager, getConnectedDeviceIds, getBondedDevices } from './BleManager';
13
14
  import { subscribeBleOn } from './subscribeBleOn';
14
15
  import {
15
- PERMISSION_ERROR,
16
- LOCATION_ERROR,
17
16
  isOnekeyDevice,
18
17
  getBluetoothServiceUuids,
19
18
  getInfosForServiceUuid,
20
19
  IOS_PACKET_LENGTH,
21
20
  ANDROID_PACKET_LENGTH,
22
21
  } from './constants';
23
- import { Deferred, create as createDeferred } from './utils/deferred';
24
22
  import { isHeaderChunk } from './utils/validateNotify';
25
23
  import BleTransport from './BleTransport';
26
24
  import timer from './utils/timer';
@@ -111,9 +109,11 @@ export default class ReactNativeBleTransport {
111
109
  error.errorCode
112
110
  )
113
111
  ) {
114
- reject(new Error(PERMISSION_ERROR));
112
+ reject(ERRORS.TypedError(HardwareErrorCode.BlePermissionError));
113
+ } else if (error.errorCode === BleErrorCode.BluetoothUnauthorized) {
114
+ reject(ERRORS.TypedError(HardwareErrorCode.BleLocationError));
115
115
  } else {
116
- reject(error);
116
+ reject(ERRORS.TypedError(HardwareErrorCode.BleScanError, error.reason ?? ''));
117
117
  }
118
118
  return;
119
119
  }
@@ -156,7 +156,7 @@ export default class ReactNativeBleTransport {
156
156
  const { uuid } = input;
157
157
 
158
158
  if (!uuid) {
159
- throw new Error('uuid is required');
159
+ throw ERRORS.TypedError(HardwareErrorCode.BleRequiredUUID);
160
160
  }
161
161
 
162
162
  let device: Device | null = null;
@@ -203,13 +203,13 @@ export default class ReactNativeBleTransport {
203
203
  connectOptions = {};
204
204
  device = await blePlxManager.connectToDevice(uuid);
205
205
  } else {
206
- throw e;
206
+ throw ERRORS.TypedError(HardwareErrorCode.BleConnectedError, e.reason ?? e);
207
207
  }
208
208
  }
209
209
  }
210
210
 
211
211
  if (!device) {
212
- throw new Error('unable to connect to device');
212
+ throw ERRORS.TypedError(HardwareErrorCode.BleConnectedError, 'unable to connect to device');
213
213
  }
214
214
 
215
215
  if (!(await device.isConnected())) {
@@ -226,7 +226,7 @@ export default class ReactNativeBleTransport {
226
226
  connectOptions = {};
227
227
  await device.connect();
228
228
  } else {
229
- throw e;
229
+ throw ERRORS.TypedError(HardwareErrorCode.BleConnectedError, e.reason ?? e);
230
230
  }
231
231
  }
232
232
  }
@@ -236,7 +236,7 @@ export default class ReactNativeBleTransport {
236
236
  const bondedDevices = await getBondedDevices();
237
237
  const hasBonded = !!bondedDevices.find(bondedDevice => bondedDevice.id === device?.id);
238
238
  if (!hasBonded) {
239
- throw new Error('device is not bonded');
239
+ throw ERRORS.TypedError('device is not bonded');
240
240
  }
241
241
  }
242
242
 
@@ -251,13 +251,13 @@ export default class ReactNativeBleTransport {
251
251
  infos = getInfosForServiceUuid(serviceUuid, 'classic');
252
252
  break;
253
253
  } catch (e) {
254
- // empty
254
+ console.log(e);
255
255
  }
256
256
  }
257
257
  }
258
258
 
259
259
  if (!infos) {
260
- throw new Error('BLEServiceNotFound: service not found');
260
+ throw ERRORS.TypedError(HardwareErrorCode.BleServiceNotFound);
261
261
  }
262
262
 
263
263
  const { serviceUuid, writeUuid, notifyUuid } = infos;
@@ -267,7 +267,7 @@ export default class ReactNativeBleTransport {
267
267
  }
268
268
 
269
269
  if (!characteristics) {
270
- throw new Error('BLEServiceNotFound: characteristics not found');
270
+ throw ERRORS.TypedError(HardwareErrorCode.BleCharacteristicNotFound);
271
271
  }
272
272
 
273
273
  let writeCharacteristic;
@@ -281,28 +281,31 @@ export default class ReactNativeBleTransport {
281
281
  }
282
282
 
283
283
  if (!writeCharacteristic) {
284
- throw new Error('BLECharacteristicNotFound: write characteristic not found');
284
+ throw ERRORS.TypedError('BLECharacteristicNotFound: write characteristic not found');
285
285
  }
286
286
 
287
287
  if (!notifyCharacteristic) {
288
- throw new Error('BLECharacteristicNotFound: notify characteristic not found');
288
+ throw ERRORS.TypedError('BLECharacteristicNotFound: notify characteristic not found');
289
289
  }
290
290
 
291
291
  if (!writeCharacteristic.isWritableWithResponse) {
292
- throw new Error('BLECharacteristicNotWritable: write characteristic not writable');
292
+ throw ERRORS.TypedError('BLECharacteristicNotWritable: write characteristic not writable');
293
293
  }
294
294
 
295
295
  if (!notifyCharacteristic.isNotifiable) {
296
- throw new Error('BLECharacteristicNotNotifiable: notify characteristic not notifiable');
296
+ throw ERRORS.TypedError(
297
+ 'BLECharacteristicNotNotifiable: notify characteristic not notifiable'
298
+ );
297
299
  }
298
300
 
299
301
  const transport = new BleTransport(device, writeCharacteristic, notifyCharacteristic);
300
302
  transport.nofitySubscription = this._monitorCharacteristic(transport.notifyCharacteristic);
301
303
  transportCache[uuid] = transport;
302
304
 
303
- device.onDisconnected(() => {
305
+ const disconnectSubscription = device.onDisconnected(() => {
304
306
  console.log('device disconnect: ', device?.id);
305
307
  this.release(uuid);
308
+ disconnectSubscription?.remove();
306
309
  });
307
310
 
308
311
  return { uuid };
@@ -318,11 +321,20 @@ export default class ReactNativeBleTransport {
318
321
  error as unknown as string
319
322
  }`
320
323
  );
324
+ if (this.runPromise) {
325
+ this.runPromise.reject(
326
+ ERRORS.TypedError(
327
+ HardwareErrorCode.BleCharacteristicNotifyError,
328
+ error.reason ?? error.message
329
+ )
330
+ );
331
+ console.log('@onekey/hd-ble-sdk: monitor notify error, and has unreleased Promise');
332
+ }
321
333
  return;
322
334
  }
323
335
 
324
336
  if (!c) {
325
- throw new Error('Monitor Error: characteristic not found');
337
+ throw ERRORS.TypedError(HardwareErrorCode.BleMonitorError);
326
338
  }
327
339
 
328
340
  try {
@@ -376,19 +388,19 @@ export default class ReactNativeBleTransport {
376
388
  async call(uuid: string, name: string, data: Record<string, unknown>) {
377
389
  if (this.stopped) {
378
390
  // eslint-disable-next-line prefer-promise-reject-errors
379
- return Promise.reject('Transport stopped.');
391
+ return Promise.reject(ERRORS.TypedError('Transport stopped.'));
380
392
  }
381
393
  if (this._messages == null) {
382
- throw new Error('Transport not configured.');
394
+ throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
383
395
  }
384
396
 
385
397
  if (this.runPromise) {
386
- throw new Error('Transport_CallInProgress');
398
+ throw ERRORS.TypedError(HardwareErrorCode.TransportCallInProgress);
387
399
  }
388
400
 
389
401
  const transport = transportCache[uuid] as BleTransport;
390
402
  if (!transport) {
391
- throw new Error('Transport not found.');
403
+ throw ERRORS.TypedError(HardwareErrorCode.TransportNotFound);
392
404
  }
393
405
 
394
406
  this.runPromise = createDeferred();
@@ -425,7 +437,7 @@ export default class ReactNativeBleTransport {
425
437
  await transport.writeCharacteristic.writeWithoutResponse(outData);
426
438
  } catch (e) {
427
439
  if (e.errorCode === BleErrorCode.DeviceDisconnected) {
428
- throw new Error('device is not bonded');
440
+ throw ERRORS.TypedError(HardwareErrorCode.BleDeviceNotBonded);
429
441
  }
430
442
  this.runPromise = null;
431
443
  console.log('writeCharacteristic write error: ', e);
@@ -464,5 +476,3 @@ export default class ReactNativeBleTransport {
464
476
  this.runPromise = null;
465
477
  }
466
478
  }
467
-
468
- export { PERMISSION_ERROR, LOCATION_ERROR };
@@ -1,4 +1,4 @@
1
- import { PERMISSION_ERROR } from './constants';
1
+ import { ERRORS, HardwareErrorCode } from '@onekeyfe/hd-shared';
2
2
  import { BlePlxManager } from './types';
3
3
  import timer from './utils/timer';
4
4
 
@@ -21,6 +21,6 @@ export const subscribeBleOn = (bleManager: BlePlxManager, ms = 1000): Promise<vo
21
21
  const clearTimeout = timer.timeout(() => {
22
22
  if (done) return;
23
23
  subscription.remove();
24
- reject(new Error(PERMISSION_ERROR));
24
+ reject(ERRORS.TypedError(HardwareErrorCode.BlePermissionError));
25
25
  }, ms);
26
26
  });
@@ -1,9 +0,0 @@
1
- export declare type Deferred<T, I = any, D = any> = {
2
- id?: I;
3
- data?: D;
4
- promise: Promise<T>;
5
- resolve: (t: T) => void;
6
- reject: (e: Error) => void;
7
- };
8
- export declare function create<T, I = any, D = any>(arg?: I, data?: D): Deferred<T, I, D>;
9
- //# sourceMappingURL=deferred.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"deferred.d.ts","sourceRoot":"","sources":["../../src/utils/deferred.ts"],"names":[],"mappings":"AAAA,oBAAY,QAAQ,CAAC,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,GAAG,IAAI;IAC1C,EAAE,CAAC,EAAE,CAAC,CAAC;IACP,IAAI,CAAC,EAAE,CAAC,CAAC;IACT,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IACpB,OAAO,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,IAAI,CAAC;IACxB,MAAM,EAAE,CAAC,CAAC,EAAE,KAAK,KAAK,IAAI,CAAC;CAC5B,CAAC;AAEF,wBAAgB,MAAM,CAAC,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,GAAG,EAAE,GAAG,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CA0BhF"}
@@ -1,35 +0,0 @@
1
- export type Deferred<T, I = any, D = any> = {
2
- id?: I;
3
- data?: D;
4
- promise: Promise<T>;
5
- resolve: (t: T) => void;
6
- reject: (e: Error) => void;
7
- };
8
-
9
- export function create<T, I = any, D = any>(arg?: I, data?: D): Deferred<T, I, D> {
10
- let localResolve: (t: T) => void = (_t: T) => {};
11
- let localReject: (e?: Error) => void = (_e?: Error) => {};
12
- let id: I | undefined;
13
-
14
- // eslint-disable-next-line no-async-promise-executor
15
- const promise: Promise<T> = new Promise(async (resolve, reject) => {
16
- localResolve = resolve;
17
- localReject = reject;
18
- if (typeof arg === 'function') {
19
- try {
20
- await arg();
21
- } catch (error) {
22
- reject(error);
23
- }
24
- }
25
- if (typeof arg === 'string') id = arg;
26
- });
27
-
28
- return {
29
- id,
30
- data,
31
- resolve: localResolve,
32
- reject: localReject,
33
- promise,
34
- };
35
- }