@onekeyfe/hd-transport-react-native 0.1.3 → 0.1.6

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;;;IA2JpC,sBAAsB,CAAC,cAAc,EAAE,cAAc;IA+C/C,OAAO,CAAC,IAAI,EAAE,MAAM;IAepB,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;;;IA8JpC,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"}
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,21 +367,22 @@ 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
384
  device.onDisconnected(() => {
385
+ console.log('device disconnect: ', device === null || device === void 0 ? void 0 : device.id);
413
386
  this.release(uuid);
414
387
  });
415
388
  return { uuid };
@@ -421,11 +394,11 @@ class ReactNativeBleTransport {
421
394
  const subscription = characteristic.monitor((error, c) => {
422
395
  var _a, _b;
423
396
  if (error) {
424
- console.log(`error monitor ${characteristic.uuid}: ${error}`);
397
+ console.log(`error monitor ${characteristic.uuid}, deviceId: ${characteristic.deviceID}: ${error}`);
425
398
  return;
426
399
  }
427
400
  if (!c) {
428
- throw new Error('Monitor Error: characteristic not found');
401
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleMonitorError);
429
402
  }
430
403
  try {
431
404
  const data = buffer.Buffer.from(c.value, 'base64');
@@ -454,12 +427,15 @@ class ReactNativeBleTransport {
454
427
  };
455
428
  }
456
429
  release(uuid) {
457
- var _a;
430
+ var _a, _b;
458
431
  return __awaiter(this, void 0, void 0, function* () {
459
432
  const transport = transportCache[uuid];
460
433
  if (transport) {
461
434
  delete transportCache[uuid];
462
435
  (_a = transport.nofitySubscription) === null || _a === void 0 ? void 0 : _a.call(transport);
436
+ if (reactNative.Platform.OS === 'android') {
437
+ yield ((_b = this.blePlxManager) === null || _b === void 0 ? void 0 : _b.cancelDeviceConnection(uuid));
438
+ }
463
439
  }
464
440
  return Promise.resolve(true);
465
441
  });
@@ -467,19 +443,19 @@ class ReactNativeBleTransport {
467
443
  call(uuid, name, data) {
468
444
  return __awaiter(this, void 0, void 0, function* () {
469
445
  if (this.stopped) {
470
- return Promise.reject('Transport stopped.');
446
+ return Promise.reject(hdShared.ERRORS.TypedError('Transport stopped.'));
471
447
  }
472
448
  if (this._messages == null) {
473
- throw new Error('Transport not configured.');
449
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
474
450
  }
475
451
  if (this.runPromise) {
476
- throw new Error('Transport_CallInProgress');
452
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportCallInProgress);
477
453
  }
478
454
  const transport = transportCache[uuid];
479
455
  if (!transport) {
480
- throw new Error('Transport not found.');
456
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotFound);
481
457
  }
482
- this.runPromise = create();
458
+ this.runPromise = hdShared.createDeferred();
483
459
  const messages = this._messages;
484
460
  console.log('transport-react-native', 'call-', ' name: ', name, ' data: ', data);
485
461
  const buffers = buildBuffers(messages, name, data);
@@ -511,11 +487,11 @@ class ReactNativeBleTransport {
511
487
  const outData = o.toString('base64');
512
488
  console.log('@onekey/hd-ble-sdk send hex strting: ', o.toString('hex'));
513
489
  try {
514
- yield transport.writeCharacteristic.writeWithResponse(outData);
490
+ yield transport.writeCharacteristic.writeWithoutResponse(outData);
515
491
  }
516
492
  catch (e) {
517
493
  if (e.errorCode === reactNativeBlePlx.BleErrorCode.DeviceDisconnected) {
518
- throw new Error('device is not bonded');
494
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleDeviceNotBonded);
519
495
  }
520
496
  this.runPromise = null;
521
497
  console.log('writeCharacteristic write error: ', e);
@@ -551,6 +527,4 @@ class ReactNativeBleTransport {
551
527
  }
552
528
  }
553
529
 
554
- exports.LOCATION_ERROR = LOCATION_ERROR;
555
- exports.PERMISSION_ERROR = PERMISSION_ERROR;
556
- exports["default"] = ReactNativeBleTransport;
530
+ 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.3",
3
+ "version": "0.1.6",
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.3",
23
+ "@onekeyfe/hd-shared": "^0.1.6",
24
+ "@onekeyfe/hd-transport": "^0.1.6",
24
25
  "react-native-ble-manager": "^8.1.0",
25
26
  "react-native-ble-plx": "^2.0.3"
26
27
  },
27
- "gitHead": "64411d3cac440d142574f8aa30c9d60204d47c2c"
28
+ "gitHead": "ebe2789fa24cbfb798c9be445678e71e67e33d71"
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,19 +279,21 @@ 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);
@@ -301,6 +301,7 @@ export default class ReactNativeBleTransport {
301
301
  transportCache[uuid] = transport;
302
302
 
303
303
  device.onDisconnected(() => {
304
+ console.log('device disconnect: ', device?.id);
304
305
  this.release(uuid);
305
306
  });
306
307
 
@@ -312,12 +313,16 @@ export default class ReactNativeBleTransport {
312
313
  let buffer: any[] = [];
313
314
  const subscription = characteristic.monitor((error, c) => {
314
315
  if (error) {
315
- console.log(`error monitor ${characteristic.uuid}: ${error as unknown as string}`);
316
+ console.log(
317
+ `error monitor ${characteristic.uuid}, deviceId: ${characteristic.deviceID}: ${
318
+ error as unknown as string
319
+ }`
320
+ );
316
321
  return;
317
322
  }
318
323
 
319
324
  if (!c) {
320
- throw new Error('Monitor Error: characteristic not found');
325
+ throw ERRORS.TypedError(HardwareErrorCode.BleMonitorError);
321
326
  }
322
327
 
323
328
  try {
@@ -360,31 +365,30 @@ export default class ReactNativeBleTransport {
360
365
  if (transport) {
361
366
  delete transportCache[uuid];
362
367
  transport.nofitySubscription?.();
368
+ if (Platform.OS === 'android') {
369
+ await this.blePlxManager?.cancelDeviceConnection(uuid);
370
+ }
363
371
  }
364
372
 
365
- /**
366
- * The current strategy does not require disconnection
367
- */
368
- // await blePlxManager.cancelDeviceConnection(uuid);
369
373
  return Promise.resolve(true);
370
374
  }
371
375
 
372
376
  async call(uuid: string, name: string, data: Record<string, unknown>) {
373
377
  if (this.stopped) {
374
378
  // eslint-disable-next-line prefer-promise-reject-errors
375
- return Promise.reject('Transport stopped.');
379
+ return Promise.reject(ERRORS.TypedError('Transport stopped.'));
376
380
  }
377
381
  if (this._messages == null) {
378
- throw new Error('Transport not configured.');
382
+ throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
379
383
  }
380
384
 
381
385
  if (this.runPromise) {
382
- throw new Error('Transport_CallInProgress');
386
+ throw ERRORS.TypedError(HardwareErrorCode.TransportCallInProgress);
383
387
  }
384
388
 
385
389
  const transport = transportCache[uuid] as BleTransport;
386
390
  if (!transport) {
387
- throw new Error('Transport not found.');
391
+ throw ERRORS.TypedError(HardwareErrorCode.TransportNotFound);
388
392
  }
389
393
 
390
394
  this.runPromise = createDeferred();
@@ -418,10 +422,10 @@ export default class ReactNativeBleTransport {
418
422
  const outData = o.toString('base64');
419
423
  console.log('@onekey/hd-ble-sdk send hex strting: ', o.toString('hex'));
420
424
  try {
421
- await transport.writeCharacteristic.writeWithResponse(outData);
425
+ await transport.writeCharacteristic.writeWithoutResponse(outData);
422
426
  } catch (e) {
423
427
  if (e.errorCode === BleErrorCode.DeviceDisconnected) {
424
- throw new Error('device is not bonded');
428
+ throw ERRORS.TypedError(HardwareErrorCode.BleDeviceNotBonded);
425
429
  }
426
430
  this.runPromise = null;
427
431
  console.log('writeCharacteristic write error: ', e);
@@ -460,5 +464,3 @@ export default class ReactNativeBleTransport {
460
464
  this.runPromise = null;
461
465
  }
462
466
  }
463
-
464
- 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
- }