@onekeyfe/hd-transport-electron 1.1.23 → 1.1.24-alpha.1

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.
@@ -32,7 +32,7 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
32
32
 
33
33
  function initNobleBleSupport(webContents) {
34
34
  return __awaiter(this, void 0, void 0, function* () {
35
- const { setupNobleBleHandlers } = yield Promise.resolve().then(function () { return require('./noble-ble-handler-1a6d7f4a.js'); });
35
+ const { setupNobleBleHandlers } = yield Promise.resolve().then(function () { return require('./noble-ble-handler-2e41f27c.js'); });
36
36
  setupNobleBleHandlers(webContents);
37
37
  });
38
38
  }
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var index = require('./index-1fa563cd.js');
5
+ var index = require('./index-de36348d.js');
6
6
 
7
7
 
8
8
 
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var index = require('./index-1fa563cd.js');
3
+ var index = require('./index-de36348d.js');
4
4
  var hdShared = require('@onekeyfe/hd-shared');
5
5
  var hdTransport = require('@onekeyfe/hd-transport');
6
6
  var pRetry = require('p-retry');
@@ -85,6 +85,7 @@ const DEVICE_SCAN_TIMEOUT = 5000;
85
85
  const FAST_SCAN_TIMEOUT = 1500;
86
86
  const DEVICE_CHECK_INTERVAL = 500;
87
87
  const CONNECTION_TIMEOUT = 3000;
88
+ const SERVICE_DISCOVERY_TIMEOUT = 10000;
88
89
  const BLE_PACKET_SIZE = 192;
89
90
  const UNIFIED_WRITE_DELAY = 5;
90
91
  const RETRY_CONFIG = { MAX_ATTEMPTS: 15, WRITE_TIMEOUT: 2000 };
@@ -305,11 +306,12 @@ function initializeNoble() {
305
306
  }
306
307
  function cleanupDevice(deviceId, webContents, options = {}) {
307
308
  var _a;
308
- const { cleanupConnection = true, sendDisconnectEvent = false, cancelOperations = true, reason = 'unknown', } = options;
309
+ const { cleanupConnection = true, cleanupDiscoveredCache = false, sendDisconnectEvent = false, cancelOperations = true, reason = 'unknown', } = options;
309
310
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Starting device cleanup', {
310
311
  deviceId,
311
312
  reason,
312
313
  cleanupConnection,
314
+ cleanupDiscoveredCache,
313
315
  sendDisconnectEvent,
314
316
  cancelOperations,
315
317
  });
@@ -324,6 +326,9 @@ function cleanupDevice(deviceId, webContents, options = {}) {
324
326
  subscriptionOperations.delete(deviceId);
325
327
  pairedDevices.delete(deviceId);
326
328
  }
