@onekeyfe/hd-transport-react-native 0.1.4 → 0.1.7

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;IAoET,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,19 @@ 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));
258
228
  }
259
229
  else {
260
- reject(error);
230
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleScanError, (_a = error.reason) !== null && _a !== void 0 ? _a : ''));
261
231
  }
262
232
  return;
263
233
  }
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)) {
234
+ 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
235
  console.log('search device start ======================');
266
236
  const { name, localName, id } = device !== null && device !== void 0 ? device : {};
267
237
  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 +258,11 @@ class ReactNativeBleTransport {
288
258
  });
289
259
  }
290
260
  acquire(input) {
261
+ var _a, _b;
291
262
  return __awaiter(this, void 0, void 0, function* () {
292
263
  const { uuid } = input;
293
264
  if (!uuid) {
294
- throw new Error('uuid is required');
265
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleRequiredUUID);
295
266
  }
296
267
  let device = null;
297
268
  if (transportCache[uuid]) {
@@ -329,12 +300,12 @@ class ReactNativeBleTransport {
329
300
  device = yield blePlxManager.connectToDevice(uuid);
330
301
  }
331
302
  else {
332
- throw e;
303
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, (_a = e.reason) !== null && _a !== void 0 ? _a : e);
333
304
  }
334
305
  }
335
306
  }
336
307
  if (!device) {
337
- throw new Error('unable to connect to device');
308
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, 'unable to connect to device');
338
309
  }
339
310
  if (!(yield device.isConnected())) {
340
311
  console.log('not connected, try to connect to device: ', uuid);
@@ -349,7 +320,7 @@ class ReactNativeBleTransport {
349
320
  yield device.connect();
350
321
  }
351
322
  else {
352
- throw e;
323
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, (_b = e.reason) !== null && _b !== void 0 ? _b : e);
353
324
  }
354
325
  }
355
326
  }
@@ -357,7 +328,7 @@ class ReactNativeBleTransport {
357
328
  const bondedDevices = yield getBondedDevices();
358
329
  const hasBonded = !!bondedDevices.find(bondedDevice => bondedDevice.id === (device === null || device === void 0 ? void 0 : device.id));
359
330
  if (!hasBonded) {
360
- throw new Error('device is not bonded');
331
+ throw hdShared.ERRORS.TypedError('device is not bonded');
361
332
  }
362
333
  }
363
334
  yield device.discoverAllServicesAndCharacteristics();
@@ -371,18 +342,19 @@ class ReactNativeBleTransport {
371
342
  break;
372
343
  }
373
344
  catch (e) {
345
+ console.log(e);
374
346
  }
375
347
  }
376
348
  }
377
349
  if (!infos) {
378
- throw new Error('BLEServiceNotFound: service not found');
350
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound);
379
351
  }
380
352
  const { serviceUuid, writeUuid, notifyUuid } = infos;
381
353
  if (!characteristics) {
382
354
  characteristics = yield device.characteristicsForService(serviceUuid);
383
355
  }
384
356
  if (!characteristics) {
385
- throw new Error('BLEServiceNotFound: characteristics not found');
357
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleCharacteristicNotFound);
386
358
  }
387
359
  let writeCharacteristic;
388
360
  let notifyCharacteristic;
@@ -395,23 +367,24 @@ class ReactNativeBleTransport {
395
367
  }
396
368
  }
397
369
  if (!writeCharacteristic) {
398
- throw new Error('BLECharacteristicNotFound: write characteristic not found');
370
+ throw hdShared.ERRORS.TypedError('BLECharacteristicNotFound: write characteristic not found');
399
371
  }
400
372
  if (!notifyCharacteristic) {
401
- throw new Error('BLECharacteristicNotFound: notify characteristic not found');
373
+ throw hdShared.ERRORS.TypedError('BLECharacteristicNotFound: notify characteristic not found');
402
374
  }
403
375
  if (!writeCharacteristic.isWritableWithResponse) {
404
- throw new Error('BLECharacteristicNotWritable: write characteristic not writable');
376
+ throw hdShared.ERRORS.TypedError('BLECharacteristicNotWritable: write characteristic not writable');
405
377
  }
406
378
  if (!notifyCharacteristic.isNotifiable) {
407
- throw new Error('BLECharacteristicNotNotifiable: notify characteristic not notifiable');
379
+ throw hdShared.ERRORS.TypedError('BLECharacteristicNotNotifiable: notify characteristic not notifiable');
408
380
  }
