@ledgerhq/device-transport-kit-react-native-ble 0.0.0-test-ble-20251112111055 → 0.0.0-test-attest-npmjs-1-20251120163531
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/api/transport/RNBleTransport.js +1 -1
- package/lib/cjs/api/transport/RNBleTransport.js.map +3 -3
- package/lib/cjs/package.json +2 -1
- package/lib/esm/api/transport/RNBleTransport.js +1 -1
- package/lib/esm/api/transport/RNBleTransport.js.map +3 -3
- package/lib/esm/package.json +2 -1
- package/lib/types/api/transport/RNBleTransport.d.ts.map +1 -1
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +7 -6
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var f=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var C=(D,e)=>{for(var n in e)f(D,n,{get:e[n],enumerable:!0})},B=(D,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of w(e))!T.call(D,t)&&t!==n&&f(D,t,{get:()=>e[t],enumerable:!(i=I(e,t))||i.enumerable});return D};var R=D=>B(f({},"__esModule",{value:!0}),D);var N={};C(N,{RNBleTransport:()=>M,rnBleTransportIdentifier:()=>E});module.exports=R(N);var b=require("react-native"),u=require("react-native-ble-plx"),g=require("@ledgerhq/device-management-kit"),s=require("purify-ts"),r=require("rxjs"),p=require("../model/Const"),l=require("../model/Errors"),y=require("../transport/RNBleApduSender");const E="RN_BLE";class M{constructor(e,n,i,t,a,v,c,d=1e3,m=h=>new g.DeviceConnectionStateMachine(h),_=(h,S)=>new y.RNBleApduSender(h,S)){this._deviceModelDataSource=e;this._loggerServiceFactory=n;this._apduSenderFactory=i;this._apduReceiverFactory=t;this._manager=a;this._platform=v;this._permissionsService=c;this._scanThrottleDelayMs=d;this._deviceConnectionStateMachineFactory=m;this._deviceApduSenderFactory=_;this._logger=n("ReactNativeBleTransport"),this._deviceConnectionsById=new Map,this._reconnectionSubscription=s.Maybe.zero();let h=!1;this._manager.onStateChange(S=>{this._logger.debug(`[manager.onStateChange] called with state: ${S}`),this._bleStateSubject.next(S),h=S===u.State.Unknown,h&&(this._logger.debug('[manager.onStateChange] forcing state update from "Unknown"'),this._manager.state().then(o=>{h&&(this._logger.debug(`[manager.onStateChange] forcing state update to: "${o}"`),this._bleStateSubject.next(o))}))},!0)}_logger;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new r.BehaviorSubject(u.State.Unknown);observeBleState(){return this._bleStateSubject.asObservable()}startDiscovering(){return(0,r.from)([])}async stopDiscovering(){await this._stopScanning()}_scannedDevicesSubject=new r.BehaviorSubject([]);_startedScanningSubscriber=void 0;_waitForScanningPrerequisites(){return(0,r.from)([!0]).pipe((0,r.tap)(()=>{if(!this.isSupported())throw new l.BleNotSupported("BLE not supported");this._logger.debug("[waitForScanningPrerequisites] Prerequisite: isSupported=true")}),(0,r.switchMap)(async()=>this.checkAndRequestPermissions()),(0,r.tap)(e=>{if(this._logger.debug(`[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${e}`),!e)throw new l.BlePermissionsNotGranted("Permissions not granted")}),(0,r.switchMap)(()=>this.observeBleState()),(0,r.first)(e=>{const n=e===u.State.PoweredOn;if(this._logger.info(`[waitForScanningPrerequisites] Prerequisite: BLE state=${e}, canStartScanning=${n}`),e===u.State.PoweredOff)throw new l.BlePoweredOff;if(e===u.State.Unauthorized)throw new l.BlePermissionsNotGranted('Ble State is "Unauthorized"');if(e===u.State.Unsupported)throw new l.BleNotSupported;return n}))}_startScanning(){if(this._startedScanningSubscriber!=null){this._logger.info("[startScanning] !! startScanning already started");return}this._scannedDevicesSubject.next([]),this._logger.info("[startScanning] startScanning"),this._startedScanningSubscriber=(0,r.from)([!0]).pipe((0,r.switchMap)(()=>{const e=new r.BehaviorSubject([]),n=new Map;this._logger.info("[startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(t,a)=>{if(t){this._logger.error("[startScanning] Error in startDeviceScan callback",{data:{error:t,rnDevice:a}}),e.error(t);return}if(!a){this._logger.warn("[startScanning] Null Device in startDeviceScan callback",{data:{rnDevice:a}}),e.error(new Error("Null device in startDeviceScan callback"));return}n.set(a.id,{device:a,timestamp:Date.now()}),e.next(Array.from(n.values()))}).catch(t=>{e.error(t),this._logger.error("[startScanning] Error while calling startDeviceScan",{data:{error:t}})}),this._logger.debug("[startScanning] after startDeviceScan");const i=setInterval(()=>{e.next(Array.from(n.values()))},1e3);return e.pipe((0,r.finalize)(()=>{this._logger.debug("[startScanning] finalize"),e.complete(),clearInterval(i),this._stopScanning()}))}),(0,r.throttleTime)(this._scanThrottleDelayMs)).subscribe({next:e=>{this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("[startScanning] Error while scanning",{data:{error:e}}),this._scannedDevicesSubject.error(e)}})}async _stopScanning(){this._logger.debug("[stopScanning] stopScanning"),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0,this._scannedDevicesSubject.complete(),this._scannedDevicesSubject=new r.BehaviorSubject([])}listenToAvailableDevices(){return this._waitForScanningPrerequisites().pipe((0,r.tap)(()=>this._startScanning()),(0,r.switchMap)(()=>this._scannedDevicesSubject),(0,r.switchMap)(async e=>{const n=e.filter(({timestamp:c})=>c>Date.now()-p.CONNECTION_LOST_DELAY).sort((c,d)=>(d.device.rssi??-1/0)-(c.device.rssi??-1/0)).map(({device:c})=>this._mapDeviceToTransportDiscoveredDevice(c,c.serviceUUIDs)).filter(c=>!!c),i=s.Either.rights(n),t=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices()).catch(c=>{throw this._logger.error("[listenToAvailableDevices] Error calling manager.connectedDevices",{data:{error:c}}),c}),a=await Promise.all(t.map(async c=>{try{const m=(await c.services()).map(_=>_.uuid);return this._mapDeviceToTransportDiscoveredDevice(c,m)}catch(d){return this._logger.error("[listenToAvailableDevices] Error in mapping device to transport discovered device",{data:{e:d}}),(0,s.Left)(new l.NoDeviceModelFoundError(`Error in mapping device to transport discovered device: ${d}`))}})),v=s.Either.rights(a);return this._logger.debug("[listenToAvailableDevices]",{data:{rawConnectedDevices:t.map(c=>c.name),connectedDevices:v.map(c=>c.name),scannedDevices:i.map(c=>c.name)}}),[...v,...i]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const n of e||[]){const i=this._deviceModelDataSource.getBluetoothServicesInfos()[n];if(i)return(0,s.Right)(i)}return(0,s.Left)(new l.NoDeviceModelFoundError(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(i=>i.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,n){const i=this._mapServicesUUIDsToDeviceModel(n);return this._logger.debug("[mapDeviceToTransportDiscoveredDevice] Found device",{data:{localName:e.localName,name:e.name}}),i.map(t=>({id:e.id,name:e.localName||e.name||"",deviceModel:t,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){this._logger.debug("[connect] Called",{data:{deviceId:e.deviceId}});const n=this._deviceConnectionsById.get(e.deviceId);if(n){this._logger.debug("[connect] Existing device connection found",{data:{deviceId:e.deviceId}});const i=n.getDependencies(),t=i.internalDevice.bleDeviceInfos.deviceModel,a=i.device.localName||i.device.name||void 0;return this._logger.info("[connect] existing device name",{data:{deviceName:a,localName:i.device.localName,name:i.device.name}}),(0,s.Right)(new g.TransportConnectedDevice({id:e.deviceId,deviceModel:t,type:"BLE",sendApdu:(...v)=>n.sendApdu(...v),transport:this.identifier,name:a}))}return this._logger.debug("[connect] No existing device connection found, establishing one",{data:{deviceId:e.deviceId}}),await this._stopScanning(),await this._safeCancel(e.deviceId),(0,s.EitherAsync)(async({throwE:i})=>{let t,a=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:p.DEFAULT_MTU}),t=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),a=(await t.services()).map(o=>o.uuid)}catch(o){return o instanceof u.BleError&&o.iosErrorCode===14?i(new l.PeerRemovedPairingError(o)):o instanceof u.BleError&&o.errorCode===u.BleErrorCode.OperationCancelled&&b.Platform.OS==="android"?i(new l.PeerRemovedPairingError(o)):i(new g.OpeningConnectionError(o))}const v=this._listenToDeviceDisconnected(e.deviceId),c=this._mapServicesUUIDsToBluetoothDeviceInfo(a).caseOf({Right:o=>o,Left:o=>i(new g.OpeningConnectionError(o))}),d=c.deviceModel,m={id:t.id,bleDeviceInfos:c},_=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:t,internalDevice:m,manager:this._manager}},this._loggerServiceFactory),h=b.Platform.OS==="ios"?p.BLE_DISCONNECT_TIMEOUT_IOS:p.BLE_DISCONNECT_TIMEOUT_ANDROID,S=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:_,timeoutDuration:h,tryToReconnect:()=>this.tryToReconnect(e.deviceId),onTerminated:async()=>{this._logger.debug("[onTerminated]",{data:{deviceId:e.deviceId}});try{await this._safeCancel(e.deviceId)}catch(o){this._logger.error("[onTerminated] Error in termination of device connection",{data:{e:o}})}finally{this._deviceConnectionsById.delete(e.deviceId),this._reconnectionSubscription.ifJust(o=>{o.unsubscribe(),this._reconnectionSubscription=s.Maybe.zero()}),this._logger.debug("[onTerminated] signaling disconnection",{data:{deviceId:e.deviceId}}),e.onDisconnect(e.deviceId)}}});return await _.setupConnection().catch(o=>{throw this._safeCancel(e.deviceId),v.remove(),o}),this._deviceConnectionsById.set(e.deviceId,S),this._logger.info("[connect] new device name",{data:{localName:t.localName,name:t.name}}),new g.TransportConnectedDevice({id:t.id,deviceModel:d,type:"BLE",sendApdu:(...o)=>S.sendApdu(...o),transport:this.identifier,name:t.localName||t.name||void 0})}).run()}async disconnect(e){const n=e.connectedDevice.id,i=this._deviceConnectionsById.get(n);if(!i)throw new g.UnknownDeviceError(`No connected device found with id ${n}`);return i.closeConnection(),Promise.resolve((0,s.Right)(void 0))}isSupported(){return["android","ios"].includes(this._platform.OS)}getIdentifier(){return this.identifier}async checkAndRequestPermissions(){return this._logger.debug("[checkAndRequestPermissions] Called"),await this._permissionsService.checkRequiredPermissions()?!0:await this._permissionsService.requestRequiredPermissions()}_handleDeviceDisconnected(e,n){if(this._logger.debug("[_handleDeviceDisconnected]",{data:{error:e,device:n}}),!n){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!n?.id||!this._deviceConnectionsById.has(n?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:n}});return}const i=n.id;s.Maybe.fromNullable(this._deviceConnectionsById.get(i)).map(t=>t.eventDeviceDisconnected())}_listenToDeviceDisconnected(e){const n=this._manager.onDeviceDisconnected(e,(i,t)=>{this._handleDeviceDisconnected(i,t),n.remove()});return n}async tryToReconnect(e){this._logger.debug("[tryToReconnect] Called",{data:{deviceId:e}});let n=0;await this._stopScanning(),await this._safeCancel(e);const i=(0,r.defer)(async()=>{let t=null;n++;try{this._logger.debug(`[tryToReconnect](try=${n}) Reconnecting to device`,{data:{id:e}});const a=await this._manager.connectToDevice(e,{requestMTU:p.DEFAULT_MTU,timeout:2e3});this._logger.debug(`[tryToReconnect](try=${n}) Established connection to device`,{data:{id:e}});const v=await a.discoverAllServicesAndCharacteristics();return this._logger.debug(`[tryToReconnect](try=${n}) Discovered all services and characteristics`,{data:{usableReconnectedDevice:v}}),t=this._listenToDeviceDisconnected(e),await this._handleDeviceReconnected(v),v}catch(a){throw this._logger.warn(`[tryToReconnect](try=${n}) Reconnecting to device failed`,{data:{e:a}}),t?.remove(),await this._stopScanning(),await this._safeCancel(e),a}}).pipe((0,r.retry)(5));this._reconnectionSubscription=s.Maybe.of(i.subscribe({next:t=>this._logger.debug(`[tryToReconnect](try=${n}) Fully reconnected to device (id=${t.id})`),complete:()=>{this._logger.debug("[tryToReconnect] Completed"),this._reconnectionSubscription=s.Maybe.zero()},error:t=>{this._logger.error("[tryToReconnect] All reconnection attempts failed",{data:{e:t}}),this._deviceConnectionsById.get(e)?.closeConnection(),this._reconnectionSubscription=s.Maybe.zero()}}))}async _handleDeviceReconnected(e){const n=s.Maybe.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new l.DeviceConnectionNotFound);return(0,s.EitherAsync)(async({liftEither:i,throwE:t})=>{const a=await i(n),v=(await e.services()).map(d=>d.uuid),c=this._mapServicesUUIDsToBluetoothDeviceInfo(v).caseOf({Right:d=>({id:e.id,bleDeviceInfos:d}),Left:d=>(this._logger.error("[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info",{data:{error:d}}),t(d))});a.setDependencies({device:e,manager:this._manager,internalDevice:c}),await a.setupConnection().catch(d=>{throw this._safeCancel(e.id),d}),a.eventDeviceConnected()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const n=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const i of n)if(i.id===e)try{await this._manager.cancelDeviceConnection(e)}catch(t){this._logger.error("[safeCancel] Error in cancelling device connection",{data:{e:t}})}}}}0&&(module.exports={RNBleTransport,rnBleTransportIdentifier});
|
|
1
|
+
"use strict";var b=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var T=(D,e)=>{for(var n in e)b(D,n,{get:e[n],enumerable:!0})},B=(D,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of w(e))!C.call(D,t)&&t!==n&&b(D,t,{get:()=>e[t],enumerable:!(i=I(e,t))||i.enumerable});return D};var R=D=>B(b({},"__esModule",{value:!0}),D);var N={};T(N,{RNBleTransport:()=>E,rnBleTransportIdentifier:()=>M});module.exports=R(N);var m=require("react-native"),u=require("react-native-ble-plx"),g=require("@ledgerhq/device-management-kit"),a=require("purify-ts"),r=require("rxjs"),p=require("../model/Const"),l=require("../model/Errors"),y=require("../transport/RNBleApduSender");const M="RN_BLE";class E{constructor(e,n,i,t,s,v,c,d=1e3,f=h=>new g.DeviceConnectionStateMachine(h),_=(h,S)=>new y.RNBleApduSender(h,S)){this._deviceModelDataSource=e;this._loggerServiceFactory=n;this._apduSenderFactory=i;this._apduReceiverFactory=t;this._manager=s;this._platform=v;this._permissionsService=c;this._scanThrottleDelayMs=d;this._deviceConnectionStateMachineFactory=f;this._deviceApduSenderFactory=_;this._logger=n("ReactNativeBleTransport"),this._deviceConnectionsById=new Map,this._reconnectionSubscription=a.Maybe.zero();let h=!1;this._manager.onStateChange(S=>{this._logger.debug(`[manager.onStateChange] called with state: ${S}`),this._bleStateSubject.next(S),h=S===u.State.Unknown,h&&(this._logger.debug('[manager.onStateChange] forcing state update from "Unknown"'),this._manager.state().then(o=>{h&&(this._logger.debug(`[manager.onStateChange] forcing state update to: "${o}"`),this._bleStateSubject.next(o))}))},!0)}_logger;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new r.BehaviorSubject(u.State.Unknown);observeBleState(){return this._bleStateSubject.asObservable()}startDiscovering(){return(0,r.from)([])}async stopDiscovering(){await this._stopScanning()}_scannedDevicesSubject=new r.BehaviorSubject([]);_startedScanningSubscriber=void 0;_waitForScanningPrerequisites(){return(0,r.from)([!0]).pipe((0,r.tap)(()=>{if(!this.isSupported())throw new l.BleNotSupported("BLE not supported");this._logger.debug("[waitForScanningPrerequisites] Prerequisite: isSupported=true")}),(0,r.switchMap)(async()=>this.checkAndRequestPermissions()),(0,r.tap)(e=>{if(this._logger.debug(`[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${e}`),!e)throw new l.BlePermissionsNotGranted("Permissions not granted")}),(0,r.switchMap)(()=>this.observeBleState()),(0,r.first)(e=>{const n=e===u.State.PoweredOn;if(this._logger.info(`[waitForScanningPrerequisites] Prerequisite: BLE state=${e}, canStartScanning=${n}`),e===u.State.PoweredOff)throw new l.BlePoweredOff;if(e===u.State.Unauthorized)throw new l.BlePermissionsNotGranted('Ble State is "Unauthorized"');if(e===u.State.Unsupported)throw new l.BleNotSupported;return n}))}_startScanning(){if(this._startedScanningSubscriber!=null){this._logger.info("[startScanning] !! startScanning already started");return}this._scannedDevicesSubject.next([]),this._logger.info("[startScanning] startScanning"),this._startedScanningSubscriber=(0,r.from)([!0]).pipe((0,r.switchMap)(()=>{const e=new r.BehaviorSubject([]),n=new Map;this._logger.info("[startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(t,s)=>{if(t){this._logger.error("[startScanning] Error in startDeviceScan callback",{data:{error:t,rnDevice:s}}),e.error(t);return}if(!s){this._logger.warn("[startScanning] Null Device in startDeviceScan callback",{data:{rnDevice:s}}),e.error(new Error("Null device in startDeviceScan callback"));return}n.set(s.id,{device:s,timestamp:Date.now()}),e.next(Array.from(n.values()))}).catch(t=>{e.error(t),this._logger.error("[startScanning] Error while calling startDeviceScan",{data:{error:t}})}),this._logger.debug("[startScanning] after startDeviceScan");const i=setInterval(()=>{e.next(Array.from(n.values()))},1e3);return e.pipe((0,r.finalize)(()=>{this._logger.debug("[startScanning] finalize"),e.complete(),clearInterval(i),this._stopScanning()}))}),(0,r.throttleTime)(this._scanThrottleDelayMs)).subscribe({next:e=>{this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("[startScanning] Error while scanning",{data:{error:e}}),this._scannedDevicesSubject.error(e)}})}async _stopScanning(){this._logger.debug("[stopScanning] stopScanning"),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0,this._scannedDevicesSubject.complete(),this._scannedDevicesSubject=new r.BehaviorSubject([])}listenToAvailableDevices(){return this._waitForScanningPrerequisites().pipe((0,r.tap)(()=>this._startScanning()),(0,r.switchMap)(()=>this._scannedDevicesSubject),(0,r.switchMap)(async e=>{const n=e.filter(({timestamp:c})=>c>Date.now()-p.CONNECTION_LOST_DELAY).sort((c,d)=>(d.device.rssi??-1/0)-(c.device.rssi??-1/0)).map(({device:c})=>this._mapDeviceToTransportDiscoveredDevice(c,c.serviceUUIDs)).filter(c=>!!c),i=a.Either.rights(n),t=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices()).catch(c=>{throw this._logger.error("[listenToAvailableDevices] Error calling manager.connectedDevices",{data:{error:c}}),c}),s=await Promise.all(t.map(async c=>{try{const f=(await c.services()).map(_=>_.uuid);return this._mapDeviceToTransportDiscoveredDevice(c,f)}catch(d){return this._logger.error("[listenToAvailableDevices] Error in mapping device to transport discovered device",{data:{e:d}}),(0,a.Left)(new l.NoDeviceModelFoundError(`Error in mapping device to transport discovered device: ${d}`))}})),v=a.Either.rights(s);return this._logger.debug("[listenToAvailableDevices]",{data:{rawConnectedDevices:t.map(c=>c.name),connectedDevices:v.map(c=>c.name),scannedDevices:i.map(c=>c.name)}}),[...v,...i]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const n of e||[]){const i=this._deviceModelDataSource.getBluetoothServicesInfos()[n];if(i)return(0,a.Right)(i)}return(0,a.Left)(new l.NoDeviceModelFoundError(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(i=>i.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,n){return this._mapServicesUUIDsToDeviceModel(n).map(t=>({id:e.id,name:e.localName||e.name||"",deviceModel:t,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){this._logger.debug("[connect] Called",{data:{deviceId:e.deviceId}});const n=this._deviceConnectionsById.get(e.deviceId);if(n){this._logger.debug("[connect] Existing device connection found",{data:{deviceId:e.deviceId}});const i=n.getDependencies(),t=i.internalDevice.bleDeviceInfos.deviceModel,s=i.device.localName||i.device.name||void 0;return(0,a.Right)(new g.TransportConnectedDevice({id:e.deviceId,deviceModel:t,type:"BLE",sendApdu:(...v)=>n.sendApdu(...v),transport:this.identifier,name:s}))}return this._logger.debug("[connect] No existing device connection found, establishing one",{data:{deviceId:e.deviceId}}),await this._stopScanning(),await this._safeCancel(e.deviceId),(0,a.EitherAsync)(async({throwE:i})=>{let t,s=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:p.DEFAULT_MTU}),t=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),s=(await t.services()).map(o=>o.uuid)}catch(o){return o instanceof u.BleError&&o.iosErrorCode===14?i(new l.PeerRemovedPairingError(o)):o instanceof u.BleError&&o.errorCode===u.BleErrorCode.OperationCancelled&&m.Platform.OS==="android"?i(new l.PeerRemovedPairingError(o)):i(new g.OpeningConnectionError(o))}const v=this._listenToDeviceDisconnected(e.deviceId),c=this._mapServicesUUIDsToBluetoothDeviceInfo(s).caseOf({Right:o=>o,Left:o=>i(new g.OpeningConnectionError(o))}),d=c.deviceModel,f={id:t.id,bleDeviceInfos:c},_=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:t,internalDevice:f,manager:this._manager}},this._loggerServiceFactory),h=m.Platform.OS==="ios"?p.BLE_DISCONNECT_TIMEOUT_IOS:p.BLE_DISCONNECT_TIMEOUT_ANDROID,S=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:_,timeoutDuration:h,tryToReconnect:()=>this.tryToReconnect(e.deviceId),onTerminated:async()=>{this._logger.debug("[onTerminated]",{data:{deviceId:e.deviceId}});try{await this._safeCancel(e.deviceId)}catch(o){this._logger.error("[onTerminated] Error in termination of device connection",{data:{e:o}})}finally{this._deviceConnectionsById.delete(e.deviceId),this._reconnectionSubscription.ifJust(o=>{o.unsubscribe(),this._reconnectionSubscription=a.Maybe.zero()}),this._logger.debug("[onTerminated] signaling disconnection",{data:{deviceId:e.deviceId}}),e.onDisconnect(e.deviceId)}}});return await _.setupConnection().catch(o=>{throw this._safeCancel(e.deviceId),v.remove(),o}),this._deviceConnectionsById.set(e.deviceId,S),new g.TransportConnectedDevice({id:t.id,deviceModel:d,type:"BLE",sendApdu:(...o)=>S.sendApdu(...o),transport:this.identifier,name:t.localName||t.name||void 0})}).run()}async disconnect(e){const n=e.connectedDevice.id,i=this._deviceConnectionsById.get(n);if(!i)throw new g.UnknownDeviceError(`No connected device found with id ${n}`);return i.closeConnection(),Promise.resolve((0,a.Right)(void 0))}isSupported(){return["android","ios"].includes(this._platform.OS)}getIdentifier(){return this.identifier}async checkAndRequestPermissions(){return this._logger.debug("[checkAndRequestPermissions] Called"),await this._permissionsService.checkRequiredPermissions()?!0:await this._permissionsService.requestRequiredPermissions()}_handleDeviceDisconnected(e,n){if(this._logger.debug("[_handleDeviceDisconnected]",{data:{error:e,device:n}}),!n){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!n?.id||!this._deviceConnectionsById.has(n?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:n}});return}const i=n.id;a.Maybe.fromNullable(this._deviceConnectionsById.get(i)).map(t=>t.eventDeviceDisconnected())}_listenToDeviceDisconnected(e){const n=this._manager.onDeviceDisconnected(e,(i,t)=>{this._handleDeviceDisconnected(i,t),n.remove()});return n}async tryToReconnect(e){this._logger.debug("[tryToReconnect] Called",{data:{deviceId:e}});let n=0;await this._stopScanning(),await this._safeCancel(e);const i=(0,r.defer)(async()=>{let t=null;n++;try{this._logger.debug(`[tryToReconnect](try=${n}) Reconnecting to device`,{data:{id:e}});const s=await this._manager.connectToDevice(e,{requestMTU:p.DEFAULT_MTU,timeout:2e3});this._logger.debug(`[tryToReconnect](try=${n}) Established connection to device`,{data:{id:e}});const v=await s.discoverAllServicesAndCharacteristics();return this._logger.debug(`[tryToReconnect](try=${n}) Discovered all services and characteristics`,{data:{usableReconnectedDevice:v}}),t=this._listenToDeviceDisconnected(e),await this._handleDeviceReconnected(v),v}catch(s){throw this._logger.warn(`[tryToReconnect](try=${n}) Reconnecting to device failed`,{data:{e:s}}),t?.remove(),await this._stopScanning(),await this._safeCancel(e),s}}).pipe((0,r.retry)(5));this._reconnectionSubscription=a.Maybe.of(i.subscribe({next:t=>this._logger.debug(`[tryToReconnect](try=${n}) Fully reconnected to device (id=${t.id})`),complete:()=>{this._logger.debug("[tryToReconnect] Completed"),this._reconnectionSubscription=a.Maybe.zero()},error:t=>{this._logger.error("[tryToReconnect] All reconnection attempts failed",{data:{e:t}}),this._deviceConnectionsById.get(e)?.closeConnection(),this._reconnectionSubscription=a.Maybe.zero()}}))}async _handleDeviceReconnected(e){const n=a.Maybe.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new l.DeviceConnectionNotFound);return(0,a.EitherAsync)(async({liftEither:i,throwE:t})=>{const s=await i(n),v=(await e.services()).map(d=>d.uuid),c=this._mapServicesUUIDsToBluetoothDeviceInfo(v).caseOf({Right:d=>({id:e.id,bleDeviceInfos:d}),Left:d=>(this._logger.error("[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info",{data:{error:d}}),t(d))});s.setDependencies({device:e,manager:this._manager,internalDevice:c}),await s.setupConnection().catch(d=>{throw this._safeCancel(e.id),d}),s.eventDeviceConnected()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const n=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const i of n)if(i.id===e)try{await this._manager.cancelDeviceConnection(e)}catch(t){this._logger.error("[safeCancel] Error in cancelling device connection",{data:{e:t}})}}}}0&&(module.exports={RNBleTransport,rnBleTransportIdentifier});
|
|
2
2
|
//# sourceMappingURL=RNBleTransport.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/transport/RNBleTransport.ts"],
|
|
4
|
-
"sourcesContent": ["import { Platform } from \"react-native\";\nimport {\n BleError,\n BleErrorCode,\n type BleManager,\n type Device,\n State,\n type Subscription as BleSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Either, EitherAsync, Left, Maybe, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n defer,\n finalize,\n first,\n from,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n tap,\n throttleTime,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT_ANDROID,\n BLE_DISCONNECT_TIMEOUT_IOS,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n BlePermissionsNotGranted,\n BlePoweredOff,\n DeviceConnectionNotFound,\n NoDeviceModelFoundError,\n PeerRemovedPairingError,\n} from \"@api/model/Errors\";\nimport { type PermissionsService } from \"@api/permissions/PermissionsService\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\ntype InternalScannedDevice = {\n device: Device;\n timestamp: number;\n};\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n // private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private readonly _bleStateSubject: BehaviorSubject<State> =\n new BehaviorSubject<State>(State.Unknown);\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n private readonly _manager: BleManager,\n private readonly _platform: Platform,\n private readonly _permissionsService: PermissionsService,\n private readonly _scanThrottleDelayMs: number = 1000,\n private readonly _deviceConnectionStateMachineFactory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies> = (args) =>\n new DeviceConnectionStateMachine(args),\n private readonly _deviceApduSenderFactory: (\n args: RNBleApduSenderConstructorArgs,\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) => RNBleApduSender = (args, loggerFactory) =>\n new RNBleApduSender(args, loggerFactory),\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._deviceConnectionsById = new Map();\n this._reconnectionSubscription = Maybe.zero();\n // FIXME: we should have a destroy method to unregister the onStateChange listener\n let lastBleStateIsUnknown = false;\n this._manager.onStateChange((state) => {\n this._logger.debug(`[manager.onStateChange] called with state: ${state}`);\n this._bleStateSubject.next(state);\n lastBleStateIsUnknown = state === State.Unknown;\n if (lastBleStateIsUnknown) {\n // There seems to be a bug in the library where the state is not updated after going in an Unknown state...\n this._logger.debug(\n `[manager.onStateChange] forcing state update from \"Unknown\"`,\n );\n this._manager.state().then((s) => {\n if (lastBleStateIsUnknown) {\n this._logger.debug(\n `[manager.onStateChange] forcing state update to: \"${s}\"`,\n );\n this._bleStateSubject.next(s);\n }\n });\n }\n }, true);\n }\n\n /** Exposed for testing purposes */\n observeBleState(): Observable<State> {\n return this._bleStateSubject.asObservable();\n }\n\n /**\n * Not implemented for now as the return signature is not really usable.\n * Use listenToAvailableDevices instead.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return from([]);\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._stopScanning();\n }\n\n private _scannedDevicesSubject: BehaviorSubject<InternalScannedDevice[]> =\n new BehaviorSubject<InternalScannedDevice[]>([]);\n private _startedScanningSubscriber: Subscription | undefined = undefined;\n\n /**\n * Returns an observable that emits a value when the prerequisites for scanning are met.\n * The prerequisites are:\n * - BLE should be supported. If not, it will throw an error.\n * - Permissions should be granted. If not, it request them, if it fails, it will throw an error.\n * - BLE state should be PoweredOn.\n * - If BLE state is undetermined (Unknown or Resetting), it will wait for the state to be updated.\n * - For other states, it will throw an error.\n */\n private _waitForScanningPrerequisites() {\n return from([true]).pipe(\n tap(() => {\n if (!this.isSupported()) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n this._logger.debug(\n \"[waitForScanningPrerequisites] Prerequisite: isSupported=true\",\n );\n }),\n switchMap(async () => this.checkAndRequestPermissions()),\n tap((hasPermissions) => {\n this._logger.debug(\n `[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${hasPermissions}`,\n );\n if (!hasPermissions) {\n throw new BlePermissionsNotGranted(\"Permissions not granted\");\n }\n }),\n switchMap(() => this.observeBleState()),\n first((state) => {\n /**\n * We wait for the BLE state to be PoweredOn, in case the current state is one of those:\n * - Unknown: temporary undetermined state which will quickly be updated\n * - Resetting: temporary undetermined state which will quickly be updated\n */\n const canStartScanning = state === State.PoweredOn;\n this._logger.info(\n `[waitForScanningPrerequisites] Prerequisite: BLE state=${state}, canStartScanning=${canStartScanning}`,\n );\n if (state === State.PoweredOff) {\n throw new BlePoweredOff();\n } else if (state === State.Unauthorized) {\n throw new BlePermissionsNotGranted('Ble State is \"Unauthorized\"');\n } else if (state === State.Unsupported) {\n throw new BleNotSupported();\n }\n return canStartScanning;\n }),\n );\n }\n\n private _startScanning() {\n if (this._startedScanningSubscriber != undefined) {\n this._logger.info(\"[startScanning] !! startScanning already started\");\n return;\n }\n\n //Reset the scanned devices list as new scan will start\n this._scannedDevicesSubject.next([]);\n\n this._logger.info(\"[startScanning] startScanning\");\n\n this._startedScanningSubscriber = from([true])\n .pipe(\n switchMap(() => {\n const subject = new BehaviorSubject<InternalScannedDevice[]>([]);\n const devicesById = new Map<string, InternalScannedDevice>();\n\n this._logger.info(\"[startScanning] startDeviceScan\");\n this._manager\n .startDeviceScan(\n this._deviceModelDataSource.getBluetoothServices(),\n { allowDuplicates: true },\n (error, rnDevice) => {\n if (error) {\n this._logger.error(\n \"[startScanning] Error in startDeviceScan callback\",\n {\n data: { error, rnDevice },\n },\n );\n subject.error(error);\n return;\n }\n if (!rnDevice) {\n this._logger.warn(\n \"[startScanning] Null Device in startDeviceScan callback\",\n {\n data: { rnDevice },\n },\n );\n subject.error(\n new Error(\"Null device in startDeviceScan callback\"),\n );\n return;\n }\n devicesById.set(rnDevice.id, {\n device: rnDevice,\n timestamp: Date.now(),\n });\n subject.next(Array.from(devicesById.values()));\n },\n )\n .catch((e) => {\n subject.error(e);\n this._logger.error(\n \"[startScanning] Error while calling startDeviceScan\",\n {\n data: { error: e },\n },\n );\n });\n\n this._logger.debug(\"[startScanning] after startDeviceScan\");\n\n /**\n * In case there is no update from startDeviceScan, we still emit the\n * list of devices. This is useful for instance if there is only 1 device\n * in the vicinity and it just got turned off. It will not \"advertise\"\n * anymore so startDeviceScan won't trigger.\n */\n const interval = setInterval(() => {\n subject.next(Array.from(devicesById.values()));\n }, 1000);\n\n return subject.pipe(\n finalize(() => {\n this._logger.debug(\"[startScanning] finalize\");\n subject.complete();\n clearInterval(interval);\n this._stopScanning();\n }),\n );\n }),\n throttleTime(this._scanThrottleDelayMs),\n )\n .subscribe({\n next: (devices) => {\n this._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"[startScanning] Error while scanning\", {\n data: { error },\n });\n this._scannedDevicesSubject.error(error);\n },\n });\n }\n\n private async _stopScanning(): Promise<void> {\n this._logger.debug(\"[stopScanning] stopScanning\");\n await this._manager.stopDeviceScan();\n //Stop listening the observable from this._startScanning()\n this._startedScanningSubscriber?.unsubscribe();\n this._startedScanningSubscriber = undefined;\n this._scannedDevicesSubject.complete();\n this._scannedDevicesSubject = new BehaviorSubject<InternalScannedDevice[]>(\n [],\n );\n\n return;\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n return this._waitForScanningPrerequisites().pipe(\n tap(() => this._startScanning()),\n switchMap(() => this._scannedDevicesSubject),\n switchMap(async (internalScannedDevices) => {\n const eitherScannedDevices = internalScannedDevices\n .filter(\n ({ timestamp }) => timestamp > Date.now() - CONNECTION_LOST_DELAY,\n )\n .sort(\n (a, b) =>\n (b.device.rssi ?? -Infinity) - (a.device.rssi ?? -Infinity), // RSSI is a negative value and the higher, the stronger the signal\n )\n .map(({ device }) =>\n this._mapDeviceToTransportDiscoveredDevice(\n device,\n device.serviceUUIDs,\n ),\n )\n .filter((d) => !!d);\n\n const scannedDevices = Either.rights(eitherScannedDevices);\n\n const rawConnectedDevices = await this._manager\n .connectedDevices(this._deviceModelDataSource.getBluetoothServices())\n .catch((e) => {\n this._logger.error(\n \"[listenToAvailableDevices] Error calling manager.connectedDevices\",\n {\n data: { error: e },\n },\n );\n throw e;\n });\n\n const eitherConnectedDevices = await Promise.all(\n rawConnectedDevices.map(async (device) => {\n try {\n const services = await device.services();\n const servicesUUIDs = services.map((s) => s.uuid);\n return this._mapDeviceToTransportDiscoveredDevice(\n device,\n servicesUUIDs,\n );\n } catch (e) {\n this._logger.error(\n \"[listenToAvailableDevices] Error in mapping device to transport discovered device\",\n {\n data: { e },\n },\n );\n return Left(\n new NoDeviceModelFoundError(\n `Error in mapping device to transport discovered device: ${e}`,\n ),\n );\n }\n }),\n );\n\n const connectedDevices = Either.rights(eitherConnectedDevices);\n\n this._logger.debug(\"[listenToAvailableDevices]\", {\n data: {\n rawConnectedDevices: rawConnectedDevices.map((d) => d.name),\n connectedDevices: connectedDevices.map((d) => d.name),\n scannedDevices: scannedDevices.map((d) => d.name),\n },\n });\n\n /** We return both connected and scanned devices, as scanned devices don't include connected devices */\n return [...connectedDevices, ...scannedDevices];\n }),\n );\n }\n\n private _mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, BleDeviceInfos> {\n for (const serviceUUID of servicesUUIDs || []) {\n const bluetoothServiceInfo =\n this._deviceModelDataSource.getBluetoothServicesInfos()[serviceUUID];\n if (bluetoothServiceInfo) return Right(bluetoothServiceInfo);\n }\n\n return Left(\n new NoDeviceModelFoundError(\n `No device model found for [uuids=${servicesUUIDs}]`,\n ),\n );\n }\n\n private _mapServicesUUIDsToDeviceModel(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDeviceModel> {\n const bluetoothServiceInfo =\n this._mapServicesUUIDsToBluetoothDeviceInfo(servicesUUIDs);\n return bluetoothServiceInfo.map((info) => info.deviceModel);\n }\n\n private _mapDeviceToTransportDiscoveredDevice(\n device: Device,\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDiscoveredDevice> {\n const deviceModel = this._mapServicesUUIDsToDeviceModel(servicesUUIDs);\n this._logger.debug(\"[mapDeviceToTransportDiscoveredDevice] Found device\", {\n data: {\n localName: device.localName,\n name: device.name,\n },\n });\n return deviceModel.map((model) => ({\n id: device.id,\n name: device.localName || device.name || \"\",\n deviceModel: model,\n transport: this.identifier,\n rssi: device.rssi || undefined,\n }));\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n this._logger.debug(\"[connect] Called\", {\n data: { deviceId: params.deviceId },\n });\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n this._logger.debug(\"[connect] Existing device connection found\", {\n data: { deviceId: params.deviceId },\n });\n const dependencies = existing.getDependencies();\n const deviceModel =\n dependencies.internalDevice.bleDeviceInfos.deviceModel;\n const deviceName =\n dependencies.device.localName || dependencies.device.name || undefined;\n this._logger.info(\"[connect] existing device name\", {\n data: {\n deviceName,\n localName: dependencies.device.localName,\n name: dependencies.device.name,\n },\n });\n return Right(\n new TransportConnectedDevice({\n id: params.deviceId,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...a) => existing.sendApdu(...a),\n transport: this.identifier,\n name: deviceName,\n }),\n );\n }\n\n this._logger.debug(\n \"[connect] No existing device connection found, establishing one\",\n {\n data: { deviceId: params.deviceId },\n },\n );\n\n await this._stopScanning();\n await this._safeCancel(params.deviceId);\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ throwE }) => {\n let device: Device;\n let servicesUUIDs: string[] = [];\n try {\n await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n device =\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n\n servicesUUIDs = (await device.services()).map((s) => s.uuid);\n } catch (error) {\n if (\n error instanceof BleError &&\n (error.iosErrorCode as number) === 14\n ) {\n /**\n * This happens when the Ledger device reset its pairing, but the\n * iOS system still has that device paired.\n */\n return throwE(new PeerRemovedPairingError(error));\n }\n if (\n error instanceof BleError &&\n error.errorCode === BleErrorCode.OperationCancelled &&\n Platform.OS === \"android\"\n ) {\n return throwE(new PeerRemovedPairingError(error));\n }\n return throwE(new OpeningConnectionError(error));\n }\n\n const disconnectionSubscription = this._listenToDeviceDisconnected(\n params.deviceId,\n );\n\n const bleDeviceInfos = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return info;\n },\n Left: (error) => {\n return throwE(new OpeningConnectionError(error));\n },\n });\n\n const deviceModel = bleDeviceInfos.deviceModel;\n\n const internalDevice: RNBleInternalDevice = {\n id: device.id,\n bleDeviceInfos,\n };\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: { device, internalDevice, manager: this._manager },\n },\n this._loggerServiceFactory,\n );\n\n const reconnectionTimeout =\n Platform.OS === \"ios\"\n ? BLE_DISCONNECT_TIMEOUT_IOS\n : BLE_DISCONNECT_TIMEOUT_ANDROID;\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: reconnectionTimeout,\n tryToReconnect: () => this.tryToReconnect(params.deviceId),\n onTerminated: async () => {\n this._logger.debug(\"[onTerminated]\", {\n data: { deviceId: params.deviceId },\n });\n try {\n await this._safeCancel(params.deviceId);\n } catch (e) {\n this._logger.error(\n \"[onTerminated] Error in termination of device connection\",\n { data: { e } },\n );\n } finally {\n this._deviceConnectionsById.delete(params.deviceId);\n this._reconnectionSubscription.ifJust((sub) => {\n sub.unsubscribe();\n this._reconnectionSubscription = Maybe.zero();\n });\n this._logger.debug(\"[onTerminated] signaling disconnection\", {\n data: { deviceId: params.deviceId },\n });\n params.onDisconnect(params.deviceId);\n }\n },\n });\n\n await deviceApduSender.setupConnection().catch((e) => {\n this._safeCancel(params.deviceId);\n disconnectionSubscription.remove();\n throw e;\n });\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n this._logger.info(\"[connect] new device name\", {\n data: {\n localName: device.localName,\n name: device.name,\n },\n });\n return new TransportConnectedDevice({\n id: device.id,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n name: device.localName || device.name || undefined,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const deviceConnection = this._deviceConnectionsById.get(deviceId);\n if (!deviceConnection) {\n throw new UnknownDeviceError(\n `No connected device found with id ${deviceId}`,\n );\n }\n\n deviceConnection.closeConnection();\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return [\"android\", \"ios\"].includes(this._platform.OS);\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Checks if the necessary permissions are granted and requests them if not.\n */\n async checkAndRequestPermissions(): Promise<boolean> {\n this._logger.debug(\"[checkAndRequestPermissions] Called\");\n\n const checkResult =\n await this._permissionsService.checkRequiredPermissions();\n if (checkResult) return true;\n\n const requestResult =\n await this._permissionsService.requestRequiredPermissions();\n return requestResult;\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n this._logger.debug(\"[_handleDeviceDisconnected]\", {\n data: { error, device },\n });\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (deviceConnection) => deviceConnection.eventDeviceDisconnected(),\n );\n }\n\n private _listenToDeviceDisconnected(deviceId: DeviceId): BleSubscription {\n const disconnectionSubscription = this._manager.onDeviceDisconnected(\n deviceId,\n (error, d) => {\n this._handleDeviceDisconnected(error, d);\n disconnectionSubscription.remove();\n },\n );\n return disconnectionSubscription;\n }\n\n private async tryToReconnect(deviceId: DeviceId) {\n this._logger.debug(\"[tryToReconnect] Called\", {\n data: { deviceId },\n });\n let reconnectionTryCount = 0;\n\n await this._stopScanning();\n await this._safeCancel(deviceId);\n\n const reconnect$ = defer(async () => {\n let disconnectionSubscription: BleSubscription | null = null;\n reconnectionTryCount++;\n try {\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device`,\n {\n data: { id: deviceId },\n },\n );\n const reconnectedDevice = await this._manager.connectToDevice(\n deviceId,\n { requestMTU: DEFAULT_MTU, timeout: 2000 },\n );\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Established connection to device`,\n {\n data: { id: deviceId },\n },\n );\n const usableReconnectedDevice =\n await reconnectedDevice.discoverAllServicesAndCharacteristics();\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Discovered all services and characteristics`,\n { data: { usableReconnectedDevice } },\n );\n disconnectionSubscription = this._listenToDeviceDisconnected(deviceId);\n await this._handleDeviceReconnected(usableReconnectedDevice);\n return usableReconnectedDevice;\n } catch (e) {\n this._logger.warn(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device failed`,\n {\n data: { e },\n },\n );\n disconnectionSubscription?.remove();\n await this._stopScanning();\n await this._safeCancel(deviceId);\n throw e;\n }\n }).pipe(retry(5));\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Fully reconnected to device (id=${d.id})`,\n ),\n complete: () => {\n this._logger.debug(\"[tryToReconnect] Completed\");\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n `[tryToReconnect] All reconnection attempts failed`,\n { data: { e } },\n );\n this._deviceConnectionsById.get(deviceId)?.closeConnection();\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The ddevice object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n return EitherAsync(async ({ liftEither, throwE }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const servicesUUIDs = (await device.services()).map((s) => s.uuid);\n\n const internalDevice = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return {\n id: device.id,\n bleDeviceInfos: info,\n };\n },\n Left: (error) => {\n this._logger.error(\n \"[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info\",\n {\n data: { error },\n },\n );\n\n return throwE(error);\n },\n });\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection().catch((e) => {\n this._safeCancel(device.id);\n throw e;\n });\n\n deviceConnectionStateMachine.eventDeviceConnected();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n const connectedDevices = await this._manager.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\n );\n\n for (const device of connectedDevices) {\n if (device.id === deviceId) {\n try {\n await this._manager.cancelDeviceConnection(deviceId);\n } catch (e) {\n this._logger.error(\n \"[safeCancel] Error in cancelling device connection\",\n {\n data: { e },\n },\n );\n }\n }\n }\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,oBAAAE,EAAA,6BAAAC,IAAA,eAAAC,EAAAJ,GAAA,IAAAK,EAAyB,wBACzBC,EAOO,gCACPC,EAmBO,2CACPC,EAAwD,qBACxDC,EAYO,gBAEPC,EAKO,4BACPC,EAOO,6BAEPC,EAKO,0CAEA,MAAMT,EAA2B,SAOjC,MAAMD,CAAoC,CAY/C,YACmBW,EACAC,EAGAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAA+B,IAC/BC,EAEiDC,GAChE,IAAI,+BAA6BA,CAAI,EACtBC,EAGM,CAACD,EAAME,IAC5B,IAAI,kBAAgBF,EAAME,CAAa,EACzC,CAnBiB,4BAAAX,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EACA,cAAAC,EACA,eAAAC,EACA,yBAAAC,EACA,0BAAAC,EACA,0CAAAC,EAIA,8BAAAE,EAMjB,KAAK,QAAUT,EAAsB,yBAAyB,EAC9D,KAAK,uBAAyB,IAAI,IAClC,KAAK,0BAA4B,QAAM,KAAK,EAE5C,IAAIW,EAAwB,GAC5B,KAAK,SAAS,cAAeC,GAAU,CACrC,KAAK,QAAQ,MAAM,8CAA8CA,CAAK,EAAE,EACxE,KAAK,iBAAiB,KAAKA,CAAK,EAChCD,EAAwBC,IAAU,QAAM,QACpCD,IAEF,KAAK,QAAQ,MACX,6DACF,EACA,KAAK,SAAS,MAAM,E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AE,IAAI,CACT,CAEA,MAAc,YAAYE,EAAoB,CAE5C,GAAI,OAAO,KAAK,SAAS,wBAA2B,WAAY,CAC9D,MAAMlB,EAAmB,MAAM,KAAK,SAAS,iBAC3C,KAAK,uBAAuB,qBAAqB,CACnD,EAEA,UAAWN,KAAUM,EACnB,GAAIN,EAAO,KAAOwB,EAChB,GAAI,CACF,MAAM,KAAK,SAAS,uBAAuBA,CAAQ,CACrD,OAAShC,EAAG,CACV,KAAK,QAAQ,MACX,qDACA,CACE,KAAM,CAAE,EAAAA,CAAE,CACZ,CACF,CACF,CAGN,CACF,CACF",
|
|
6
|
-
"names": ["RNBleTransport_exports", "__export", "RNBleTransport", "rnBleTransportIdentifier", "__toCommonJS", "import_react_native", "import_react_native_ble_plx", "import_device_management_kit", "import_purify_ts", "import_rxjs", "import_Const", "import_Errors", "import_RNBleApduSender", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_manager", "_platform", "_permissionsService", "_scanThrottleDelayMs", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "lastBleStateIsUnknown", "state", "s", "hasPermissions", "canStartScanning", "subject", "devicesById", "error", "rnDevice", "e", "interval", "devices", "internalScannedDevices", "eitherScannedDevices", "timestamp", "a", "b", "device", "d", "scannedDevices", "rawConnectedDevices", "eitherConnectedDevices", "servicesUUIDs", "connectedDevices", "serviceUUID", "bluetoothServiceInfo", "info", "
|
|
4
|
+
"sourcesContent": ["import { Platform } from \"react-native\";\nimport {\n BleError,\n BleErrorCode,\n type BleManager,\n type Device,\n State,\n type Subscription as BleSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Either, EitherAsync, Left, Maybe, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n defer,\n finalize,\n first,\n from,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n tap,\n throttleTime,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT_ANDROID,\n BLE_DISCONNECT_TIMEOUT_IOS,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n BlePermissionsNotGranted,\n BlePoweredOff,\n DeviceConnectionNotFound,\n NoDeviceModelFoundError,\n PeerRemovedPairingError,\n} from \"@api/model/Errors\";\nimport { type PermissionsService } from \"@api/permissions/PermissionsService\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\ntype InternalScannedDevice = {\n device: Device;\n timestamp: number;\n};\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n // private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private readonly _bleStateSubject: BehaviorSubject<State> =\n new BehaviorSubject<State>(State.Unknown);\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n private readonly _manager: BleManager,\n private readonly _platform: Platform,\n private readonly _permissionsService: PermissionsService,\n private readonly _scanThrottleDelayMs: number = 1000,\n private readonly _deviceConnectionStateMachineFactory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies> = (args) =>\n new DeviceConnectionStateMachine(args),\n private readonly _deviceApduSenderFactory: (\n args: RNBleApduSenderConstructorArgs,\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) => RNBleApduSender = (args, loggerFactory) =>\n new RNBleApduSender(args, loggerFactory),\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._deviceConnectionsById = new Map();\n this._reconnectionSubscription = Maybe.zero();\n // FIXME: we should have a destroy method to unregister the onStateChange listener\n let lastBleStateIsUnknown = false;\n this._manager.onStateChange((state) => {\n this._logger.debug(`[manager.onStateChange] called with state: ${state}`);\n this._bleStateSubject.next(state);\n lastBleStateIsUnknown = state === State.Unknown;\n if (lastBleStateIsUnknown) {\n // There seems to be a bug in the library where the state is not updated after going in an Unknown state...\n this._logger.debug(\n `[manager.onStateChange] forcing state update from \"Unknown\"`,\n );\n this._manager.state().then((s) => {\n if (lastBleStateIsUnknown) {\n this._logger.debug(\n `[manager.onStateChange] forcing state update to: \"${s}\"`,\n );\n this._bleStateSubject.next(s);\n }\n });\n }\n }, true);\n }\n\n /** Exposed for testing purposes */\n observeBleState(): Observable<State> {\n return this._bleStateSubject.asObservable();\n }\n\n /**\n * Not implemented for now as the return signature is not really usable.\n * Use listenToAvailableDevices instead.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return from([]);\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._stopScanning();\n }\n\n private _scannedDevicesSubject: BehaviorSubject<InternalScannedDevice[]> =\n new BehaviorSubject<InternalScannedDevice[]>([]);\n private _startedScanningSubscriber: Subscription | undefined = undefined;\n\n /**\n * Returns an observable that emits a value when the prerequisites for scanning are met.\n * The prerequisites are:\n * - BLE should be supported. If not, it will throw an error.\n * - Permissions should be granted. If not, it request them, if it fails, it will throw an error.\n * - BLE state should be PoweredOn.\n * - If BLE state is undetermined (Unknown or Resetting), it will wait for the state to be updated.\n * - For other states, it will throw an error.\n */\n private _waitForScanningPrerequisites() {\n return from([true]).pipe(\n tap(() => {\n if (!this.isSupported()) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n this._logger.debug(\n \"[waitForScanningPrerequisites] Prerequisite: isSupported=true\",\n );\n }),\n switchMap(async () => this.checkAndRequestPermissions()),\n tap((hasPermissions) => {\n this._logger.debug(\n `[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${hasPermissions}`,\n );\n if (!hasPermissions) {\n throw new BlePermissionsNotGranted(\"Permissions not granted\");\n }\n }),\n switchMap(() => this.observeBleState()),\n first((state) => {\n /**\n * We wait for the BLE state to be PoweredOn, in case the current state is one of those:\n * - Unknown: temporary undetermined state which will quickly be updated\n * - Resetting: temporary undetermined state which will quickly be updated\n */\n const canStartScanning = state === State.PoweredOn;\n this._logger.info(\n `[waitForScanningPrerequisites] Prerequisite: BLE state=${state}, canStartScanning=${canStartScanning}`,\n );\n if (state === State.PoweredOff) {\n throw new BlePoweredOff();\n } else if (state === State.Unauthorized) {\n throw new BlePermissionsNotGranted('Ble State is \"Unauthorized\"');\n } else if (state === State.Unsupported) {\n throw new BleNotSupported();\n }\n return canStartScanning;\n }),\n );\n }\n\n private _startScanning() {\n if (this._startedScanningSubscriber != undefined) {\n this._logger.info(\"[startScanning] !! startScanning already started\");\n return;\n }\n\n //Reset the scanned devices list as new scan will start\n this._scannedDevicesSubject.next([]);\n\n this._logger.info(\"[startScanning] startScanning\");\n\n this._startedScanningSubscriber = from([true])\n .pipe(\n switchMap(() => {\n const subject = new BehaviorSubject<InternalScannedDevice[]>([]);\n const devicesById = new Map<string, InternalScannedDevice>();\n\n this._logger.info(\"[startScanning] startDeviceScan\");\n this._manager\n .startDeviceScan(\n this._deviceModelDataSource.getBluetoothServices(),\n { allowDuplicates: true },\n (error, rnDevice) => {\n if (error) {\n this._logger.error(\n \"[startScanning] Error in startDeviceScan callback\",\n {\n data: { error, rnDevice },\n },\n );\n subject.error(error);\n return;\n }\n if (!rnDevice) {\n this._logger.warn(\n \"[startScanning] Null Device in startDeviceScan callback\",\n {\n data: { rnDevice },\n },\n );\n subject.error(\n new Error(\"Null device in startDeviceScan callback\"),\n );\n return;\n }\n devicesById.set(rnDevice.id, {\n device: rnDevice,\n timestamp: Date.now(),\n });\n subject.next(Array.from(devicesById.values()));\n },\n )\n .catch((e) => {\n subject.error(e);\n this._logger.error(\n \"[startScanning] Error while calling startDeviceScan\",\n {\n data: { error: e },\n },\n );\n });\n\n this._logger.debug(\"[startScanning] after startDeviceScan\");\n\n /**\n * In case there is no update from startDeviceScan, we still emit the\n * list of devices. This is useful for instance if there is only 1 device\n * in the vicinity and it just got turned off. It will not \"advertise\"\n * anymore so startDeviceScan won't trigger.\n */\n const interval = setInterval(() => {\n subject.next(Array.from(devicesById.values()));\n }, 1000);\n\n return subject.pipe(\n finalize(() => {\n this._logger.debug(\"[startScanning] finalize\");\n subject.complete();\n clearInterval(interval);\n this._stopScanning();\n }),\n );\n }),\n throttleTime(this._scanThrottleDelayMs),\n )\n .subscribe({\n next: (devices) => {\n this._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"[startScanning] Error while scanning\", {\n data: { error },\n });\n this._scannedDevicesSubject.error(error);\n },\n });\n }\n\n private async _stopScanning(): Promise<void> {\n this._logger.debug(\"[stopScanning] stopScanning\");\n await this._manager.stopDeviceScan();\n //Stop listening the observable from this._startScanning()\n this._startedScanningSubscriber?.unsubscribe();\n this._startedScanningSubscriber = undefined;\n this._scannedDevicesSubject.complete();\n this._scannedDevicesSubject = new BehaviorSubject<InternalScannedDevice[]>(\n [],\n );\n\n return;\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n return this._waitForScanningPrerequisites().pipe(\n tap(() => this._startScanning()),\n switchMap(() => this._scannedDevicesSubject),\n switchMap(async (internalScannedDevices) => {\n const eitherScannedDevices = internalScannedDevices\n .filter(\n ({ timestamp }) => timestamp > Date.now() - CONNECTION_LOST_DELAY,\n )\n .sort(\n (a, b) =>\n (b.device.rssi ?? -Infinity) - (a.device.rssi ?? -Infinity), // RSSI is a negative value and the higher, the stronger the signal\n )\n .map(({ device }) =>\n this._mapDeviceToTransportDiscoveredDevice(\n device,\n device.serviceUUIDs,\n ),\n )\n .filter((d) => !!d);\n\n const scannedDevices = Either.rights(eitherScannedDevices);\n\n const rawConnectedDevices = await this._manager\n .connectedDevices(this._deviceModelDataSource.getBluetoothServices())\n .catch((e) => {\n this._logger.error(\n \"[listenToAvailableDevices] Error calling manager.connectedDevices\",\n {\n data: { error: e },\n },\n );\n throw e;\n });\n\n const eitherConnectedDevices = await Promise.all(\n rawConnectedDevices.map(async (device) => {\n try {\n const services = await device.services();\n const servicesUUIDs = services.map((s) => s.uuid);\n return this._mapDeviceToTransportDiscoveredDevice(\n device,\n servicesUUIDs,\n );\n } catch (e) {\n this._logger.error(\n \"[listenToAvailableDevices] Error in mapping device to transport discovered device\",\n {\n data: { e },\n },\n );\n return Left(\n new NoDeviceModelFoundError(\n `Error in mapping device to transport discovered device: ${e}`,\n ),\n );\n }\n }),\n );\n\n const connectedDevices = Either.rights(eitherConnectedDevices);\n\n this._logger.debug(\"[listenToAvailableDevices]\", {\n data: {\n rawConnectedDevices: rawConnectedDevices.map((d) => d.name),\n connectedDevices: connectedDevices.map((d) => d.name),\n scannedDevices: scannedDevices.map((d) => d.name),\n },\n });\n\n /** We return both connected and scanned devices, as scanned devices don't include connected devices */\n return [...connectedDevices, ...scannedDevices];\n }),\n );\n }\n\n private _mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, BleDeviceInfos> {\n for (const serviceUUID of servicesUUIDs || []) {\n const bluetoothServiceInfo =\n this._deviceModelDataSource.getBluetoothServicesInfos()[serviceUUID];\n if (bluetoothServiceInfo) return Right(bluetoothServiceInfo);\n }\n\n return Left(\n new NoDeviceModelFoundError(\n `No device model found for [uuids=${servicesUUIDs}]`,\n ),\n );\n }\n\n private _mapServicesUUIDsToDeviceModel(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDeviceModel> {\n const bluetoothServiceInfo =\n this._mapServicesUUIDsToBluetoothDeviceInfo(servicesUUIDs);\n return bluetoothServiceInfo.map((info) => info.deviceModel);\n }\n\n private _mapDeviceToTransportDiscoveredDevice(\n device: Device,\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDiscoveredDevice> {\n const deviceModel = this._mapServicesUUIDsToDeviceModel(servicesUUIDs);\n return deviceModel.map((model) => ({\n id: device.id,\n name: device.localName || device.name || \"\",\n deviceModel: model,\n transport: this.identifier,\n rssi: device.rssi || undefined,\n }));\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n this._logger.debug(\"[connect] Called\", {\n data: { deviceId: params.deviceId },\n });\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n this._logger.debug(\"[connect] Existing device connection found\", {\n data: { deviceId: params.deviceId },\n });\n const dependencies = existing.getDependencies();\n const deviceModel =\n dependencies.internalDevice.bleDeviceInfos.deviceModel;\n const deviceName =\n dependencies.device.localName || dependencies.device.name || undefined;\n return Right(\n new TransportConnectedDevice({\n id: params.deviceId,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...a) => existing.sendApdu(...a),\n transport: this.identifier,\n name: deviceName,\n }),\n );\n }\n\n this._logger.debug(\n \"[connect] No existing device connection found, establishing one\",\n {\n data: { deviceId: params.deviceId },\n },\n );\n\n await this._stopScanning();\n await this._safeCancel(params.deviceId);\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ throwE }) => {\n let device: Device;\n let servicesUUIDs: string[] = [];\n try {\n await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n device =\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n\n servicesUUIDs = (await device.services()).map((s) => s.uuid);\n } catch (error) {\n if (\n error instanceof BleError &&\n (error.iosErrorCode as number) === 14\n ) {\n /**\n * This happens when the Ledger device reset its pairing, but the\n * iOS system still has that device paired.\n */\n return throwE(new PeerRemovedPairingError(error));\n }\n if (\n error instanceof BleError &&\n error.errorCode === BleErrorCode.OperationCancelled &&\n Platform.OS === \"android\"\n ) {\n return throwE(new PeerRemovedPairingError(error));\n }\n return throwE(new OpeningConnectionError(error));\n }\n\n const disconnectionSubscription = this._listenToDeviceDisconnected(\n params.deviceId,\n );\n\n const bleDeviceInfos = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return info;\n },\n Left: (error) => {\n return throwE(new OpeningConnectionError(error));\n },\n });\n\n const deviceModel = bleDeviceInfos.deviceModel;\n\n const internalDevice: RNBleInternalDevice = {\n id: device.id,\n bleDeviceInfos,\n };\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: { device, internalDevice, manager: this._manager },\n },\n this._loggerServiceFactory,\n );\n\n const reconnectionTimeout =\n Platform.OS === \"ios\"\n ? BLE_DISCONNECT_TIMEOUT_IOS\n : BLE_DISCONNECT_TIMEOUT_ANDROID;\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: reconnectionTimeout,\n tryToReconnect: () => this.tryToReconnect(params.deviceId),\n onTerminated: async () => {\n this._logger.debug(\"[onTerminated]\", {\n data: { deviceId: params.deviceId },\n });\n try {\n await this._safeCancel(params.deviceId);\n } catch (e) {\n this._logger.error(\n \"[onTerminated] Error in termination of device connection\",\n { data: { e } },\n );\n } finally {\n this._deviceConnectionsById.delete(params.deviceId);\n this._reconnectionSubscription.ifJust((sub) => {\n sub.unsubscribe();\n this._reconnectionSubscription = Maybe.zero();\n });\n this._logger.debug(\"[onTerminated] signaling disconnection\", {\n data: { deviceId: params.deviceId },\n });\n params.onDisconnect(params.deviceId);\n }\n },\n });\n\n await deviceApduSender.setupConnection().catch((e) => {\n this._safeCancel(params.deviceId);\n disconnectionSubscription.remove();\n throw e;\n });\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n\n return new TransportConnectedDevice({\n id: device.id,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n name: device.localName || device.name || undefined,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const deviceConnection = this._deviceConnectionsById.get(deviceId);\n if (!deviceConnection) {\n throw new UnknownDeviceError(\n `No connected device found with id ${deviceId}`,\n );\n }\n\n deviceConnection.closeConnection();\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return [\"android\", \"ios\"].includes(this._platform.OS);\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Checks if the necessary permissions are granted and requests them if not.\n */\n async checkAndRequestPermissions(): Promise<boolean> {\n this._logger.debug(\"[checkAndRequestPermissions] Called\");\n\n const checkResult =\n await this._permissionsService.checkRequiredPermissions();\n if (checkResult) return true;\n\n const requestResult =\n await this._permissionsService.requestRequiredPermissions();\n return requestResult;\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n this._logger.debug(\"[_handleDeviceDisconnected]\", {\n data: { error, device },\n });\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (deviceConnection) => deviceConnection.eventDeviceDisconnected(),\n );\n }\n\n private _listenToDeviceDisconnected(deviceId: DeviceId): BleSubscription {\n const disconnectionSubscription = this._manager.onDeviceDisconnected(\n deviceId,\n (error, d) => {\n this._handleDeviceDisconnected(error, d);\n disconnectionSubscription.remove();\n },\n );\n return disconnectionSubscription;\n }\n\n private async tryToReconnect(deviceId: DeviceId) {\n this._logger.debug(\"[tryToReconnect] Called\", {\n data: { deviceId },\n });\n let reconnectionTryCount = 0;\n\n await this._stopScanning();\n await this._safeCancel(deviceId);\n\n const reconnect$ = defer(async () => {\n let disconnectionSubscription: BleSubscription | null = null;\n reconnectionTryCount++;\n try {\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device`,\n {\n data: { id: deviceId },\n },\n );\n const reconnectedDevice = await this._manager.connectToDevice(\n deviceId,\n { requestMTU: DEFAULT_MTU, timeout: 2000 },\n );\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Established connection to device`,\n {\n data: { id: deviceId },\n },\n );\n const usableReconnectedDevice =\n await reconnectedDevice.discoverAllServicesAndCharacteristics();\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Discovered all services and characteristics`,\n { data: { usableReconnectedDevice } },\n );\n disconnectionSubscription = this._listenToDeviceDisconnected(deviceId);\n await this._handleDeviceReconnected(usableReconnectedDevice);\n return usableReconnectedDevice;\n } catch (e) {\n this._logger.warn(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device failed`,\n {\n data: { e },\n },\n );\n disconnectionSubscription?.remove();\n await this._stopScanning();\n await this._safeCancel(deviceId);\n throw e;\n }\n }).pipe(retry(5));\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Fully reconnected to device (id=${d.id})`,\n ),\n complete: () => {\n this._logger.debug(\"[tryToReconnect] Completed\");\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n `[tryToReconnect] All reconnection attempts failed`,\n { data: { e } },\n );\n this._deviceConnectionsById.get(deviceId)?.closeConnection();\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The ddevice object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n return EitherAsync(async ({ liftEither, throwE }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const servicesUUIDs = (await device.services()).map((s) => s.uuid);\n\n const internalDevice = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return {\n id: device.id,\n bleDeviceInfos: info,\n };\n },\n Left: (error) => {\n this._logger.error(\n \"[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info\",\n {\n data: { error },\n },\n );\n\n return throwE(error);\n },\n });\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection().catch((e) => {\n this._safeCancel(device.id);\n throw e;\n });\n\n deviceConnectionStateMachine.eventDeviceConnected();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n const connectedDevices = await this._manager.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\n );\n\n for (const device of connectedDevices) {\n if (device.id === deviceId) {\n try {\n await this._manager.cancelDeviceConnection(deviceId);\n } catch (e) {\n this._logger.error(\n \"[safeCancel] Error in cancelling device connection\",\n {\n data: { e },\n },\n );\n }\n }\n }\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,E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MAAMS,EACzCD,CACF,EAEMzB,GAAiB,MAAML,EAAO,SAAS,GAAG,IAAKf,GAAMA,EAAE,IAAI,EAE3DkC,EAAiB,KAAK,uCAC1Bd,CACF,EAAE,OAAO,CACP,MAAQI,IACC,CACL,GAAIT,EAAO,GACX,eAAgBS,CAClB,GAEF,KAAOnB,IACL,KAAK,QAAQ,MACX,sFACA,CACE,KAAM,CAAE,MAAAA,CAAM,CAChB,CACF,EAEO0B,EAAO1B,CAAK,EAEvB,CAAC,EAEDgC,EAA6B,gBAAgB,CAC3C,OAAAtB,EACA,QAAS,KAAK,SACd,eAAAmB,CACF,CAAC,EAED,MAAMG,EAA6B,gBAAgB,EAAE,MAAO9B,GAAM,CAChE,WAAK,YAAYQ,EAAO,EAAE,EACpBR,CACR,CAAC,EAED8B,EAA6B,qBAAqB,CACpD,CAAC,EAAE,IAAI,CACT,CAEA,MAAc,YAAYE,EAAoB,CAE5C,GAAI,OAAO,KAAK,SAAS,wBAA2B,WAAY,CAC9D,MAAMlB,EAAmB,MAAM,KAAK,SAAS,iBAC3C,KAAK,uBAAuB,qBAAqB,CACnD,EAEA,UAAWN,KAAUM,EACnB,GAAIN,EAAO,KAAOwB,EAChB,GAAI,CACF,MAAM,KAAK,SAAS,uBAAuBA,CAAQ,CACrD,OAAShC,EAAG,CACV,KAAK,QAAQ,MACX,qDACA,CACE,KAAM,CAAE,EAAAA,CAAE,CACZ,CACF,CACF,CAGN,CACF,CACF",
|
|
6
|
+
"names": ["RNBleTransport_exports", "__export", "RNBleTransport", "rnBleTransportIdentifier", "__toCommonJS", "import_react_native", "import_react_native_ble_plx", "import_device_management_kit", "import_purify_ts", "import_rxjs", "import_Const", "import_Errors", "import_RNBleApduSender", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_manager", "_platform", "_permissionsService", "_scanThrottleDelayMs", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "lastBleStateIsUnknown", "state", "s", "hasPermissions", "canStartScanning", "subject", "devicesById", "error", "rnDevice", "e", "interval", "devices", "internalScannedDevices", "eitherScannedDevices", "timestamp", "a", "b", "device", "d", "scannedDevices", "rawConnectedDevices", "eitherConnectedDevices", "servicesUUIDs", "connectedDevices", "serviceUUID", "bluetoothServiceInfo", "info", "model", "params", "existing", "dependencies", "deviceModel", "deviceName", "throwE", "disconnectionSubscription", "bleDeviceInfos", "internalDevice", "deviceApduSender", "reconnectionTimeout", "deviceConnectionStateMachine", "sub", "deviceId", "deviceConnection", "reconnectionTryCount", "reconnect$", "reconnectedDevice", "usableReconnectedDevice", "errorOrDeviceConnection", "liftEither"]
|
|
7
7
|
}
|
package/lib/cjs/package.json
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Platform as f}from"react-native";import{BleError as b,BleErrorCode as A,State as u}from"react-native-ble-plx";import{DeviceConnectionStateMachine as P,OpeningConnectionError as y,TransportConnectedDevice as I,UnknownDeviceError as U}from"@ledgerhq/device-management-kit";import{Either as w,EitherAsync as T,Left as C,Maybe as v,Right as S}from"purify-ts";import{BehaviorSubject as D,defer as F,finalize as O,first as q,from as _,retry as L,switchMap as h,tap as m,throttleTime as k}from"rxjs";import{BLE_DISCONNECT_TIMEOUT_ANDROID as j,BLE_DISCONNECT_TIMEOUT_IOS as $,CONNECTION_LOST_DELAY as x,DEFAULT_MTU as B}from"../model/Const";import{BleNotSupported as R,BlePermissionsNotGranted as E,BlePoweredOff as z,DeviceConnectionNotFound as H,NoDeviceModelFoundError as M,PeerRemovedPairingError as N}from"../model/Errors";import{RNBleApduSender as G}from"../transport/RNBleApduSender";const ne="RN_BLE";class te{constructor(e,n,i,t,o,s,r,a=1e3,p=d=>new P(d),g=(d,l)=>new G(d,l)){this._deviceModelDataSource=e;this._loggerServiceFactory=n;this._apduSenderFactory=i;this._apduReceiverFactory=t;this._manager=o;this._platform=s;this._permissionsService=r;this._scanThrottleDelayMs=a;this._deviceConnectionStateMachineFactory=p;this._deviceApduSenderFactory=g;this._logger=n("ReactNativeBleTransport"),this._deviceConnectionsById=new Map,this._reconnectionSubscription=v.zero();let d=!1;this._manager.onStateChange(l=>{this._logger.debug(`[manager.onStateChange] called with state: ${l}`),this._bleStateSubject.next(l),d=l===u.Unknown,d&&(this._logger.debug('[manager.onStateChange] forcing state update from "Unknown"'),this._manager.state().then(c=>{d&&(this._logger.debug(`[manager.onStateChange] forcing state update to: "${c}"`),this._bleStateSubject.next(c))}))},!0)}_logger;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new D(u.Unknown);observeBleState(){return this._bleStateSubject.asObservable()}startDiscovering(){return _([])}async stopDiscovering(){await this._stopScanning()}_scannedDevicesSubject=new D([]);_startedScanningSubscriber=void 0;_waitForScanningPrerequisites(){return _([!0]).pipe(m(()=>{if(!this.isSupported())throw new R("BLE not supported");this._logger.debug("[waitForScanningPrerequisites] Prerequisite: isSupported=true")}),h(async()=>this.checkAndRequestPermissions()),m(e=>{if(this._logger.debug(`[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${e}`),!e)throw new E("Permissions not granted")}),h(()=>this.observeBleState()),q(e=>{const n=e===u.PoweredOn;if(this._logger.info(`[waitForScanningPrerequisites] Prerequisite: BLE state=${e}, canStartScanning=${n}`),e===u.PoweredOff)throw new z;if(e===u.Unauthorized)throw new E('Ble State is "Unauthorized"');if(e===u.Unsupported)throw new R;return n}))}_startScanning(){if(this._startedScanningSubscriber!=null){this._logger.info("[startScanning] !! startScanning already started");return}this._scannedDevicesSubject.next([]),this._logger.info("[startScanning] startScanning"),this._startedScanningSubscriber=_([!0]).pipe(h(()=>{const e=new D([]),n=new Map;this._logger.info("[startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(t,o)=>{if(t){this._logger.error("[startScanning] Error in startDeviceScan callback",{data:{error:t,rnDevice:o}}),e.error(t);return}if(!o){this._logger.warn("[startScanning] Null Device in startDeviceScan callback",{data:{rnDevice:o}}),e.error(new Error("Null device in startDeviceScan callback"));return}n.set(o.id,{device:o,timestamp:Date.now()}),e.next(Array.from(n.values()))}).catch(t=>{e.error(t),this._logger.error("[startScanning] Error while calling startDeviceScan",{data:{error:t}})}),this._logger.debug("[startScanning] after startDeviceScan");const i=setInterval(()=>{e.next(Array.from(n.values()))},1e3);return e.pipe(O(()=>{this._logger.debug("[startScanning] finalize"),e.complete(),clearInterval(i),this._stopScanning()}))}),k(this._scanThrottleDelayMs)).subscribe({next:e=>{this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("[startScanning] Error while scanning",{data:{error:e}}),this._scannedDevicesSubject.error(e)}})}async _stopScanning(){this._logger.debug("[stopScanning] stopScanning"),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0,this._scannedDevicesSubject.complete(),this._scannedDevicesSubject=new D([])}listenToAvailableDevices(){return this._waitForScanningPrerequisites().pipe(m(()=>this._startScanning()),h(()=>this._scannedDevicesSubject),h(async e=>{const n=e.filter(({timestamp:r})=>r>Date.now()-x).sort((r,a)=>(a.device.rssi??-1/0)-(r.device.rssi??-1/0)).map(({device:r})=>this._mapDeviceToTransportDiscoveredDevice(r,r.serviceUUIDs)).filter(r=>!!r),i=w.rights(n),t=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices()).catch(r=>{throw this._logger.error("[listenToAvailableDevices] Error calling manager.connectedDevices",{data:{error:r}}),r}),o=await Promise.all(t.map(async r=>{try{const p=(await r.services()).map(g=>g.uuid);return this._mapDeviceToTransportDiscoveredDevice(r,p)}catch(a){return this._logger.error("[listenToAvailableDevices] Error in mapping device to transport discovered device",{data:{e:a}}),C(new M(`Error in mapping device to transport discovered device: ${a}`))}})),s=w.rights(o);return this._logger.debug("[listenToAvailableDevices]",{data:{rawConnectedDevices:t.map(r=>r.name),connectedDevices:s.map(r=>r.name),scannedDevices:i.map(r=>r.name)}}),[...s,...i]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const n of e||[]){const i=this._deviceModelDataSource.getBluetoothServicesInfos()[n];if(i)return S(i)}return C(new M(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(i=>i.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,n){const i=this._mapServicesUUIDsToDeviceModel(n);return this._logger.debug("[mapDeviceToTransportDiscoveredDevice] Found device",{data:{localName:e.localName,name:e.name}}),i.map(t=>({id:e.id,name:e.localName||e.name||"",deviceModel:t,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){this._logger.debug("[connect] Called",{data:{deviceId:e.deviceId}});const n=this._deviceConnectionsById.get(e.deviceId);if(n){this._logger.debug("[connect] Existing device connection found",{data:{deviceId:e.deviceId}});const i=n.getDependencies(),t=i.internalDevice.bleDeviceInfos.deviceModel,o=i.device.localName||i.device.name||void 0;return this._logger.info("[connect] existing device name",{data:{deviceName:o,localName:i.device.localName,name:i.device.name}}),S(new I({id:e.deviceId,deviceModel:t,type:"BLE",sendApdu:(...s)=>n.sendApdu(...s),transport:this.identifier,name:o}))}return this._logger.debug("[connect] No existing device connection found, establishing one",{data:{deviceId:e.deviceId}}),await this._stopScanning(),await this._safeCancel(e.deviceId),T(async({throwE:i})=>{let t,o=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:B}),t=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),o=(await t.services()).map(c=>c.uuid)}catch(c){return c instanceof b&&c.iosErrorCode===14?i(new N(c)):c instanceof b&&c.errorCode===A.OperationCancelled&&f.OS==="android"?i(new N(c)):i(new y(c))}const s=this._listenToDeviceDisconnected(e.deviceId),r=this._mapServicesUUIDsToBluetoothDeviceInfo(o).caseOf({Right:c=>c,Left:c=>i(new y(c))}),a=r.deviceModel,p={id:t.id,bleDeviceInfos:r},g=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:t,internalDevice:p,manager:this._manager}},this._loggerServiceFactory),d=f.OS==="ios"?$:j,l=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:g,timeoutDuration:d,tryToReconnect:()=>this.tryToReconnect(e.deviceId),onTerminated:async()=>{this._logger.debug("[onTerminated]",{data:{deviceId:e.deviceId}});try{await this._safeCancel(e.deviceId)}catch(c){this._logger.error("[onTerminated] Error in termination of device connection",{data:{e:c}})}finally{this._deviceConnectionsById.delete(e.deviceId),this._reconnectionSubscription.ifJust(c=>{c.unsubscribe(),this._reconnectionSubscription=v.zero()}),this._logger.debug("[onTerminated] signaling disconnection",{data:{deviceId:e.deviceId}}),e.onDisconnect(e.deviceId)}}});return await g.setupConnection().catch(c=>{throw this._safeCancel(e.deviceId),s.remove(),c}),this._deviceConnectionsById.set(e.deviceId,l),this._logger.info("[connect] new device name",{data:{localName:t.localName,name:t.name}}),new I({id:t.id,deviceModel:a,type:"BLE",sendApdu:(...c)=>l.sendApdu(...c),transport:this.identifier,name:t.localName||t.name||void 0})}).run()}async disconnect(e){const n=e.connectedDevice.id,i=this._deviceConnectionsById.get(n);if(!i)throw new U(`No connected device found with id ${n}`);return i.closeConnection(),Promise.resolve(S(void 0))}isSupported(){return["android","ios"].includes(this._platform.OS)}getIdentifier(){return this.identifier}async checkAndRequestPermissions(){return this._logger.debug("[checkAndRequestPermissions] Called"),await this._permissionsService.checkRequiredPermissions()?!0:await this._permissionsService.requestRequiredPermissions()}_handleDeviceDisconnected(e,n){if(this._logger.debug("[_handleDeviceDisconnected]",{data:{error:e,device:n}}),!n){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!n?.id||!this._deviceConnectionsById.has(n?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:n}});return}const i=n.id;v.fromNullable(this._deviceConnectionsById.get(i)).map(t=>t.eventDeviceDisconnected())}_listenToDeviceDisconnected(e){const n=this._manager.onDeviceDisconnected(e,(i,t)=>{this._handleDeviceDisconnected(i,t),n.remove()});return n}async tryToReconnect(e){this._logger.debug("[tryToReconnect] Called",{data:{deviceId:e}});let n=0;await this._stopScanning(),await this._safeCancel(e);const i=F(async()=>{let t=null;n++;try{this._logger.debug(`[tryToReconnect](try=${n}) Reconnecting to device`,{data:{id:e}});const o=await this._manager.connectToDevice(e,{requestMTU:B,timeout:2e3});this._logger.debug(`[tryToReconnect](try=${n}) Established connection to device`,{data:{id:e}});const s=await o.discoverAllServicesAndCharacteristics();return this._logger.debug(`[tryToReconnect](try=${n}) Discovered all services and characteristics`,{data:{usableReconnectedDevice:s}}),t=this._listenToDeviceDisconnected(e),await this._handleDeviceReconnected(s),s}catch(o){throw this._logger.warn(`[tryToReconnect](try=${n}) Reconnecting to device failed`,{data:{e:o}}),t?.remove(),await this._stopScanning(),await this._safeCancel(e),o}}).pipe(L(5));this._reconnectionSubscription=v.of(i.subscribe({next:t=>this._logger.debug(`[tryToReconnect](try=${n}) Fully reconnected to device (id=${t.id})`),complete:()=>{this._logger.debug("[tryToReconnect] Completed"),this._reconnectionSubscription=v.zero()},error:t=>{this._logger.error("[tryToReconnect] All reconnection attempts failed",{data:{e:t}}),this._deviceConnectionsById.get(e)?.closeConnection(),this._reconnectionSubscription=v.zero()}}))}async _handleDeviceReconnected(e){const n=v.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new H);return T(async({liftEither:i,throwE:t})=>{const o=await i(n),s=(await e.services()).map(a=>a.uuid),r=this._mapServicesUUIDsToBluetoothDeviceInfo(s).caseOf({Right:a=>({id:e.id,bleDeviceInfos:a}),Left:a=>(this._logger.error("[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info",{data:{error:a}}),t(a))});o.setDependencies({device:e,manager:this._manager,internalDevice:r}),await o.setupConnection().catch(a=>{throw this._safeCancel(e.id),a}),o.eventDeviceConnected()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const n=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const i of n)if(i.id===e)try{await this._manager.cancelDeviceConnection(e)}catch(t){this._logger.error("[safeCancel] Error in cancelling device connection",{data:{e:t}})}}}}export{te as RNBleTransport,ne as rnBleTransportIdentifier};
|
|
1
|
+
import{Platform as b}from"react-native";import{BleError as m,BleErrorCode as A,State as u}from"react-native-ble-plx";import{DeviceConnectionStateMachine as P,OpeningConnectionError as y,TransportConnectedDevice as I,UnknownDeviceError as U}from"@ledgerhq/device-management-kit";import{Either as w,EitherAsync as C,Left as T,Maybe as v,Right as S}from"purify-ts";import{BehaviorSubject as D,defer as F,finalize as O,first as q,from as _,retry as L,switchMap as h,tap as f,throttleTime as k}from"rxjs";import{BLE_DISCONNECT_TIMEOUT_ANDROID as j,BLE_DISCONNECT_TIMEOUT_IOS as $,CONNECTION_LOST_DELAY as x,DEFAULT_MTU as B}from"../model/Const";import{BleNotSupported as R,BlePermissionsNotGranted as M,BlePoweredOff as z,DeviceConnectionNotFound as H,NoDeviceModelFoundError as E,PeerRemovedPairingError as N}from"../model/Errors";import{RNBleApduSender as G}from"../transport/RNBleApduSender";const ne="RN_BLE";class te{constructor(e,n,i,t,o,a,r,s=1e3,p=d=>new P(d),g=(d,l)=>new G(d,l)){this._deviceModelDataSource=e;this._loggerServiceFactory=n;this._apduSenderFactory=i;this._apduReceiverFactory=t;this._manager=o;this._platform=a;this._permissionsService=r;this._scanThrottleDelayMs=s;this._deviceConnectionStateMachineFactory=p;this._deviceApduSenderFactory=g;this._logger=n("ReactNativeBleTransport"),this._deviceConnectionsById=new Map,this._reconnectionSubscription=v.zero();let d=!1;this._manager.onStateChange(l=>{this._logger.debug(`[manager.onStateChange] called with state: ${l}`),this._bleStateSubject.next(l),d=l===u.Unknown,d&&(this._logger.debug('[manager.onStateChange] forcing state update from "Unknown"'),this._manager.state().then(c=>{d&&(this._logger.debug(`[manager.onStateChange] forcing state update to: "${c}"`),this._bleStateSubject.next(c))}))},!0)}_logger;_deviceConnectionsById;identifier="RN_BLE";_reconnectionSubscription;_bleStateSubject=new D(u.Unknown);observeBleState(){return this._bleStateSubject.asObservable()}startDiscovering(){return _([])}async stopDiscovering(){await this._stopScanning()}_scannedDevicesSubject=new D([]);_startedScanningSubscriber=void 0;_waitForScanningPrerequisites(){return _([!0]).pipe(f(()=>{if(!this.isSupported())throw new R("BLE not supported");this._logger.debug("[waitForScanningPrerequisites] Prerequisite: isSupported=true")}),h(async()=>this.checkAndRequestPermissions()),f(e=>{if(this._logger.debug(`[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${e}`),!e)throw new M("Permissions not granted")}),h(()=>this.observeBleState()),q(e=>{const n=e===u.PoweredOn;if(this._logger.info(`[waitForScanningPrerequisites] Prerequisite: BLE state=${e}, canStartScanning=${n}`),e===u.PoweredOff)throw new z;if(e===u.Unauthorized)throw new M('Ble State is "Unauthorized"');if(e===u.Unsupported)throw new R;return n}))}_startScanning(){if(this._startedScanningSubscriber!=null){this._logger.info("[startScanning] !! startScanning already started");return}this._scannedDevicesSubject.next([]),this._logger.info("[startScanning] startScanning"),this._startedScanningSubscriber=_([!0]).pipe(h(()=>{const e=new D([]),n=new Map;this._logger.info("[startScanning] startDeviceScan"),this._manager.startDeviceScan(this._deviceModelDataSource.getBluetoothServices(),{allowDuplicates:!0},(t,o)=>{if(t){this._logger.error("[startScanning] Error in startDeviceScan callback",{data:{error:t,rnDevice:o}}),e.error(t);return}if(!o){this._logger.warn("[startScanning] Null Device in startDeviceScan callback",{data:{rnDevice:o}}),e.error(new Error("Null device in startDeviceScan callback"));return}n.set(o.id,{device:o,timestamp:Date.now()}),e.next(Array.from(n.values()))}).catch(t=>{e.error(t),this._logger.error("[startScanning] Error while calling startDeviceScan",{data:{error:t}})}),this._logger.debug("[startScanning] after startDeviceScan");const i=setInterval(()=>{e.next(Array.from(n.values()))},1e3);return e.pipe(O(()=>{this._logger.debug("[startScanning] finalize"),e.complete(),clearInterval(i),this._stopScanning()}))}),k(this._scanThrottleDelayMs)).subscribe({next:e=>{this._scannedDevicesSubject.next(e)},error:e=>{this._logger.error("[startScanning] Error while scanning",{data:{error:e}}),this._scannedDevicesSubject.error(e)}})}async _stopScanning(){this._logger.debug("[stopScanning] stopScanning"),await this._manager.stopDeviceScan(),this._startedScanningSubscriber?.unsubscribe(),this._startedScanningSubscriber=void 0,this._scannedDevicesSubject.complete(),this._scannedDevicesSubject=new D([])}listenToAvailableDevices(){return this._waitForScanningPrerequisites().pipe(f(()=>this._startScanning()),h(()=>this._scannedDevicesSubject),h(async e=>{const n=e.filter(({timestamp:r})=>r>Date.now()-x).sort((r,s)=>(s.device.rssi??-1/0)-(r.device.rssi??-1/0)).map(({device:r})=>this._mapDeviceToTransportDiscoveredDevice(r,r.serviceUUIDs)).filter(r=>!!r),i=w.rights(n),t=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices()).catch(r=>{throw this._logger.error("[listenToAvailableDevices] Error calling manager.connectedDevices",{data:{error:r}}),r}),o=await Promise.all(t.map(async r=>{try{const p=(await r.services()).map(g=>g.uuid);return this._mapDeviceToTransportDiscoveredDevice(r,p)}catch(s){return this._logger.error("[listenToAvailableDevices] Error in mapping device to transport discovered device",{data:{e:s}}),T(new E(`Error in mapping device to transport discovered device: ${s}`))}})),a=w.rights(o);return this._logger.debug("[listenToAvailableDevices]",{data:{rawConnectedDevices:t.map(r=>r.name),connectedDevices:a.map(r=>r.name),scannedDevices:i.map(r=>r.name)}}),[...a,...i]}))}_mapServicesUUIDsToBluetoothDeviceInfo(e){for(const n of e||[]){const i=this._deviceModelDataSource.getBluetoothServicesInfos()[n];if(i)return S(i)}return T(new E(`No device model found for [uuids=${e}]`))}_mapServicesUUIDsToDeviceModel(e){return this._mapServicesUUIDsToBluetoothDeviceInfo(e).map(i=>i.deviceModel)}_mapDeviceToTransportDiscoveredDevice(e,n){return this._mapServicesUUIDsToDeviceModel(n).map(t=>({id:e.id,name:e.localName||e.name||"",deviceModel:t,transport:this.identifier,rssi:e.rssi||void 0}))}async connect(e){this._logger.debug("[connect] Called",{data:{deviceId:e.deviceId}});const n=this._deviceConnectionsById.get(e.deviceId);if(n){this._logger.debug("[connect] Existing device connection found",{data:{deviceId:e.deviceId}});const i=n.getDependencies(),t=i.internalDevice.bleDeviceInfos.deviceModel,o=i.device.localName||i.device.name||void 0;return S(new I({id:e.deviceId,deviceModel:t,type:"BLE",sendApdu:(...a)=>n.sendApdu(...a),transport:this.identifier,name:o}))}return this._logger.debug("[connect] No existing device connection found, establishing one",{data:{deviceId:e.deviceId}}),await this._stopScanning(),await this._safeCancel(e.deviceId),C(async({throwE:i})=>{let t,o=[];try{await this._manager.connectToDevice(e.deviceId,{requestMTU:B}),t=await this._manager.discoverAllServicesAndCharacteristicsForDevice(e.deviceId),o=(await t.services()).map(c=>c.uuid)}catch(c){return c instanceof m&&c.iosErrorCode===14?i(new N(c)):c instanceof m&&c.errorCode===A.OperationCancelled&&b.OS==="android"?i(new N(c)):i(new y(c))}const a=this._listenToDeviceDisconnected(e.deviceId),r=this._mapServicesUUIDsToBluetoothDeviceInfo(o).caseOf({Right:c=>c,Left:c=>i(new y(c))}),s=r.deviceModel,p={id:t.id,bleDeviceInfos:r},g=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:t,internalDevice:p,manager:this._manager}},this._loggerServiceFactory),d=b.OS==="ios"?$:j,l=this._deviceConnectionStateMachineFactory({deviceId:e.deviceId,deviceApduSender:g,timeoutDuration:d,tryToReconnect:()=>this.tryToReconnect(e.deviceId),onTerminated:async()=>{this._logger.debug("[onTerminated]",{data:{deviceId:e.deviceId}});try{await this._safeCancel(e.deviceId)}catch(c){this._logger.error("[onTerminated] Error in termination of device connection",{data:{e:c}})}finally{this._deviceConnectionsById.delete(e.deviceId),this._reconnectionSubscription.ifJust(c=>{c.unsubscribe(),this._reconnectionSubscription=v.zero()}),this._logger.debug("[onTerminated] signaling disconnection",{data:{deviceId:e.deviceId}}),e.onDisconnect(e.deviceId)}}});return await g.setupConnection().catch(c=>{throw this._safeCancel(e.deviceId),a.remove(),c}),this._deviceConnectionsById.set(e.deviceId,l),new I({id:t.id,deviceModel:s,type:"BLE",sendApdu:(...c)=>l.sendApdu(...c),transport:this.identifier,name:t.localName||t.name||void 0})}).run()}async disconnect(e){const n=e.connectedDevice.id,i=this._deviceConnectionsById.get(n);if(!i)throw new U(`No connected device found with id ${n}`);return i.closeConnection(),Promise.resolve(S(void 0))}isSupported(){return["android","ios"].includes(this._platform.OS)}getIdentifier(){return this.identifier}async checkAndRequestPermissions(){return this._logger.debug("[checkAndRequestPermissions] Called"),await this._permissionsService.checkRequiredPermissions()?!0:await this._permissionsService.requestRequiredPermissions()}_handleDeviceDisconnected(e,n){if(this._logger.debug("[_handleDeviceDisconnected]",{data:{error:e,device:n}}),!n){this._logger.debug("[_handleDeviceDisconnected] disconnected handler didn't find device");return}if(!n?.id||!this._deviceConnectionsById.has(n?.id))return;if(e){this._logger.error("device disconnected error",{data:{error:e,device:n}});return}const i=n.id;v.fromNullable(this._deviceConnectionsById.get(i)).map(t=>t.eventDeviceDisconnected())}_listenToDeviceDisconnected(e){const n=this._manager.onDeviceDisconnected(e,(i,t)=>{this._handleDeviceDisconnected(i,t),n.remove()});return n}async tryToReconnect(e){this._logger.debug("[tryToReconnect] Called",{data:{deviceId:e}});let n=0;await this._stopScanning(),await this._safeCancel(e);const i=F(async()=>{let t=null;n++;try{this._logger.debug(`[tryToReconnect](try=${n}) Reconnecting to device`,{data:{id:e}});const o=await this._manager.connectToDevice(e,{requestMTU:B,timeout:2e3});this._logger.debug(`[tryToReconnect](try=${n}) Established connection to device`,{data:{id:e}});const a=await o.discoverAllServicesAndCharacteristics();return this._logger.debug(`[tryToReconnect](try=${n}) Discovered all services and characteristics`,{data:{usableReconnectedDevice:a}}),t=this._listenToDeviceDisconnected(e),await this._handleDeviceReconnected(a),a}catch(o){throw this._logger.warn(`[tryToReconnect](try=${n}) Reconnecting to device failed`,{data:{e:o}}),t?.remove(),await this._stopScanning(),await this._safeCancel(e),o}}).pipe(L(5));this._reconnectionSubscription=v.of(i.subscribe({next:t=>this._logger.debug(`[tryToReconnect](try=${n}) Fully reconnected to device (id=${t.id})`),complete:()=>{this._logger.debug("[tryToReconnect] Completed"),this._reconnectionSubscription=v.zero()},error:t=>{this._logger.error("[tryToReconnect] All reconnection attempts failed",{data:{e:t}}),this._deviceConnectionsById.get(e)?.closeConnection(),this._reconnectionSubscription=v.zero()}}))}async _handleDeviceReconnected(e){const n=v.fromNullable(this._deviceConnectionsById.get(e.id)).toEither(new H);return C(async({liftEither:i,throwE:t})=>{const o=await i(n),a=(await e.services()).map(s=>s.uuid),r=this._mapServicesUUIDsToBluetoothDeviceInfo(a).caseOf({Right:s=>({id:e.id,bleDeviceInfos:s}),Left:s=>(this._logger.error("[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info",{data:{error:s}}),t(s))});o.setDependencies({device:e,manager:this._manager,internalDevice:r}),await o.setupConnection().catch(s=>{throw this._safeCancel(e.id),s}),o.eventDeviceConnected()}).run()}async _safeCancel(e){if(typeof this._manager.cancelDeviceConnection=="function"){const n=await this._manager.connectedDevices(this._deviceModelDataSource.getBluetoothServices());for(const i of n)if(i.id===e)try{await this._manager.cancelDeviceConnection(e)}catch(t){this._logger.error("[safeCancel] Error in cancelling device connection",{data:{e:t}})}}}}export{te as RNBleTransport,ne as rnBleTransportIdentifier};
|
|
2
2
|
//# sourceMappingURL=RNBleTransport.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/api/transport/RNBleTransport.ts"],
|
|
4
|
-
"sourcesContent": ["import { Platform } from \"react-native\";\nimport {\n BleError,\n BleErrorCode,\n type BleManager,\n type Device,\n State,\n type Subscription as BleSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Either, EitherAsync, Left, Maybe, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n defer,\n finalize,\n first,\n from,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n tap,\n throttleTime,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT_ANDROID,\n BLE_DISCONNECT_TIMEOUT_IOS,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n BlePermissionsNotGranted,\n BlePoweredOff,\n DeviceConnectionNotFound,\n NoDeviceModelFoundError,\n PeerRemovedPairingError,\n} from \"@api/model/Errors\";\nimport { type PermissionsService } from \"@api/permissions/PermissionsService\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\ntype InternalScannedDevice = {\n device: Device;\n timestamp: number;\n};\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n // private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private readonly _bleStateSubject: BehaviorSubject<State> =\n new BehaviorSubject<State>(State.Unknown);\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n private readonly _manager: BleManager,\n private readonly _platform: Platform,\n private readonly _permissionsService: PermissionsService,\n private readonly _scanThrottleDelayMs: number = 1000,\n private readonly _deviceConnectionStateMachineFactory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies> = (args) =>\n new DeviceConnectionStateMachine(args),\n private readonly _deviceApduSenderFactory: (\n args: RNBleApduSenderConstructorArgs,\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) => RNBleApduSender = (args, loggerFactory) =>\n new RNBleApduSender(args, loggerFactory),\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._deviceConnectionsById = new Map();\n this._reconnectionSubscription = Maybe.zero();\n // FIXME: we should have a destroy method to unregister the onStateChange listener\n let lastBleStateIsUnknown = false;\n this._manager.onStateChange((state) => {\n this._logger.debug(`[manager.onStateChange] called with state: ${state}`);\n this._bleStateSubject.next(state);\n lastBleStateIsUnknown = state === State.Unknown;\n if (lastBleStateIsUnknown) {\n // There seems to be a bug in the library where the state is not updated after going in an Unknown state...\n this._logger.debug(\n `[manager.onStateChange] forcing state update from \"Unknown\"`,\n );\n this._manager.state().then((s) => {\n if (lastBleStateIsUnknown) {\n this._logger.debug(\n `[manager.onStateChange] forcing state update to: \"${s}\"`,\n );\n this._bleStateSubject.next(s);\n }\n });\n }\n }, true);\n }\n\n /** Exposed for testing purposes */\n observeBleState(): Observable<State> {\n return this._bleStateSubject.asObservable();\n }\n\n /**\n * Not implemented for now as the return signature is not really usable.\n * Use listenToAvailableDevices instead.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return from([]);\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._stopScanning();\n }\n\n private _scannedDevicesSubject: BehaviorSubject<InternalScannedDevice[]> =\n new BehaviorSubject<InternalScannedDevice[]>([]);\n private _startedScanningSubscriber: Subscription | undefined = undefined;\n\n /**\n * Returns an observable that emits a value when the prerequisites for scanning are met.\n * The prerequisites are:\n * - BLE should be supported. If not, it will throw an error.\n * - Permissions should be granted. If not, it request them, if it fails, it will throw an error.\n * - BLE state should be PoweredOn.\n * - If BLE state is undetermined (Unknown or Resetting), it will wait for the state to be updated.\n * - For other states, it will throw an error.\n */\n private _waitForScanningPrerequisites() {\n return from([true]).pipe(\n tap(() => {\n if (!this.isSupported()) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n this._logger.debug(\n \"[waitForScanningPrerequisites] Prerequisite: isSupported=true\",\n );\n }),\n switchMap(async () => this.checkAndRequestPermissions()),\n tap((hasPermissions) => {\n this._logger.debug(\n `[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${hasPermissions}`,\n );\n if (!hasPermissions) {\n throw new BlePermissionsNotGranted(\"Permissions not granted\");\n }\n }),\n switchMap(() => this.observeBleState()),\n first((state) => {\n /**\n * We wait for the BLE state to be PoweredOn, in case the current state is one of those:\n * - Unknown: temporary undetermined state which will quickly be updated\n * - Resetting: temporary undetermined state which will quickly be updated\n */\n const canStartScanning = state === State.PoweredOn;\n this._logger.info(\n `[waitForScanningPrerequisites] Prerequisite: BLE state=${state}, canStartScanning=${canStartScanning}`,\n );\n if (state === State.PoweredOff) {\n throw new BlePoweredOff();\n } else if (state === State.Unauthorized) {\n throw new BlePermissionsNotGranted('Ble State is \"Unauthorized\"');\n } else if (state === State.Unsupported) {\n throw new BleNotSupported();\n }\n return canStartScanning;\n }),\n );\n }\n\n private _startScanning() {\n if (this._startedScanningSubscriber != undefined) {\n this._logger.info(\"[startScanning] !! startScanning already started\");\n return;\n }\n\n //Reset the scanned devices list as new scan will start\n this._scannedDevicesSubject.next([]);\n\n this._logger.info(\"[startScanning] startScanning\");\n\n this._startedScanningSubscriber = from([true])\n .pipe(\n switchMap(() => {\n const subject = new BehaviorSubject<InternalScannedDevice[]>([]);\n const devicesById = new Map<string, InternalScannedDevice>();\n\n this._logger.info(\"[startScanning] startDeviceScan\");\n this._manager\n .startDeviceScan(\n this._deviceModelDataSource.getBluetoothServices(),\n { allowDuplicates: true },\n (error, rnDevice) => {\n if (error) {\n this._logger.error(\n \"[startScanning] Error in startDeviceScan callback\",\n {\n data: { error, rnDevice },\n },\n );\n subject.error(error);\n return;\n }\n if (!rnDevice) {\n this._logger.warn(\n \"[startScanning] Null Device in startDeviceScan callback\",\n {\n data: { rnDevice },\n },\n );\n subject.error(\n new Error(\"Null device in startDeviceScan callback\"),\n );\n return;\n }\n devicesById.set(rnDevice.id, {\n device: rnDevice,\n timestamp: Date.now(),\n });\n subject.next(Array.from(devicesById.values()));\n },\n )\n .catch((e) => {\n subject.error(e);\n this._logger.error(\n \"[startScanning] Error while calling startDeviceScan\",\n {\n data: { error: e },\n },\n );\n });\n\n this._logger.debug(\"[startScanning] after startDeviceScan\");\n\n /**\n * In case there is no update from startDeviceScan, we still emit the\n * list of devices. This is useful for instance if there is only 1 device\n * in the vicinity and it just got turned off. It will not \"advertise\"\n * anymore so startDeviceScan won't trigger.\n */\n const interval = setInterval(() => {\n subject.next(Array.from(devicesById.values()));\n }, 1000);\n\n return subject.pipe(\n finalize(() => {\n this._logger.debug(\"[startScanning] finalize\");\n subject.complete();\n clearInterval(interval);\n this._stopScanning();\n }),\n );\n }),\n throttleTime(this._scanThrottleDelayMs),\n )\n .subscribe({\n next: (devices) => {\n this._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"[startScanning] Error while scanning\", {\n data: { error },\n });\n this._scannedDevicesSubject.error(error);\n },\n });\n }\n\n private async _stopScanning(): Promise<void> {\n this._logger.debug(\"[stopScanning] stopScanning\");\n await this._manager.stopDeviceScan();\n //Stop listening the observable from this._startScanning()\n this._startedScanningSubscriber?.unsubscribe();\n this._startedScanningSubscriber = undefined;\n this._scannedDevicesSubject.complete();\n this._scannedDevicesSubject = new BehaviorSubject<InternalScannedDevice[]>(\n [],\n );\n\n return;\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n return this._waitForScanningPrerequisites().pipe(\n tap(() => this._startScanning()),\n switchMap(() => this._scannedDevicesSubject),\n switchMap(async (internalScannedDevices) => {\n const eitherScannedDevices = internalScannedDevices\n .filter(\n ({ timestamp }) => timestamp > Date.now() - CONNECTION_LOST_DELAY,\n )\n .sort(\n (a, b) =>\n (b.device.rssi ?? -Infinity) - (a.device.rssi ?? -Infinity), // RSSI is a negative value and the higher, the stronger the signal\n )\n .map(({ device }) =>\n this._mapDeviceToTransportDiscoveredDevice(\n device,\n device.serviceUUIDs,\n ),\n )\n .filter((d) => !!d);\n\n const scannedDevices = Either.rights(eitherScannedDevices);\n\n const rawConnectedDevices = await this._manager\n .connectedDevices(this._deviceModelDataSource.getBluetoothServices())\n .catch((e) => {\n this._logger.error(\n \"[listenToAvailableDevices] Error calling manager.connectedDevices\",\n {\n data: { error: e },\n },\n );\n throw e;\n });\n\n const eitherConnectedDevices = await Promise.all(\n rawConnectedDevices.map(async (device) => {\n try {\n const services = await device.services();\n const servicesUUIDs = services.map((s) => s.uuid);\n return this._mapDeviceToTransportDiscoveredDevice(\n device,\n servicesUUIDs,\n );\n } catch (e) {\n this._logger.error(\n \"[listenToAvailableDevices] Error in mapping device to transport discovered device\",\n {\n data: { e },\n },\n );\n return Left(\n new NoDeviceModelFoundError(\n `Error in mapping device to transport discovered device: ${e}`,\n ),\n );\n }\n }),\n );\n\n const connectedDevices = Either.rights(eitherConnectedDevices);\n\n this._logger.debug(\"[listenToAvailableDevices]\", {\n data: {\n rawConnectedDevices: rawConnectedDevices.map((d) => d.name),\n connectedDevices: connectedDevices.map((d) => d.name),\n scannedDevices: scannedDevices.map((d) => d.name),\n },\n });\n\n /** We return both connected and scanned devices, as scanned devices don't include connected devices */\n return [...connectedDevices, ...scannedDevices];\n }),\n );\n }\n\n private _mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, BleDeviceInfos> {\n for (const serviceUUID of servicesUUIDs || []) {\n const bluetoothServiceInfo =\n this._deviceModelDataSource.getBluetoothServicesInfos()[serviceUUID];\n if (bluetoothServiceInfo) return Right(bluetoothServiceInfo);\n }\n\n return Left(\n new NoDeviceModelFoundError(\n `No device model found for [uuids=${servicesUUIDs}]`,\n ),\n );\n }\n\n private _mapServicesUUIDsToDeviceModel(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDeviceModel> {\n const bluetoothServiceInfo =\n this._mapServicesUUIDsToBluetoothDeviceInfo(servicesUUIDs);\n return bluetoothServiceInfo.map((info) => info.deviceModel);\n }\n\n private _mapDeviceToTransportDiscoveredDevice(\n device: Device,\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDiscoveredDevice> {\n const deviceModel = this._mapServicesUUIDsToDeviceModel(servicesUUIDs);\n this._logger.debug(\"[mapDeviceToTransportDiscoveredDevice] Found device\", {\n data: {\n localName: device.localName,\n name: device.name,\n },\n });\n return deviceModel.map((model) => ({\n id: device.id,\n name: device.localName || device.name || \"\",\n deviceModel: model,\n transport: this.identifier,\n rssi: device.rssi || undefined,\n }));\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n this._logger.debug(\"[connect] Called\", {\n data: { deviceId: params.deviceId },\n });\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n this._logger.debug(\"[connect] Existing device connection found\", {\n data: { deviceId: params.deviceId },\n });\n const dependencies = existing.getDependencies();\n const deviceModel =\n dependencies.internalDevice.bleDeviceInfos.deviceModel;\n const deviceName =\n dependencies.device.localName || dependencies.device.name || undefined;\n this._logger.info(\"[connect] existing device name\", {\n data: {\n deviceName,\n localName: dependencies.device.localName,\n name: dependencies.device.name,\n },\n });\n return Right(\n new TransportConnectedDevice({\n id: params.deviceId,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...a) => existing.sendApdu(...a),\n transport: this.identifier,\n name: deviceName,\n }),\n );\n }\n\n this._logger.debug(\n \"[connect] No existing device connection found, establishing one\",\n {\n data: { deviceId: params.deviceId },\n },\n );\n\n await this._stopScanning();\n await this._safeCancel(params.deviceId);\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ throwE }) => {\n let device: Device;\n let servicesUUIDs: string[] = [];\n try {\n await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n device =\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n\n servicesUUIDs = (await device.services()).map((s) => s.uuid);\n } catch (error) {\n if (\n error instanceof BleError &&\n (error.iosErrorCode as number) === 14\n ) {\n /**\n * This happens when the Ledger device reset its pairing, but the\n * iOS system still has that device paired.\n */\n return throwE(new PeerRemovedPairingError(error));\n }\n if (\n error instanceof BleError &&\n error.errorCode === BleErrorCode.OperationCancelled &&\n Platform.OS === \"android\"\n ) {\n return throwE(new PeerRemovedPairingError(error));\n }\n return throwE(new OpeningConnectionError(error));\n }\n\n const disconnectionSubscription = this._listenToDeviceDisconnected(\n params.deviceId,\n );\n\n const bleDeviceInfos = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return info;\n },\n Left: (error) => {\n return throwE(new OpeningConnectionError(error));\n },\n });\n\n const deviceModel = bleDeviceInfos.deviceModel;\n\n const internalDevice: RNBleInternalDevice = {\n id: device.id,\n bleDeviceInfos,\n };\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: { device, internalDevice, manager: this._manager },\n },\n this._loggerServiceFactory,\n );\n\n const reconnectionTimeout =\n Platform.OS === \"ios\"\n ? BLE_DISCONNECT_TIMEOUT_IOS\n : BLE_DISCONNECT_TIMEOUT_ANDROID;\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: reconnectionTimeout,\n tryToReconnect: () => this.tryToReconnect(params.deviceId),\n onTerminated: async () => {\n this._logger.debug(\"[onTerminated]\", {\n data: { deviceId: params.deviceId },\n });\n try {\n await this._safeCancel(params.deviceId);\n } catch (e) {\n this._logger.error(\n \"[onTerminated] Error in termination of device connection\",\n { data: { e } },\n );\n } finally {\n this._deviceConnectionsById.delete(params.deviceId);\n this._reconnectionSubscription.ifJust((sub) => {\n sub.unsubscribe();\n this._reconnectionSubscription = Maybe.zero();\n });\n this._logger.debug(\"[onTerminated] signaling disconnection\", {\n data: { deviceId: params.deviceId },\n });\n params.onDisconnect(params.deviceId);\n }\n },\n });\n\n await deviceApduSender.setupConnection().catch((e) => {\n this._safeCancel(params.deviceId);\n disconnectionSubscription.remove();\n throw e;\n });\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n this._logger.info(\"[connect] new device name\", {\n data: {\n localName: device.localName,\n name: device.name,\n },\n });\n return new TransportConnectedDevice({\n id: device.id,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n name: device.localName || device.name || undefined,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const deviceConnection = this._deviceConnectionsById.get(deviceId);\n if (!deviceConnection) {\n throw new UnknownDeviceError(\n `No connected device found with id ${deviceId}`,\n );\n }\n\n deviceConnection.closeConnection();\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return [\"android\", \"ios\"].includes(this._platform.OS);\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Checks if the necessary permissions are granted and requests them if not.\n */\n async checkAndRequestPermissions(): Promise<boolean> {\n this._logger.debug(\"[checkAndRequestPermissions] Called\");\n\n const checkResult =\n await this._permissionsService.checkRequiredPermissions();\n if (checkResult) return true;\n\n const requestResult =\n await this._permissionsService.requestRequiredPermissions();\n return requestResult;\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n this._logger.debug(\"[_handleDeviceDisconnected]\", {\n data: { error, device },\n });\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (deviceConnection) => deviceConnection.eventDeviceDisconnected(),\n );\n }\n\n private _listenToDeviceDisconnected(deviceId: DeviceId): BleSubscription {\n const disconnectionSubscription = this._manager.onDeviceDisconnected(\n deviceId,\n (error, d) => {\n this._handleDeviceDisconnected(error, d);\n disconnectionSubscription.remove();\n },\n );\n return disconnectionSubscription;\n }\n\n private async tryToReconnect(deviceId: DeviceId) {\n this._logger.debug(\"[tryToReconnect] Called\", {\n data: { deviceId },\n });\n let reconnectionTryCount = 0;\n\n await this._stopScanning();\n await this._safeCancel(deviceId);\n\n const reconnect$ = defer(async () => {\n let disconnectionSubscription: BleSubscription | null = null;\n reconnectionTryCount++;\n try {\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device`,\n {\n data: { id: deviceId },\n },\n );\n const reconnectedDevice = await this._manager.connectToDevice(\n deviceId,\n { requestMTU: DEFAULT_MTU, timeout: 2000 },\n );\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Established connection to device`,\n {\n data: { id: deviceId },\n },\n );\n const usableReconnectedDevice =\n await reconnectedDevice.discoverAllServicesAndCharacteristics();\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Discovered all services and characteristics`,\n { data: { usableReconnectedDevice } },\n );\n disconnectionSubscription = this._listenToDeviceDisconnected(deviceId);\n await this._handleDeviceReconnected(usableReconnectedDevice);\n return usableReconnectedDevice;\n } catch (e) {\n this._logger.warn(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device failed`,\n {\n data: { e },\n },\n );\n disconnectionSubscription?.remove();\n await this._stopScanning();\n await this._safeCancel(deviceId);\n throw e;\n }\n }).pipe(retry(5));\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Fully reconnected to device (id=${d.id})`,\n ),\n complete: () => {\n this._logger.debug(\"[tryToReconnect] Completed\");\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n `[tryToReconnect] All reconnection attempts failed`,\n { data: { e } },\n );\n this._deviceConnectionsById.get(deviceId)?.closeConnection();\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The ddevice object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n return EitherAsync(async ({ liftEither, throwE }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const servicesUUIDs = (await device.services()).map((s) => s.uuid);\n\n const internalDevice = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return {\n id: device.id,\n bleDeviceInfos: info,\n };\n },\n Left: (error) => {\n this._logger.error(\n \"[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info\",\n {\n data: { error },\n },\n );\n\n return throwE(error);\n },\n });\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection().catch((e) => {\n this._safeCancel(device.id);\n throw e;\n });\n\n deviceConnectionStateMachine.eventDeviceConnected();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n const connectedDevices = await this._manager.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\n );\n\n for (const device of connectedDevices) {\n if (device.id === deviceId) {\n try {\n await this._manager.cancelDeviceConnection(deviceId);\n } catch (e) {\n this._logger.error(\n \"[safeCancel] Error in cancelling device connection\",\n {\n data: { e },\n },\n );\n }\n }\n }\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA,OAAS,YAAAA,MAAgB,eACzB,OACE,YAAAC,EACA,gBAAAC,EAGA,SAAAC,MAEK,uBACP,OAKE,gCAAAC,EAOA,0BAAAC,EAEA,4BAAAC,EAIA,sBAAAC,MACK,kCACP,OAAS,UAAAC,EAAQ,eAAAC,EAAa,QAAAC,EAAM,SAAAC,EAAO,SAAAC,MAAa,YACxD,OACE,mBAAAC,EACA,SAAAC,EACA,YAAAC,EACA,SAAAC,EACA,QAAAC,EAEA,SAAAC,EAEA,aAAAC,EACA,OAAAC,EACA,gBAAAC,MACK,OAEP,OACE,kCAAAC,EACA,8BAAAC,EACA,yBAAAC,EACA,eAAAC,MACK,mBACP,OACE,mBAAAC,EACA,4BAAAC,EACA,iBAAAC,EACA,4BAAAC,EACA,2BAAAC,EACA,2BAAAC,MACK,oBAEP,OACE,mBAAAC,MAIK,iCAEA,MAAMC,GAA2B,SAOjC,MAAMC,EAAoC,CAY/C,YACmBC,EACAC,EAGAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAA+B,IAC/BC,EAEiDC,GAChE,IAAIxC,EAA6BwC,CAAI,EACtBC,EAGM,CAACD,EAAME,IAC5B,IAAId,EAAgBY,EAAME,CAAa,EACzC,CAnBiB,4BAAAX,EACA,2BAAAC,EAGA,wBAAAC,EACA,0BAAAC,EACA,cAAAC,EACA,eAAAC,EACA,yBAAAC,EACA,0BAAAC,EACA,0CAAAC,EAIA,8BAAAE,EAMjB,KAAK,QAAUT,EA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I,EAE3DkC,EAAiB,KAAK,uCAC1Bd,CACF,EAAE,OAAO,CACP,MAAQI,IACC,CACL,GAAIT,EAAO,GACX,eAAgBS,CAClB,GAEF,KAAOnB,IACL,KAAK,QAAQ,MACX,sFACA,CACE,KAAM,CAAE,MAAAA,CAAM,CAChB,CACF,EAEO0B,EAAO1B,CAAK,EAEvB,CAAC,EAEDgC,EAA6B,gBAAgB,CAC3C,OAAAtB,EACA,QAAS,KAAK,SACd,eAAAmB,CACF,CAAC,EAED,MAAMG,EAA6B,gBAAgB,EAAE,MAAO9B,GAAM,CAChE,WAAK,YAAYQ,EAAO,EAAE,EACpBR,CACR,CAAC,EAED8B,EAA6B,qBAAqB,CACpD,CAAC,EAAE,IAAI,CACT,CAEA,MAAc,YAAYE,EAAoB,CAE5C,GAAI,OAAO,KAAK,SAAS,wBAA2B,WAAY,CAC9D,MAAMlB,EAAmB,MAAM,KAAK,SAAS,iBAC3C,KAAK,uBAAuB,qBAAqB,CACnD,EAEA,UAAWN,KAAUM,EACnB,GAAIN,EAAO,KAAOwB,EAChB,GAAI,CACF,MAAM,KAAK,SAAS,uBAAuBA,CAAQ,CACrD,OAAShC,EAAG,CACV,KAAK,QAAQ,MACX,qDACA,CACE,KAAM,CAAE,EAAAA,CAAE,CACZ,CACF,CACF,CAGN,CACF,CACF",
|
|
6
|
-
"names": ["Platform", "BleError", "BleErrorCode", "State", "DeviceConnectionStateMachine", "OpeningConnectionError", "TransportConnectedDevice", "UnknownDeviceError", "Either", "EitherAsync", "Left", "Maybe", "Right", "BehaviorSubject", "defer", "finalize", "first", "from", "retry", "switchMap", "tap", "throttleTime", "BLE_DISCONNECT_TIMEOUT_ANDROID", "BLE_DISCONNECT_TIMEOUT_IOS", "CONNECTION_LOST_DELAY", "DEFAULT_MTU", "BleNotSupported", "BlePermissionsNotGranted", "BlePoweredOff", "DeviceConnectionNotFound", "NoDeviceModelFoundError", "PeerRemovedPairingError", "RNBleApduSender", "rnBleTransportIdentifier", "RNBleTransport", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_manager", "_platform", "_permissionsService", "_scanThrottleDelayMs", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "lastBleStateIsUnknown", "state", "s", "hasPermissions", "canStartScanning", "subject", "devicesById", "error", "rnDevice", "e", "interval", "devices", "internalScannedDevices", "eitherScannedDevices", "timestamp", "a", "b", "device", "d", "scannedDevices", "rawConnectedDevices", "eitherConnectedDevices", "servicesUUIDs", "connectedDevices", "serviceUUID", "bluetoothServiceInfo", "info", "
|
|
4
|
+
"sourcesContent": ["import { Platform } from \"react-native\";\nimport {\n BleError,\n BleErrorCode,\n type BleManager,\n type Device,\n State,\n type Subscription as BleSubscription,\n} from \"react-native-ble-plx\";\nimport {\n type ApduReceiverServiceFactory,\n type ApduSenderServiceFactory,\n type BleDeviceInfos,\n type ConnectError,\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n type DeviceId,\n type DeviceModelDataSource,\n type DisconnectHandler,\n type DmkError,\n type LoggerPublisherService,\n OpeningConnectionError,\n type Transport,\n TransportConnectedDevice,\n type TransportDeviceModel,\n type TransportDiscoveredDevice,\n type TransportIdentifier,\n UnknownDeviceError,\n} from \"@ledgerhq/device-management-kit\";\nimport { Either, EitherAsync, Left, Maybe, Right } from \"purify-ts\";\nimport {\n BehaviorSubject,\n defer,\n finalize,\n first,\n from,\n type Observable,\n retry,\n type Subscription,\n switchMap,\n tap,\n throttleTime,\n} from \"rxjs\";\n\nimport {\n BLE_DISCONNECT_TIMEOUT_ANDROID,\n BLE_DISCONNECT_TIMEOUT_IOS,\n CONNECTION_LOST_DELAY,\n DEFAULT_MTU,\n} from \"@api/model/Const\";\nimport {\n BleNotSupported,\n BlePermissionsNotGranted,\n BlePoweredOff,\n DeviceConnectionNotFound,\n NoDeviceModelFoundError,\n PeerRemovedPairingError,\n} from \"@api/model/Errors\";\nimport { type PermissionsService } from \"@api/permissions/PermissionsService\";\nimport {\n RNBleApduSender,\n type RNBleApduSenderConstructorArgs,\n type RNBleApduSenderDependencies,\n type RNBleInternalDevice,\n} from \"@api/transport/RNBleApduSender\";\n\nexport const rnBleTransportIdentifier = \"RN_BLE\";\n\ntype InternalScannedDevice = {\n device: Device;\n timestamp: number;\n};\n\nexport class RNBleTransport implements Transport {\n private _logger: LoggerPublisherService;\n private _deviceConnectionsById: Map<\n DeviceId,\n DeviceConnectionStateMachine<RNBleApduSenderDependencies>\n >;\n // private readonly _manager: BleManager;\n private readonly identifier: TransportIdentifier = \"RN_BLE\";\n private _reconnectionSubscription: Maybe<Subscription>;\n private readonly _bleStateSubject: BehaviorSubject<State> =\n new BehaviorSubject<State>(State.Unknown);\n\n constructor(\n private readonly _deviceModelDataSource: DeviceModelDataSource,\n private readonly _loggerServiceFactory: (\n tag: string,\n ) => LoggerPublisherService,\n private readonly _apduSenderFactory: ApduSenderServiceFactory,\n private readonly _apduReceiverFactory: ApduReceiverServiceFactory,\n private readonly _manager: BleManager,\n private readonly _platform: Platform,\n private readonly _permissionsService: PermissionsService,\n private readonly _scanThrottleDelayMs: number = 1000,\n private readonly _deviceConnectionStateMachineFactory: (\n args: DeviceConnectionStateMachineParams<RNBleApduSenderDependencies>,\n ) => DeviceConnectionStateMachine<RNBleApduSenderDependencies> = (args) =>\n new DeviceConnectionStateMachine(args),\n private readonly _deviceApduSenderFactory: (\n args: RNBleApduSenderConstructorArgs,\n loggerFactory: (tag: string) => LoggerPublisherService,\n ) => RNBleApduSender = (args, loggerFactory) =>\n new RNBleApduSender(args, loggerFactory),\n ) {\n this._logger = _loggerServiceFactory(\"ReactNativeBleTransport\");\n this._deviceConnectionsById = new Map();\n this._reconnectionSubscription = Maybe.zero();\n // FIXME: we should have a destroy method to unregister the onStateChange listener\n let lastBleStateIsUnknown = false;\n this._manager.onStateChange((state) => {\n this._logger.debug(`[manager.onStateChange] called with state: ${state}`);\n this._bleStateSubject.next(state);\n lastBleStateIsUnknown = state === State.Unknown;\n if (lastBleStateIsUnknown) {\n // There seems to be a bug in the library where the state is not updated after going in an Unknown state...\n this._logger.debug(\n `[manager.onStateChange] forcing state update from \"Unknown\"`,\n );\n this._manager.state().then((s) => {\n if (lastBleStateIsUnknown) {\n this._logger.debug(\n `[manager.onStateChange] forcing state update to: \"${s}\"`,\n );\n this._bleStateSubject.next(s);\n }\n });\n }\n }, true);\n }\n\n /** Exposed for testing purposes */\n observeBleState(): Observable<State> {\n return this._bleStateSubject.asObservable();\n }\n\n /**\n * Not implemented for now as the return signature is not really usable.\n * Use listenToAvailableDevices instead.\n */\n startDiscovering(): Observable<TransportDiscoveredDevice> {\n return from([]);\n }\n\n /**\n * Stops the device scanning operation currently in progress.\n *\n * @return {Promise<void>} A promise that resolves once the device scanning has been successfully stopped.\n */\n async stopDiscovering(): Promise<void> {\n await this._stopScanning();\n }\n\n private _scannedDevicesSubject: BehaviorSubject<InternalScannedDevice[]> =\n new BehaviorSubject<InternalScannedDevice[]>([]);\n private _startedScanningSubscriber: Subscription | undefined = undefined;\n\n /**\n * Returns an observable that emits a value when the prerequisites for scanning are met.\n * The prerequisites are:\n * - BLE should be supported. If not, it will throw an error.\n * - Permissions should be granted. If not, it request them, if it fails, it will throw an error.\n * - BLE state should be PoweredOn.\n * - If BLE state is undetermined (Unknown or Resetting), it will wait for the state to be updated.\n * - For other states, it will throw an error.\n */\n private _waitForScanningPrerequisites() {\n return from([true]).pipe(\n tap(() => {\n if (!this.isSupported()) {\n throw new BleNotSupported(\"BLE not supported\");\n }\n this._logger.debug(\n \"[waitForScanningPrerequisites] Prerequisite: isSupported=true\",\n );\n }),\n switchMap(async () => this.checkAndRequestPermissions()),\n tap((hasPermissions) => {\n this._logger.debug(\n `[_waitForScanningPrerequisites] Prerequisite: hasPermissions=${hasPermissions}`,\n );\n if (!hasPermissions) {\n throw new BlePermissionsNotGranted(\"Permissions not granted\");\n }\n }),\n switchMap(() => this.observeBleState()),\n first((state) => {\n /**\n * We wait for the BLE state to be PoweredOn, in case the current state is one of those:\n * - Unknown: temporary undetermined state which will quickly be updated\n * - Resetting: temporary undetermined state which will quickly be updated\n */\n const canStartScanning = state === State.PoweredOn;\n this._logger.info(\n `[waitForScanningPrerequisites] Prerequisite: BLE state=${state}, canStartScanning=${canStartScanning}`,\n );\n if (state === State.PoweredOff) {\n throw new BlePoweredOff();\n } else if (state === State.Unauthorized) {\n throw new BlePermissionsNotGranted('Ble State is \"Unauthorized\"');\n } else if (state === State.Unsupported) {\n throw new BleNotSupported();\n }\n return canStartScanning;\n }),\n );\n }\n\n private _startScanning() {\n if (this._startedScanningSubscriber != undefined) {\n this._logger.info(\"[startScanning] !! startScanning already started\");\n return;\n }\n\n //Reset the scanned devices list as new scan will start\n this._scannedDevicesSubject.next([]);\n\n this._logger.info(\"[startScanning] startScanning\");\n\n this._startedScanningSubscriber = from([true])\n .pipe(\n switchMap(() => {\n const subject = new BehaviorSubject<InternalScannedDevice[]>([]);\n const devicesById = new Map<string, InternalScannedDevice>();\n\n this._logger.info(\"[startScanning] startDeviceScan\");\n this._manager\n .startDeviceScan(\n this._deviceModelDataSource.getBluetoothServices(),\n { allowDuplicates: true },\n (error, rnDevice) => {\n if (error) {\n this._logger.error(\n \"[startScanning] Error in startDeviceScan callback\",\n {\n data: { error, rnDevice },\n },\n );\n subject.error(error);\n return;\n }\n if (!rnDevice) {\n this._logger.warn(\n \"[startScanning] Null Device in startDeviceScan callback\",\n {\n data: { rnDevice },\n },\n );\n subject.error(\n new Error(\"Null device in startDeviceScan callback\"),\n );\n return;\n }\n devicesById.set(rnDevice.id, {\n device: rnDevice,\n timestamp: Date.now(),\n });\n subject.next(Array.from(devicesById.values()));\n },\n )\n .catch((e) => {\n subject.error(e);\n this._logger.error(\n \"[startScanning] Error while calling startDeviceScan\",\n {\n data: { error: e },\n },\n );\n });\n\n this._logger.debug(\"[startScanning] after startDeviceScan\");\n\n /**\n * In case there is no update from startDeviceScan, we still emit the\n * list of devices. This is useful for instance if there is only 1 device\n * in the vicinity and it just got turned off. It will not \"advertise\"\n * anymore so startDeviceScan won't trigger.\n */\n const interval = setInterval(() => {\n subject.next(Array.from(devicesById.values()));\n }, 1000);\n\n return subject.pipe(\n finalize(() => {\n this._logger.debug(\"[startScanning] finalize\");\n subject.complete();\n clearInterval(interval);\n this._stopScanning();\n }),\n );\n }),\n throttleTime(this._scanThrottleDelayMs),\n )\n .subscribe({\n next: (devices) => {\n this._scannedDevicesSubject.next(devices);\n },\n error: (error) => {\n this._logger.error(\"[startScanning] Error while scanning\", {\n data: { error },\n });\n this._scannedDevicesSubject.error(error);\n },\n });\n }\n\n private async _stopScanning(): Promise<void> {\n this._logger.debug(\"[stopScanning] stopScanning\");\n await this._manager.stopDeviceScan();\n //Stop listening the observable from this._startScanning()\n this._startedScanningSubscriber?.unsubscribe();\n this._startedScanningSubscriber = undefined;\n this._scannedDevicesSubject.complete();\n this._scannedDevicesSubject = new BehaviorSubject<InternalScannedDevice[]>(\n [],\n );\n\n return;\n }\n\n /**\n * Listens to known devices and emits updates when new devices are discovered or when properties of existing devices are updated.\n *\n * @return {Observable<TransportDiscoveredDevice[]>} An observable stream of discovered devices, containing device information as an array of TransportDiscoveredDevice objects.\n */\n listenToAvailableDevices(): Observable<TransportDiscoveredDevice[]> {\n return this._waitForScanningPrerequisites().pipe(\n tap(() => this._startScanning()),\n switchMap(() => this._scannedDevicesSubject),\n switchMap(async (internalScannedDevices) => {\n const eitherScannedDevices = internalScannedDevices\n .filter(\n ({ timestamp }) => timestamp > Date.now() - CONNECTION_LOST_DELAY,\n )\n .sort(\n (a, b) =>\n (b.device.rssi ?? -Infinity) - (a.device.rssi ?? -Infinity), // RSSI is a negative value and the higher, the stronger the signal\n )\n .map(({ device }) =>\n this._mapDeviceToTransportDiscoveredDevice(\n device,\n device.serviceUUIDs,\n ),\n )\n .filter((d) => !!d);\n\n const scannedDevices = Either.rights(eitherScannedDevices);\n\n const rawConnectedDevices = await this._manager\n .connectedDevices(this._deviceModelDataSource.getBluetoothServices())\n .catch((e) => {\n this._logger.error(\n \"[listenToAvailableDevices] Error calling manager.connectedDevices\",\n {\n data: { error: e },\n },\n );\n throw e;\n });\n\n const eitherConnectedDevices = await Promise.all(\n rawConnectedDevices.map(async (device) => {\n try {\n const services = await device.services();\n const servicesUUIDs = services.map((s) => s.uuid);\n return this._mapDeviceToTransportDiscoveredDevice(\n device,\n servicesUUIDs,\n );\n } catch (e) {\n this._logger.error(\n \"[listenToAvailableDevices] Error in mapping device to transport discovered device\",\n {\n data: { e },\n },\n );\n return Left(\n new NoDeviceModelFoundError(\n `Error in mapping device to transport discovered device: ${e}`,\n ),\n );\n }\n }),\n );\n\n const connectedDevices = Either.rights(eitherConnectedDevices);\n\n this._logger.debug(\"[listenToAvailableDevices]\", {\n data: {\n rawConnectedDevices: rawConnectedDevices.map((d) => d.name),\n connectedDevices: connectedDevices.map((d) => d.name),\n scannedDevices: scannedDevices.map((d) => d.name),\n },\n });\n\n /** We return both connected and scanned devices, as scanned devices don't include connected devices */\n return [...connectedDevices, ...scannedDevices];\n }),\n );\n }\n\n private _mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, BleDeviceInfos> {\n for (const serviceUUID of servicesUUIDs || []) {\n const bluetoothServiceInfo =\n this._deviceModelDataSource.getBluetoothServicesInfos()[serviceUUID];\n if (bluetoothServiceInfo) return Right(bluetoothServiceInfo);\n }\n\n return Left(\n new NoDeviceModelFoundError(\n `No device model found for [uuids=${servicesUUIDs}]`,\n ),\n );\n }\n\n private _mapServicesUUIDsToDeviceModel(\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDeviceModel> {\n const bluetoothServiceInfo =\n this._mapServicesUUIDsToBluetoothDeviceInfo(servicesUUIDs);\n return bluetoothServiceInfo.map((info) => info.deviceModel);\n }\n\n private _mapDeviceToTransportDiscoveredDevice(\n device: Device,\n servicesUUIDs: string[] | null | undefined,\n ): Either<NoDeviceModelFoundError, TransportDiscoveredDevice> {\n const deviceModel = this._mapServicesUUIDsToDeviceModel(servicesUUIDs);\n return deviceModel.map((model) => ({\n id: device.id,\n name: device.localName || device.name || \"\",\n deviceModel: model,\n transport: this.identifier,\n rssi: device.rssi || undefined,\n }));\n }\n\n /**\n * Establishes a connection to a device and configures the necessary parameters for communication.\n *\n * @param {Object} params - An object containing parameters required for the connection.\n * @param {DeviceId} params.deviceId - The unique identifier of the device to connect to.\n * @param {DisconnectHandler} params.onDisconnect - A callback function to handle device disconnection.\n * @returns {Promise<Either<ConnectError, TransportConnectedDevice>>} A promise resolving to either a connection error or a successfully connected device.\n */\n async connect(params: {\n deviceId: DeviceId;\n onDisconnect: DisconnectHandler;\n }): Promise<Either<ConnectError, TransportConnectedDevice>> {\n this._logger.debug(\"[connect] Called\", {\n data: { deviceId: params.deviceId },\n });\n const existing = this._deviceConnectionsById.get(params.deviceId);\n if (existing) {\n this._logger.debug(\"[connect] Existing device connection found\", {\n data: { deviceId: params.deviceId },\n });\n const dependencies = existing.getDependencies();\n const deviceModel =\n dependencies.internalDevice.bleDeviceInfos.deviceModel;\n const deviceName =\n dependencies.device.localName || dependencies.device.name || undefined;\n return Right(\n new TransportConnectedDevice({\n id: params.deviceId,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...a) => existing.sendApdu(...a),\n transport: this.identifier,\n name: deviceName,\n }),\n );\n }\n\n this._logger.debug(\n \"[connect] No existing device connection found, establishing one\",\n {\n data: { deviceId: params.deviceId },\n },\n );\n\n await this._stopScanning();\n await this._safeCancel(params.deviceId);\n\n return EitherAsync<ConnectError, TransportConnectedDevice>(\n async ({ throwE }) => {\n let device: Device;\n let servicesUUIDs: string[] = [];\n try {\n await this._manager.connectToDevice(params.deviceId, {\n requestMTU: DEFAULT_MTU,\n });\n\n device =\n await this._manager.discoverAllServicesAndCharacteristicsForDevice(\n params.deviceId,\n );\n\n servicesUUIDs = (await device.services()).map((s) => s.uuid);\n } catch (error) {\n if (\n error instanceof BleError &&\n (error.iosErrorCode as number) === 14\n ) {\n /**\n * This happens when the Ledger device reset its pairing, but the\n * iOS system still has that device paired.\n */\n return throwE(new PeerRemovedPairingError(error));\n }\n if (\n error instanceof BleError &&\n error.errorCode === BleErrorCode.OperationCancelled &&\n Platform.OS === \"android\"\n ) {\n return throwE(new PeerRemovedPairingError(error));\n }\n return throwE(new OpeningConnectionError(error));\n }\n\n const disconnectionSubscription = this._listenToDeviceDisconnected(\n params.deviceId,\n );\n\n const bleDeviceInfos = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return info;\n },\n Left: (error) => {\n return throwE(new OpeningConnectionError(error));\n },\n });\n\n const deviceModel = bleDeviceInfos.deviceModel;\n\n const internalDevice: RNBleInternalDevice = {\n id: device.id,\n bleDeviceInfos,\n };\n\n const deviceApduSender = this._deviceApduSenderFactory(\n {\n apduSenderFactory: this._apduSenderFactory,\n apduReceiverFactory: this._apduReceiverFactory,\n dependencies: { device, internalDevice, manager: this._manager },\n },\n this._loggerServiceFactory,\n );\n\n const reconnectionTimeout =\n Platform.OS === \"ios\"\n ? BLE_DISCONNECT_TIMEOUT_IOS\n : BLE_DISCONNECT_TIMEOUT_ANDROID;\n\n const deviceConnectionStateMachine =\n this._deviceConnectionStateMachineFactory({\n deviceId: params.deviceId,\n deviceApduSender,\n timeoutDuration: reconnectionTimeout,\n tryToReconnect: () => this.tryToReconnect(params.deviceId),\n onTerminated: async () => {\n this._logger.debug(\"[onTerminated]\", {\n data: { deviceId: params.deviceId },\n });\n try {\n await this._safeCancel(params.deviceId);\n } catch (e) {\n this._logger.error(\n \"[onTerminated] Error in termination of device connection\",\n { data: { e } },\n );\n } finally {\n this._deviceConnectionsById.delete(params.deviceId);\n this._reconnectionSubscription.ifJust((sub) => {\n sub.unsubscribe();\n this._reconnectionSubscription = Maybe.zero();\n });\n this._logger.debug(\"[onTerminated] signaling disconnection\", {\n data: { deviceId: params.deviceId },\n });\n params.onDisconnect(params.deviceId);\n }\n },\n });\n\n await deviceApduSender.setupConnection().catch((e) => {\n this._safeCancel(params.deviceId);\n disconnectionSubscription.remove();\n throw e;\n });\n\n this._deviceConnectionsById.set(\n params.deviceId,\n deviceConnectionStateMachine,\n );\n\n return new TransportConnectedDevice({\n id: device.id,\n deviceModel: deviceModel,\n type: \"BLE\",\n sendApdu: (...args) => deviceConnectionStateMachine.sendApdu(...args),\n transport: this.identifier,\n name: device.localName || device.name || undefined,\n });\n },\n ).run();\n }\n\n /**\n * Terminates the connection with the connected device and cleans up related resources.\n *\n * @param {TransportConnectedDevice} params.connectedDevice - The connected device to be disconnected.\n * @return {Promise<Either<DmkError, void>>} A promise resolving to either a success (void) or a failure (DmkError) value.\n */\n async disconnect(params: {\n connectedDevice: TransportConnectedDevice;\n }): Promise<Either<DmkError, void>> {\n const deviceId = params.connectedDevice.id;\n const deviceConnection = this._deviceConnectionsById.get(deviceId);\n if (!deviceConnection) {\n throw new UnknownDeviceError(\n `No connected device found with id ${deviceId}`,\n );\n }\n\n deviceConnection.closeConnection();\n\n return Promise.resolve(Right(undefined));\n }\n\n /**\n * Determines if the feature or permission is supported.\n *\n * This method evaluates the current state of the `_isSupported` property to determine\n * whether the relevant feature is supported or throws an error if its state has\n * not been initialized properly.\n *\n * @return {boolean} Returns `true` if the feature is supported, otherwise `false`.\n * Throws an error if the `_isSupported` property has not been initialized.\n */\n isSupported(): boolean {\n return [\"android\", \"ios\"].includes(this._platform.OS);\n }\n\n /**\n * Retrieves the transport identifier associated with the object.\n *\n * @return {TransportIdentifier} The transport identifier.\n */\n getIdentifier(): TransportIdentifier {\n return this.identifier;\n }\n\n /**\n * Checks if the necessary permissions are granted and requests them if not.\n */\n async checkAndRequestPermissions(): Promise<boolean> {\n this._logger.debug(\"[checkAndRequestPermissions] Called\");\n\n const checkResult =\n await this._permissionsService.checkRequiredPermissions();\n if (checkResult) return true;\n\n const requestResult =\n await this._permissionsService.requestRequiredPermissions();\n return requestResult;\n }\n\n /**\n * Handles the event when a Bluetooth device gets disconnected. This method attempts\n * to reconnect to the device, retries a certain number of times on failure, and\n * invokes a callback if the reconnection does not succeed.\n *\n * @param {BleError | null} error - The error object representing the reason for the disconnection, or null if no error occurred.\n * @param {Device | null} device - The Bluetooth device that was disconnected, or null if no device is provided.\n * @return {void}\n */\n private _handleDeviceDisconnected(\n error: BleError | null,\n device: Device | null,\n ) {\n this._logger.debug(\"[_handleDeviceDisconnected]\", {\n data: { error, device },\n });\n if (!device) {\n this._logger.debug(\n \"[_handleDeviceDisconnected] disconnected handler didn't find device\",\n );\n return;\n }\n if (!device?.id || !this._deviceConnectionsById.has(device?.id)) return;\n if (error) {\n this._logger.error(\"device disconnected error\", {\n data: { error, device },\n });\n return;\n }\n const deviceId = device.id;\n\n Maybe.fromNullable(this._deviceConnectionsById.get(deviceId)).map(\n (deviceConnection) => deviceConnection.eventDeviceDisconnected(),\n );\n }\n\n private _listenToDeviceDisconnected(deviceId: DeviceId): BleSubscription {\n const disconnectionSubscription = this._manager.onDeviceDisconnected(\n deviceId,\n (error, d) => {\n this._handleDeviceDisconnected(error, d);\n disconnectionSubscription.remove();\n },\n );\n return disconnectionSubscription;\n }\n\n private async tryToReconnect(deviceId: DeviceId) {\n this._logger.debug(\"[tryToReconnect] Called\", {\n data: { deviceId },\n });\n let reconnectionTryCount = 0;\n\n await this._stopScanning();\n await this._safeCancel(deviceId);\n\n const reconnect$ = defer(async () => {\n let disconnectionSubscription: BleSubscription | null = null;\n reconnectionTryCount++;\n try {\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device`,\n {\n data: { id: deviceId },\n },\n );\n const reconnectedDevice = await this._manager.connectToDevice(\n deviceId,\n { requestMTU: DEFAULT_MTU, timeout: 2000 },\n );\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Established connection to device`,\n {\n data: { id: deviceId },\n },\n );\n const usableReconnectedDevice =\n await reconnectedDevice.discoverAllServicesAndCharacteristics();\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Discovered all services and characteristics`,\n { data: { usableReconnectedDevice } },\n );\n disconnectionSubscription = this._listenToDeviceDisconnected(deviceId);\n await this._handleDeviceReconnected(usableReconnectedDevice);\n return usableReconnectedDevice;\n } catch (e) {\n this._logger.warn(\n `[tryToReconnect](try=${reconnectionTryCount}) Reconnecting to device failed`,\n {\n data: { e },\n },\n );\n disconnectionSubscription?.remove();\n await this._stopScanning();\n await this._safeCancel(deviceId);\n throw e;\n }\n }).pipe(retry(5));\n\n this._reconnectionSubscription = Maybe.of(\n reconnect$.subscribe({\n next: (d) =>\n this._logger.debug(\n `[tryToReconnect](try=${reconnectionTryCount}) Fully reconnected to device (id=${d.id})`,\n ),\n complete: () => {\n this._logger.debug(\"[tryToReconnect] Completed\");\n this._reconnectionSubscription = Maybe.zero();\n },\n error: (e) => {\n this._logger.error(\n `[tryToReconnect] All reconnection attempts failed`,\n { data: { e } },\n );\n this._deviceConnectionsById.get(deviceId)?.closeConnection();\n this._reconnectionSubscription = Maybe.zero();\n },\n }),\n );\n }\n\n /**\n * Handles the reconnection of a device. Configures the device connection and its corresponding\n * internal device upon reconnection, including updating the connection state, registering\n * callbacks for write and monitor operations, and initiating a reconnect operation.\n *\n * @param {Device} device - The ddevice object that has been reconnected. Contains device details,\n * such as the device ID.\n * @return {Promise<Either<DeviceConnectionNotFound | InternalDeviceNotFound, void>>} A promise that completes when the device reconnection has been fully\n * configured. Resolves with no value or rejects if an error occurs during\n * the reconnection process.\n */\n private async _handleDeviceReconnected(device: Device) {\n const errorOrDeviceConnection = Maybe.fromNullable(\n this._deviceConnectionsById.get(device.id),\n ).toEither(new DeviceConnectionNotFound());\n\n return EitherAsync(async ({ liftEither, throwE }) => {\n const deviceConnectionStateMachine = await liftEither(\n errorOrDeviceConnection,\n );\n\n const servicesUUIDs = (await device.services()).map((s) => s.uuid);\n\n const internalDevice = this._mapServicesUUIDsToBluetoothDeviceInfo(\n servicesUUIDs,\n ).caseOf({\n Right: (info) => {\n return {\n id: device.id,\n bleDeviceInfos: info,\n };\n },\n Left: (error) => {\n this._logger.error(\n \"[_handleDeviceReconnected] Error in mapping services UUIDs to Bluetooth device info\",\n {\n data: { error },\n },\n );\n\n return throwE(error);\n },\n });\n\n deviceConnectionStateMachine.setDependencies({\n device,\n manager: this._manager,\n internalDevice,\n });\n\n await deviceConnectionStateMachine.setupConnection().catch((e) => {\n this._safeCancel(device.id);\n throw e;\n });\n\n deviceConnectionStateMachine.eventDeviceConnected();\n }).run();\n }\n\n private async _safeCancel(deviceId: DeviceId) {\n // only invoke if the BleManager under test actually has it\n if (typeof this._manager.cancelDeviceConnection === \"function\") {\n const connectedDevices = await this._manager.connectedDevices(\n this._deviceModelDataSource.getBluetoothServices(),\n );\n\n for (const device of connectedDevices) {\n if (device.id === deviceId) {\n try {\n await this._manager.cancelDeviceConnection(deviceId);\n } catch (e) {\n this._logger.error(\n \"[safeCancel] Error in cancelling device connection\",\n {\n data: { e },\n },\n );\n }\n }\n }\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,YAAAA,MAAgB,eACzB,OACE,YAAAC,EACA,gBAAAC,EAGA,SAAAC,MAEK,uBACP,OAKE,gCAAAC,EAOA,0BAAAC,EAEA,4BAAAC,EAIA,sBAAAC,MACK,kCACP,OAAS,UAAAC,EAAQ,eAAAC,EAAa,QAAAC,EAAM,SAAAC,EAAO,SAAAC,MAAa,YACxD,OACE,mBAAAC,EACA,SAAAC,EACA,YAAAC,EACA,SAAAC,EACA,QAAAC,EAEA,SAAAC,EAEA,aAAAC,EACA,OAAAC,EACA,gBAAAC,MACK,OAEP,OACE,kCAAAC,EACA,8BAAAC,EACA,yBAAAC,EACA,eAAAC,MACK,mBACP,OACE,mBAAAC,EACA,4BAAAC,EACA,iBAAAC,EACA,4BAAAC,EACA,2BAAAC,EACA,2BAAAC,MACK,oBAEP,OACE,mBAAAC,MAIK,iCAEA,MAAMC,GAA2B,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M,EAAE,IAAI,EAE3DmB,EAAiB,KAAK,uCAC1Bd,CACF,EAAE,OAAO,CACP,MAAQI,IACC,CACL,GAAIT,EAAO,GACX,eAAgBS,CAClB,GAEF,KAAOnB,IACL,KAAK,QAAQ,MACX,sFACA,CACE,KAAM,CAAE,MAAAA,CAAM,CAChB,CACF,EAEO0B,EAAO1B,CAAK,EAEvB,CAAC,EAEDgC,EAA6B,gBAAgB,CAC3C,OAAAtB,EACA,QAAS,KAAK,SACd,eAAAmB,CACF,CAAC,EAED,MAAMG,EAA6B,gBAAgB,EAAE,MAAO9B,GAAM,CAChE,WAAK,YAAYQ,EAAO,EAAE,EACpBR,CACR,CAAC,EAED8B,EAA6B,qBAAqB,CACpD,CAAC,EAAE,IAAI,CACT,CAEA,MAAc,YAAYE,EAAoB,CAE5C,GAAI,OAAO,KAAK,SAAS,wBAA2B,WAAY,CAC9D,MAAMlB,EAAmB,MAAM,KAAK,SAAS,iBAC3C,KAAK,uBAAuB,qBAAqB,CACnD,EAEA,UAAWN,KAAUM,EACnB,GAAIN,EAAO,KAAOwB,EAChB,GAAI,CACF,MAAM,KAAK,SAAS,uBAAuBA,CAAQ,CACrD,OAAShC,EAAG,CACV,KAAK,QAAQ,MACX,qDACA,CACE,KAAM,CAAE,EAAAA,CAAE,CACZ,CACF,CACF,CAGN,CACF,CACF",
|
|
6
|
+
"names": ["Platform", "BleError", "BleErrorCode", "State", "DeviceConnectionStateMachine", "OpeningConnectionError", "TransportConnectedDevice", "UnknownDeviceError", "Either", "EitherAsync", "Left", "Maybe", "Right", "BehaviorSubject", "defer", "finalize", "first", "from", "retry", "switchMap", "tap", "throttleTime", "BLE_DISCONNECT_TIMEOUT_ANDROID", "BLE_DISCONNECT_TIMEOUT_IOS", "CONNECTION_LOST_DELAY", "DEFAULT_MTU", "BleNotSupported", "BlePermissionsNotGranted", "BlePoweredOff", "DeviceConnectionNotFound", "NoDeviceModelFoundError", "PeerRemovedPairingError", "RNBleApduSender", "rnBleTransportIdentifier", "RNBleTransport", "_deviceModelDataSource", "_loggerServiceFactory", "_apduSenderFactory", "_apduReceiverFactory", "_manager", "_platform", "_permissionsService", "_scanThrottleDelayMs", "_deviceConnectionStateMachineFactory", "args", "_deviceApduSenderFactory", "loggerFactory", "lastBleStateIsUnknown", "state", "s", "hasPermissions", "canStartScanning", "subject", "devicesById", "error", "rnDevice", "e", "interval", "devices", "internalScannedDevices", "eitherScannedDevices", "timestamp", "a", "b", "device", "d", "scannedDevices", "rawConnectedDevices", "eitherConnectedDevices", "servicesUUIDs", "connectedDevices", "serviceUUID", "bluetoothServiceInfo", "info", "model", "params", "existing", "dependencies", "deviceModel", "deviceName", "throwE", "disconnectionSubscription", "bleDeviceInfos", "internalDevice", "deviceApduSender", "reconnectionTimeout", "deviceConnectionStateMachine", "sub", "deviceId", "deviceConnection", "reconnectionTryCount", "reconnect$", "reconnectedDevice", "usableReconnectedDevice", "errorOrDeviceConnection", "liftEither"]
|
|
7
7
|
}
|