329
+ if (cleanupDiscoveredCache) {
330
+ discoveredDevices.delete(deviceId);
331
+ }
327
332
  if (sendDisconnectEvent && webContents) {
328
333
  webContents.send(hdShared.EOneKeyBleMessageKeys.BLE_DEVICE_DISCONNECTED, {
329
334
  id: deviceId,
@@ -469,7 +474,7 @@ function transmitHexDataToDevice(deviceId, hexData) {
469
474
  yield writeCharacteristicWithAck(deviceId, writeCharacteristic, toBuffer);
470
475
  return;
471
476
  }
472
- for (let offset = 0, idx = 0; offset < toBuffer.length; idx++) {
477
+ for (let offset = 0; offset < toBuffer.length;) {
473
478
  const chunkSize = Math.min(BLE_PACKET_SIZE, toBuffer.length - offset);
474
479
  const chunk = toBuffer.subarray(offset, offset + chunkSize);
475
480
  offset += chunkSize;
@@ -528,50 +533,40 @@ function performTargetedScan(targetDeviceId) {
528
533
  if (!noble) {
529
534
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'Noble not available');
530
535
  }
536
+ const nobleInstance = noble;
531
537
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Starting targeted scan for device:', targetDeviceId);
532
- ensureDiscoverListener();
533
538
  return new Promise((resolve, reject) => {
534
- const timeout = setTimeout(() => {
535
- if (noble) {
536
- noble.stopScanning();
537
- }
538
- logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Targeted scan timeout for device:', targetDeviceId);
539
- resolve(null);
540
- }, FAST_SCAN_TIMEOUT);
541
539
  const onDiscover = (peripheral) => {
542
540
  var _a;
543
541
  if (peripheral.id === targetDeviceId) {
544
- clearTimeout(timeout);
545
- if (noble) {
546
- noble.stopScanning();
547
- noble.removeListener('discover', onDiscover);
548
- }
549
- discoveredDevices.set(peripheral.id, peripheral);
550
- logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] OneKey device found during targeted scan:', {
542
+ logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Target device found during targeted scan:', {
551
543
  id: peripheral.id,
552
- name: ((_a = peripheral.advertisement) === null || _a === void 0 ? void 0 : _a.localName) || 'Unknown',
544
+ name: (_a = peripheral.advertisement) === null || _a === void 0 ? void 0 : _a.localName,
553
545
  });
546
+ clearTimeout(timeoutId);
547
+ nobleInstance.removeListener('discover', onDiscover);
548
+ nobleInstance.stopScanning();
549
+ discoveredDevices.set(peripheral.id, peripheral);
554
550
  resolve(peripheral);
555
551
  }
556
552
  };
557
- if (noble) {
558
- noble.removeListener('discover', onDiscover);
559
- noble.on('discover', onDiscover);
560
- }
561
- if (noble) {
562
- noble.startScanning(ONEKEY_SERVICE_UUIDS, false, (error) => {
563
- if (error) {
564
- clearTimeout(timeout);
565
- if (noble) {
566
- noble.removeListener('discover', onDiscover);
567
- }
568
- logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Failed to start targeted scan:', error);
569
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleScanError, error.message));
570
- return;
571
- }
572
- logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Targeted scan started for device:', targetDeviceId);
573
- });
574
- }
553
+ const timeoutId = setTimeout(() => {
554
+ nobleInstance.removeListener('discover', onDiscover);
555
+ nobleInstance.stopScanning();
556
+ logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Targeted scan timeout for device:', targetDeviceId);
557
+ resolve(null);
558
+ }, FAST_SCAN_TIMEOUT);
559
+ nobleInstance.on('discover', onDiscover);
560
+ nobleInstance.startScanning(ONEKEY_SERVICE_UUIDS, false, (error) => {
561
+ if (error) {
562
+ clearTimeout(timeoutId);
563
+ nobleInstance.removeListener('discover', onDiscover);
564
+ logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Failed to start targeted scan:', error);
565
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleScanError, error.message));
566
+ return;
567
+ }
568
+ logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Targeted scan started for device:', targetDeviceId);
569
+ });
575
570
  });
576
571
  });
577
572
  }
@@ -583,49 +578,48 @@ function enumerateDevices() {
583
578
  if (!noble) {
584
579
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'Noble not available');
585
580
  }
581
+ const nobleInstance = noble;
586
582
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Starting device enumeration');
587
583
  discoveredDevices.clear();
588
584
  ensureDiscoverListener();