409
381
  const transport = new BleTransport(device, writeCharacteristic, notifyCharacteristic);
410
382
  transport.nofitySubscription = this._monitorCharacteristic(transport.notifyCharacteristic);
411
383
  transportCache[uuid] = transport;
412
- device.onDisconnected(() => {
384
+ const disconnectSubscription = device.onDisconnected(() => {
413
385
  console.log('device disconnect: ', device === null || device === void 0 ? void 0 : device.id);
414
386
  this.release(uuid);
387
+ disconnectSubscription === null || disconnectSubscription === void 0 ? void 0 : disconnectSubscription.remove();
415
388
  });
416
389
  return { uuid };
417
390
  });
@@ -420,13 +393,17 @@ class ReactNativeBleTransport {
420
393
  let bufferLength = 0;
421
394
  let buffer$1 = [];
422
395
  const subscription = characteristic.monitor((error, c) => {
423
- var _a, _b;
396
+ var _a, _b, _c;
424
397
  if (error) {
425
398
  console.log(`error monitor ${characteristic.uuid}, deviceId: ${characteristic.deviceID}: ${error}`);
399
+ if (this.runPromise) {
400
+ this.runPromise.reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleCharacteristicNotifyError, (_a = error.reason) !== null && _a !== void 0 ? _a : error.message));
401
+ console.log('@onekey/hd-ble-sdk: monitor notify error, and has unreleased Promise');
402
+ }
426
403
  return;
427
404
  }
428
405
  if (!c) {
429
- throw new Error('Monitor Error: characteristic not found');
406
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleMonitorError);
430
407
  }
431
408
  try {
432
409
  const data = buffer.Buffer.from(c.value, 'base64');
@@ -441,12 +418,12 @@ class ReactNativeBleTransport {
441
418
  const value = buffer.Buffer.from(buffer$1);
442
419
  bufferLength = 0;
443
420
  buffer$1 = [];
444
- (_a = this.runPromise) === null || _a === void 0 ? void 0 : _a.resolve(value.toString('hex'));
421
+ (_b = this.runPromise) === null || _b === void 0 ? void 0 : _b.resolve(value.toString('hex'));
445
422
  }
446
423
  }
447
424
  catch (error) {
448
425
  console.log('monitor data error: ', error);
449
- (_b = this.runPromise) === null || _b === void 0 ? void 0 : _b.reject(error);
426
+ (_c = this.runPromise) === null || _c === void 0 ? void 0 : _c.reject(error);
450
427
  }
451
428
  });
452
429
  return () => {
@@ -471,19 +448,19 @@ class ReactNativeBleTransport {
471
448
  call(uuid, name, data) {
472
449
  return __awaiter(this, void 0, void 0, function* () {
473
450
  if (this.stopped) {
474
- return Promise.reject('Transport stopped.');
451
+ return Promise.reject(hdShared.ERRORS.TypedError('Transport stopped.'));
475
452
  }
476
453
  if (this._messages == null) {
477
- throw new Error('Transport not configured.');
454
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
478
455
  }
479
456
  if (this.runPromise) {
480
- throw new Error('Transport_CallInProgress');
457
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportCallInProgress);
481
458
  }
482
459
  const transport = transportCache[uuid];
483
460
  if (!transport) {
484
- throw new Error('Transport not found.');
461
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
485
462
  }
486
- this.runPromise = create();
463
+ this.runPromise = hdShared.createDeferred();
487
464
  const messages = this._messages;
488
465
  console.log('transport-react-native', 'call-', ' name: ', name, ' data: ', data);
489
466
  const buffers = buildBuffers(messages, name, data);
@@ -519,7 +496,7 @@ class ReactNativeBleTransport {
519
496
  }
520
497
  catch (e) {
521
498
  if (e.errorCode === reactNativeBlePlx.BleErrorCode.DeviceDisconnected) {
522
- throw new Error('device is not bonded');
499
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceNotBonded);
523
500
  }
524
501
  this.runPromise = null;
525
502
  console.log('writeCharacteristic write error: ', e);
@@ -555,6 +532,4 @@ class ReactNativeBleTransport {
555
532
  }
556
533
  }
557
534
 
558
- exports.LOCATION_ERROR = LOCATION_ERROR;
559
- exports.PERMISSION_ERROR = PERMISSION_ERROR;
560
- exports["default"] = ReactNativeBleTransport;
535
+ 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.4",
3
+ "version": "0.1.7",
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.4",
23
+ "@onekeyfe/hd-shared": "^0.1.7",
24
+ "@onekeyfe/hd-transport": "^0.1.7",
24
25
  "react-native-ble-manager": "^8.1.0",
25
26
  "react-native-ble-plx": "^2.0.3"
26
27
  },
27
- "gitHead": "11d482262e5af9baf45b0b554006cff0aebed97c"
28
+ "gitHead": "1d3889d02e41afd60cd0388b6e01d7f2ac7c5399"
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,9 @@ export default class ReactNativeBleTransport {
111
109
  error.errorCode
112
110
  )
113
111
  ) {
114
- reject(new Error(PERMISSION_ERROR));
112
+ reject(ERRORS.TypedError(HardwareErrorCode.BlePermissionError));
115
113
  } else {
116
- reject(error);
114
+ reject(ERRORS.TypedError(HardwareErrorCode.BleScanError, error.reason ?? ''));
117
115
  }
118
116
  return;
119
117
  }