589
585
  return new Promise((resolve, reject) => {
590
586
  const devices = [];
591
- if (!noble) {
592
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'Noble not available'));
593
- return;
594
- }
595
- const timeout = setTimeout(() => {
596
- if (noble) {
597
- noble.stopScanning();
598
- }
587
+ let intervalId;
588
+ const cleanup = () => {
589
+ clearTimeout(timeoutId);
590
+ if (intervalId)
591
+ clearInterval(intervalId);
592
+ nobleInstance.stopScanning();
593
+ };
594
+ const checkDevices = () => {
595
+ discoveredDevices.forEach((peripheral, id) => {
596
+ var _a;
597
+ const existingDevice = devices.find(d => d.id === id);
598
+ if (!existingDevice) {
599
+ const deviceName = ((_a = peripheral.advertisement) === null || _a === void 0 ? void 0 : _a.localName) || 'Unknown Device';
600
+ devices.push({
601
+ commType: 'electron-ble',
602
+ id,
603
+ name: deviceName,
604
+ state: peripheral.state || 'disconnected',
605
+ });
606
+ }
607
+ });
608
+ };
609
+ const timeoutId = setTimeout(() => {
610
+ cleanup();
599
611
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Scan completed, found devices:', devices.length);
600
612
  resolve(devices);
601
613
  }, DEVICE_SCAN_TIMEOUT);
602
- noble.startScanning(ONEKEY_SERVICE_UUIDS, false, (error) => {
614
+ nobleInstance.startScanning(ONEKEY_SERVICE_UUIDS, false, (error) => {
603
615
  if (error) {
604
- clearTimeout(timeout);
616
+ cleanup();
605
617
  logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Failed to start scanning:', error);
606
618
  reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleScanError, error.message));
607
619
  return;
608
620
  }
609
621
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Scanning started for OneKey devices');
610
- const checkDevices = () => {
611
- discoveredDevices.forEach((peripheral, id) => {
612
- var _a;
613
- const existingDevice = devices.find(d => d.id === id);
614
- if (!existingDevice) {
615
- const deviceName = ((_a = peripheral.advertisement) === null || _a === void 0 ? void 0 : _a.localName) || 'Unknown Device';
616
- devices.push({
617
- commType: 'electron-ble',
618
- id,
619
- name: deviceName,
620
- state: peripheral.state || 'disconnected',
621
- });
622
- }
623
- });
624
- };
625
- const interval = setInterval(checkDevices, DEVICE_CHECK_INTERVAL);
626
- setTimeout(() => {
627
- clearInterval(interval);
628
- }, DEVICE_SCAN_TIMEOUT);
622
+ intervalId = setInterval(checkDevices, DEVICE_CHECK_INTERVAL);
629
623
  });
630
624
  });
631
625
  });
@@ -689,54 +683,87 @@ function getDevice(deviceId) {
689
683
  }