@@ -156,7 +154,7 @@ export default class ReactNativeBleTransport {
156
154
  const { uuid } = input;
157
155
 
158
156
  if (!uuid) {
159
- throw new Error('uuid is required');
157
+ throw ERRORS.TypedError(HardwareErrorCode.BleRequiredUUID);
160
158
  }
161
159
 
162
160
  let device: Device | null = null;
@@ -203,13 +201,13 @@ export default class ReactNativeBleTransport {
203
201
  connectOptions = {};
204
202
  device = await blePlxManager.connectToDevice(uuid);
205
203
  } else {
206
- throw e;
204
+ throw ERRORS.TypedError(HardwareErrorCode.BleConnectedError, e.reason ?? e);
207
205
  }
208
206
  }
209
207
  }
210
208
 
211
209
  if (!device) {
212
- throw new Error('unable to connect to device');
210
+ throw ERRORS.TypedError(HardwareErrorCode.BleConnectedError, 'unable to connect to device');
213
211
  }
214
212
 
215
213
  if (!(await device.isConnected())) {
@@ -226,7 +224,7 @@ export default class ReactNativeBleTransport {
226
224
  connectOptions = {};
227
225
  await device.connect();
228
226
  } else {
229
- throw e;
227
+ throw ERRORS.TypedError(HardwareErrorCode.BleConnectedError, e.reason ?? e);
230
228
  }
231
229
  }
232
230
  }
@@ -236,7 +234,7 @@ export default class ReactNativeBleTransport {
236
234
  const bondedDevices = await getBondedDevices();
237
235
  const hasBonded = !!bondedDevices.find(bondedDevice => bondedDevice.id === device?.id);
238
236
  if (!hasBonded) {
239
- throw new Error('device is not bonded');
237
+ throw ERRORS.TypedError('device is not bonded');
240
238
  }
241
239
  }
242
240
 
@@ -251,13 +249,13 @@ export default class ReactNativeBleTransport {
251
249
  infos = getInfosForServiceUuid(serviceUuid, 'classic');
252
250
  break;
253
251
  } catch (e) {
254
- // empty
252
+ console.log(e);
255
253
  }
256
254
  }
257
255
  }
258
256
 
259
257
  if (!infos) {
260
- throw new Error('BLEServiceNotFound: service not found');
258
+ throw ERRORS.TypedError(HardwareErrorCode.BleServiceNotFound);
261
259
  }
262
260
 
263
261
  const { serviceUuid, writeUuid, notifyUuid } = infos;
@@ -267,7 +265,7 @@ export default class ReactNativeBleTransport {
267
265
  }
268
266
 
269
267
  if (!characteristics) {
270
- throw new Error('BLEServiceNotFound: characteristics not found');
268
+ throw ERRORS.TypedError(HardwareErrorCode.BleCharacteristicNotFound);
271
269
  }
272
270
 
273
271
  let writeCharacteristic;
@@ -281,28 +279,31 @@ export default class ReactNativeBleTransport {
281
279
  }
282
280
 