690
684
  function discoverServicesAndCharacteristics(peripheral) {
691
685
  return index.__awaiter(this, void 0, void 0, function* () {
692
- return new Promise((resolve, reject) => {
693
- peripheral.discoverServices(ONEKEY_SERVICE_UUIDS, (error, services) => {
694
- if (error) {
695
- logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Service discovery failed:', error);
696
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound, error.message));
697
- return;
698
- }
699
- if (!services || services.length === 0) {
700
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound, 'No OneKey services found'));
701
- return;
702
- }
703
- const service = services[0];
704
- logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Found service:', service.uuid);
705
- service.discoverCharacteristics([hdShared.ONEKEY_WRITE_CHARACTERISTIC_UUID, hdShared.ONEKEY_NOTIFY_CHARACTERISTIC_UUID], (error, characteristics) => {
686
+ let timeoutId;
687
+ let onDisconnect;
688
+ const cleanup = () => {
689
+ if (timeoutId)
690
+ clearTimeout(timeoutId);
691
+ if (onDisconnect)
692
+ peripheral.removeListener('disconnect', onDisconnect);
693
+ };
694
+ const timeoutPromise = new Promise((_, reject) => {
695
+ timeoutId = setTimeout(() => {
696
+ logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Service discovery timeout');
697
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound, 'Service discovery timeout'));
698
+ }, SERVICE_DISCOVERY_TIMEOUT);
699
+ });
700
+ const disconnectPromise = new Promise((_, reject) => {
701
+ onDisconnect = () => {
702
+ logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Device disconnected during service discovery');
703
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound, 'Device disconnected during service discovery'));
704
+ };
705
+ peripheral.once('disconnect', onDisconnect);
706
+ });
707
+ const discoveryPromise = (() => index.__awaiter(this, void 0, void 0, function* () {
708
+ const services = yield new Promise((resolve, reject) => {
709
+ peripheral.discoverServices(ONEKEY_SERVICE_UUIDS, (error, svc) => {
710
+ if (error) {
711
+ logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Service discovery failed:', error);
712
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound, error.message));
713
+ }
714
+ else {
715
+ resolve(svc);
716
+ }
717
+ });
718
+ });
719
+ if (!services || services.length === 0) {
720
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound, 'No OneKey services found');
721
+ }
722
+ const service = services[0];
723
+ logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Found service:', service.uuid);
724
+ const characteristics = yield new Promise((resolve, reject) => {
725
+ service.discoverCharacteristics([hdShared.ONEKEY_WRITE_CHARACTERISTIC_UUID, hdShared.ONEKEY_NOTIFY_CHARACTERISTIC_UUID], (error, chars) => {
706
726
  if (error) {
707
727
  logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Characteristic discovery failed:', error);
708
728
  reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleCharacteristicNotFound, error.message));
709
- return;
710
729
  }
711
- logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Discovered characteristics:', {
712
- count: (characteristics === null || characteristics === void 0 ? void 0 : characteristics.length) || 0,
713
- uuids: (characteristics === null || characteristics === void 0 ? void 0 : characteristics.map(c => c.uuid)) || [],
714
- });
715
- let writeCharacteristic = null;
716
- let notifyCharacteristic = null;
717
- for (const characteristic of characteristics) {
718
- const uuid = characteristic.uuid.replace(/-/g, '').toLowerCase();
719
- const uuidKey = uuid.length >= 8 ? uuid.substring(4, 8) : uuid;
720
- if (uuidKey === NORMALIZED_WRITE_UUID) {
721
- writeCharacteristic = characteristic;
722
- }
723
- else if (uuidKey === NORMALIZED_NOTIFY_UUID) {
724
- notifyCharacteristic = characteristic;
725
- }
726
- }
727
- logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Characteristic discovery result:', {
728
- writeFound: !!writeCharacteristic,
729
- notifyFound: !!notifyCharacteristic,
730
- });
731
- if (!writeCharacteristic || !notifyCharacteristic) {
732
- logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Missing characteristics - write:', !!writeCharacteristic, 'notify:', !!notifyCharacteristic);
733
- reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleCharacteristicNotFound, 'Required characteristics not found'));
734
- return;
730
+ else {
731
+ resolve(chars);
735
732
  }
736
- resolve({ write: writeCharacteristic, notify: notifyCharacteristic });
737
733
  });
738
734
  });
739
- });
735
+ logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Discovered characteristics:', {
736
+ count: (characteristics === null || characteristics === void 0 ? void 0 : characteristics.length) || 0,
737
+ uuids: (characteristics === null || characteristics === void 0 ? void 0 : characteristics.map(c => c.uuid)) || [],
738
+ });
739
+ let writeCharacteristic = null;
740
+ let notifyCharacteristic = null;
741
+ for (const characteristic of characteristics) {
742
+ const uuid = characteristic.uuid.replace(/-/g, '').toLowerCase();
743
+ const uuidKey = uuid.length >= 8 ? uuid.substring(4, 8) : uuid;
744
+ if (uuidKey === NORMALIZED_WRITE_UUID) {
745
+ writeCharacteristic = characteristic;
746
+ }
747
+ else if (uuidKey === NORMALIZED_NOTIFY_UUID) {
748
+ notifyCharacteristic = characteristic;
749
+ }
750
+ }
751
+ logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Characteristic discovery result:', {
752
+ writeFound: !!writeCharacteristic,
753
+ notifyFound: !!notifyCharacteristic,
754
+ });
755
+ if (!writeCharacteristic || !notifyCharacteristic) {
756
+ logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Missing characteristics - write:', !!writeCharacteristic, 'notify:', !!notifyCharacteristic);
757
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleCharacteristicNotFound, 'Required characteristics not found');
758
+ }
759
+ return { write: writeCharacteristic, notify: notifyCharacteristic };
760
+ }))();
761
+ try {
762
+ return yield Promise.race([discoveryPromise, timeoutPromise, disconnectPromise]);
763
+ }
764
+ finally {
765
+ cleanup();
766
+ }
740
767
  });
741
768
  }
742
769
  function forceReconnectPeripheral(peripheral, deviceId) {
@@ -749,20 +776,19 @@ function forceReconnectPeripheral(peripheral, deviceId) {
749
776
  reason: 'force-reconnect',
750
777
  });
751
778
  if (peripheral.state === 'connected') {
779
+ peripheral.removeAllListeners('disconnect');
752
780
  yield new Promise(resolve => {
753
781
  peripheral.disconnect(() => {
754
782
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Force disconnect completed');
755
783
  resolve();
756
784
  });
757
785
  });
758
- yield hdShared.wait(1000);
759
786
  }
760
- peripheral.removeAllListeners();
761
787
  yield new Promise((resolve, reject) => {
762
788
  peripheral.connect((error) => {
763
789
  if (error) {
764
790
  logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Force reconnect failed:', error);
765
- reject(new Error(`Force reconnect failed: ${error.message}`));
791
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, error.message));
766
792
  }
767
793
  else {
768
794
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Force reconnect successful');
@@ -774,49 +800,34 @@ function forceReconnectPeripheral(peripheral, deviceId) {
774
800
  yield hdShared.wait(500);
775
801
  });
776
802
  }
777
- function connectAndDiscoverWithFreshScan(deviceId) {
803
+ function freshScanAndDiscover(deviceId, webContents) {
778
804
  return index.__awaiter(this, void 0, void 0, function* () {
779
- logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Attempting connection with fresh peripheral scan as fallback');
780
- const currentPeripheral = discoveredDevices.get(deviceId);
781
- if (currentPeripheral) {
782
- try {
783
- return yield discoverServicesAndCharacteristicsWithRetry(currentPeripheral, deviceId);
784
- }
785
- catch (error) {
786
- logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Service discovery failed with existing peripheral, attempting fresh scan...');
787
- }
788
- }
789
805
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Performing fresh scan to get new peripheral object for device:', deviceId);
790
- try {
791
- const freshPeripheral = yield performTargetedScan(deviceId);
792
- if (!freshPeripheral) {
793
- discoveredDevices.delete(deviceId);
794
- subscriptionOperations.set(deviceId, 'idle');
795
- logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Deep cleanup before throwing DeviceNotFound (fresh scan null)', {
796
- deviceId,
797
- });
798
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceNotFound, `Device ${deviceId} not found in fresh scan`);
799
- }
800
- discoveredDevices.set(deviceId, freshPeripheral);
801
- yield new Promise((resolve, reject) => {
802
- freshPeripheral.connect((error) => {
803
- if (error) {
804
- reject(new Error(`Fresh peripheral connection failed: ${error.message}`));
805
- }
806
- else {
807
- connectedDevices.set(deviceId, freshPeripheral);
808
- resolve();
809
- }
810
- });
806
+ const freshPeripheral = yield performTargetedScan(deviceId);
807
+ if (!freshPeripheral) {
808
+ discoveredDevices.delete(deviceId);
809
+ subscriptionOperations.set(deviceId, 'idle');
810
+ logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Deep cleanup before throwing DeviceNotFound (fresh scan null)', {
811
+ deviceId,
811
812
  });
812
- logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Attempting service discovery with fresh peripheral');
813
- yield hdShared.wait(1000);
814
- return yield discoverServicesAndCharacteristics(freshPeripheral);
815
- }
816
- catch (error) {
817
- logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Fresh scan and connection failed:', error);
818
- throw error;
813
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceNotFound, `Device ${deviceId} not found in fresh scan`);
819
814
  }
815
+ discoveredDevices.set(deviceId, freshPeripheral);
816
+ yield new Promise((resolve, reject) => {
817
+ freshPeripheral.connect((error) => {
818
+ if (error) {
819
+ reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, `Fresh peripheral connection failed: ${error.message}`));
820
+ }
821
+ else {
822
+ connectedDevices.set(deviceId, freshPeripheral);
823
+ resolve();
824
+ }
825
+ });
826
+ });
827
+ setupDisconnectListener(freshPeripheral, deviceId, webContents);
828
+ yield hdShared.wait(500);
829
+ logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Attempting service discovery with fresh peripheral');
830
+ return discoverServicesAndCharacteristics(freshPeripheral);
820
831
  });