283
281
  if (!writeCharacteristic) {
284
- throw new Error('BLECharacteristicNotFound: write characteristic not found');
282
+ throw ERRORS.TypedError('BLECharacteristicNotFound: write characteristic not found');
285
283
  }
286
284
 
287
285
  if (!notifyCharacteristic) {
288
- throw new Error('BLECharacteristicNotFound: notify characteristic not found');
286
+ throw ERRORS.TypedError('BLECharacteristicNotFound: notify characteristic not found');
289
287
  }
290
288
 
291
289
  if (!writeCharacteristic.isWritableWithResponse) {
292
- throw new Error('BLECharacteristicNotWritable: write characteristic not writable');
290
+ throw ERRORS.TypedError('BLECharacteristicNotWritable: write characteristic not writable');
293
291
  }
294
292
 
295
293
  if (!notifyCharacteristic.isNotifiable) {
296
- throw new Error('BLECharacteristicNotNotifiable: notify characteristic not notifiable');
294
+ throw ERRORS.TypedError(
295
+ 'BLECharacteristicNotNotifiable: notify characteristic not notifiable'
296
+ );
297
297
  }
298
298
 
299
299
  const transport = new BleTransport(device, writeCharacteristic, notifyCharacteristic);
300
300
  transport.nofitySubscription = this._monitorCharacteristic(transport.notifyCharacteristic);
301
301
  transportCache[uuid] = transport;
302
302
 
303
- device.onDisconnected(() => {
303
+ const disconnectSubscription = device.onDisconnected(() => {
304
304
  console.log('device disconnect: ', device?.id);
305
305
  this.release(uuid);
306
+ disconnectSubscription?.remove();
306
307
  });
307
308
 
308
309
  return { uuid };
@@ -318,11 +319,20 @@ export default class ReactNativeBleTransport {
318
319
  error as unknown as string
319
320
  }`
320
321
  );
322
+ if (this.runPromise) {
323
+ this.runPromise.reject(
324
+ ERRORS.TypedError(
325
+ HardwareErrorCode.BleCharacteristicNotifyError,
326
+ error.reason ?? error.message
327
+ )
328
+ );
329
+ console.log('@onekey/hd-ble-sdk: monitor notify error, and has unreleased Promise');
330
+ }
321
331
  return;
322
332
  }
323
333
 
324
334
  if (!c) {
325
- throw new Error('Monitor Error: characteristic not found');
335
+ throw ERRORS.TypedError(HardwareErrorCode.BleMonitorError);
326
336
  }
327
337
 
328
338
  try {
@@ -376,19 +386,19 @@ export default class ReactNativeBleTransport {
376
386
  async call(uuid: string, name: string, data: Record<string, unknown>) {
377
387
  if (this.stopped) {
378
388
  // eslint-disable-next-line prefer-promise-reject-errors
379
- return Promise.reject('Transport stopped.');
389
+ return Promise.reject(ERRORS.TypedError('Transport stopped.'));
380
390
  }
381
391
  if (this._messages == null) {
382
- throw new Error('Transport not configured.');
392
+ throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
383
393
  }
384
394
 
385
395
  if (this.runPromise) {
386
- throw new Error('Transport_CallInProgress');
396
+ throw ERRORS.TypedError(HardwareErrorCode.TransportCallInProgress);
387
397
  }
388
398
 
389
399
  const transport = transportCache[uuid] as BleTransport;
390
400
  if (!transport) {
391
- throw new Error('Transport not found.');
401
+ throw ERRORS.TypedError(HardwareErrorCode.TransportNotFound);
392
402
  }
393
403
 
394
404
  this.runPromise = createDeferred();
@@ -425,7 +435,7 @@ export default class ReactNativeBleTransport {
425
435
  await transport.writeCharacteristic.writeWithoutResponse(outData);
426
436
  } catch (e) {
427
437
  if (e.errorCode === BleErrorCode.DeviceDisconnected) {
428
- throw new Error('device is not bonded');
438
+ throw ERRORS.TypedError(HardwareErrorCode.BleDeviceNotBonded);
429
439
  }
430
440
  this.runPromise = null;
431
441
  console.log('writeCharacteristic write error: ', e);
@@ -464,5 +474,3 @@ export default class ReactNativeBleTransport {
464
474
  this.runPromise = null;
465
475
  }
466
476
  }
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
- }