821
832
  }
822
833
  function discoverServicesAndCharacteristicsWithRetry(peripheral, deviceId) {
@@ -829,21 +840,11 @@ function discoverServicesAndCharacteristicsWithRetry(peripheral, deviceId) {
829
840
  maxRetries: 5,
830
841
  targetUUIDs: ONEKEY_SERVICE_UUIDS,
831
842
  });
832
- if (attemptNumber === 3) {
833
- logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Attempting force reconnect to clear connection state...');
834
- try {
835
- yield forceReconnectPeripheral(peripheral, deviceId);
836
- }
837
- catch (error) {
838
- logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Force reconnect failed:', error);
839
- throw error;
840
- }
841
- }
842
843
  if (attemptNumber > 1) {
843
844
  logger === null || logger === void 0 ? void 0 : logger.info(`[NobleBLE] Service discovery retry attempt ${attemptNumber}/5`);
844
845
  }
845
846
  if (peripheral.state !== 'connected') {
846
- throw new Error(`Device not connected: ${peripheral.state}`);
847
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, `Device not connected: ${peripheral.state}`);
847
848
  }
848
849
  try {
849
850
  return yield discoverServicesAndCharacteristics(peripheral);
@@ -870,6 +871,19 @@ function discoverServicesAndCharacteristicsWithRetry(peripheral, deviceId) {
870
871
  });
871
872
  });
872
873
  }
874
+ function setupConnectionAndDiscoverServices(peripheral, deviceId, webContents) {
875
+ return index.__awaiter(this, void 0, void 0, function* () {
876
+ yield forceReconnectPeripheral(peripheral, deviceId);
877
+ setupDisconnectListener(peripheral, deviceId, webContents);
878
+ try {
879
+ return yield discoverServicesAndCharacteristicsWithRetry(peripheral, deviceId);
880
+ }
881
+ catch (error) {
882
+ logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Service discovery failed, attempting fresh scan...', error);
883
+ return freshScanAndDiscover(deviceId, webContents);
884
+ }
885
+ });
886
+ }
873
887
  function connectDevice(deviceId, webContents) {
874
888
  return index.__awaiter(this, void 0, void 0, function* () {
875
889
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Connect device request:', {
@@ -933,17 +947,10 @@ function connectDevice(deviceId, webContents) {
933
947
  devicePacketStates.delete(deviceId);
934
948
  subscribedDevices.delete(deviceId);
935
949
  }
936
- yield hdShared.wait(300);
937
- try {
938
- const characteristics = yield connectAndDiscoverWithFreshScan(deviceId);
939
- deviceCharacteristics.set(deviceId, characteristics);
940
- logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Device ready for communication:', deviceId);
941
- return;
942
- }
943
- catch (error) {
944
- logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Service/characteristic discovery failed after all attempts:', error);
945
- throw error;
946
- }
950
+ const characteristics = yield setupConnectionAndDiscoverServices(peripheral, deviceId, webContents);
951
+ deviceCharacteristics.set(deviceId, characteristics);
952
+ logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Device ready for communication:', deviceId);
953
+ return;
947
954
  }
948
955
  return new Promise((resolve, reject) => {
949
956
  const timeout = setTimeout(() => {
@@ -959,17 +966,17 @@ function connectDevice(deviceId, webContents) {
959
966
  }
960
967
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Connected to device:', deviceId);
961
968
  connectedDevices.set(deviceId, connectedPeripheral);
962
- setupDisconnectListener(connectedPeripheral, deviceId, webContents);
963
969
  try {
964
- const characteristics = yield connectAndDiscoverWithFreshScan(deviceId);
970
+ const characteristics = yield setupConnectionAndDiscoverServices(connectedPeripheral, deviceId, webContents);
965
971
  deviceCharacteristics.set(deviceId, characteristics);
966
972
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Device ready for communication:', deviceId);
967
973
  resolve();
968
974
  }
969
- catch (discoveryError) {
970
- logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Service/characteristic discovery failed after all attempts:', discoveryError);
971
- connectedPeripheral.disconnect();
972
- reject(discoveryError);
975
+ catch (setupError) {
976
+ logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Connection setup failed:', setupError);
977
+ connectedPeripheral.disconnect(() => {
978
+ reject(setupError);
979
+ });
973
980
  }
974
981
  }));
975
982
  });
@@ -1114,9 +1121,13 @@ function subscribeNotifications(deviceId, callback) {
1114
1121
  });
1115
1122
  });
1116
1123
  }
1117
- yield rebuildAppSubscription(deviceId, notifyCharacteristic);
1118
- subscribedDevices.set(deviceId, true);
1119
- subscriptionOperations.set(deviceId, 'idle');
1124
+ try {
1125
+ yield rebuildAppSubscription(deviceId, notifyCharacteristic);
1126
+ subscribedDevices.set(deviceId, true);
1127
+ }
1128
+ finally {
1129
+ subscriptionOperations.set(deviceId, 'idle');
1130
+ }
1120
1131
  });
1121
1132
  }
1122
1133
  function setupNobleBleHandlers(webContents) {
@@ -1 +1 @@
1
- {"version":3,"file":"noble-ble-handler.d.ts","sourceRoot":"","sources":["../src/noble-ble-handler.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EAAsB,WAAW,EAAE,MAAM,UAAU,CAAC;AA0+ChE,wBAAgB,qBAAqB,CAAC,WAAW,EAAE,WAAW,GAAG,IAAI,CAsKpE"}
1
+ {"version":3,"file":"noble-ble-handler.d.ts","sourceRoot":"","sources":["../src/noble-ble-handler.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EAAsB,WAAW,EAAE,MAAM,UAAU,CAAC;AAshDhE,wBAAgB,qBAAqB,CAAC,WAAW,EAAE,WAAW,GAAG,IAAI,CAsKpE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/hd-transport-electron",
3
- "version": "1.1.23",
3
+ "version": "1.1.24-alpha.1",
4
4
  "author": "OneKey",
5
5
  "homepage": "https://github.com/OneKeyHQ/hardware-js-sdk#readme",
6
6
  "license": "MIT",
@@ -25,10 +25,10 @@
25
25
  "electron-log": ">=4.0.0"
26
26
  },
27
27
  "dependencies": {
28
- "@onekeyfe/hd-core": "1.1.23",
29
- "@onekeyfe/hd-shared": "1.1.23",
30
- "@onekeyfe/hd-transport": "1.1.23",
31
- "@stoprocent/noble": "2.3.4",
28
+ "@onekeyfe/hd-core": "1.1.24-alpha.1",
29
+ "@onekeyfe/hd-shared": "1.1.24-alpha.1",
30
+ "@onekeyfe/hd-transport": "1.1.24-alpha.1",
31
+ "@stoprocent/noble": "2.3.16",
32
32
  "p-retry": "^4.6.2"
33
33
  },
34
34
  "devDependencies": {
@@ -36,5 +36,5 @@
36
36
  "electron": "^25.0.0",
37
37
  "typescript": "^5.3.3"
38
38
  },
39
- "gitHead": "eb24e6d66c84185b820a82b880c9707f3f548131"
39
+ "gitHead": "54b5b47750112a573f51ebd264583786d8ee977a"
40
40
  }