@@ -2,6 +2,8 @@ package uk.co.playerdata.reactnativemcumanager
22
33import android.bluetooth.BluetoothAdapter
44import android.bluetooth.BluetoothDevice
5+ import android.bluetooth.BluetoothManager
6+ import android.content.Context
57import android.net.Uri
68import android.util.Log
79import expo.modules.kotlin.Promise
@@ -27,22 +29,24 @@ class UpdateOptions : Record {
2729 @Field val upgradeMode: Int? = null
2830}
2931
30- class ReactNativeMcuManagerModule : Module () {
31- private val bluetoothAdapter: BluetoothAdapter ? = BluetoothAdapter .getDefaultAdapter()
32+ class ReactNativeMcuManagerModule () : Module() {
3233 private val upgrades: MutableMap <String , DeviceUpgrade > = mutableMapOf ()
3334 private val context
3435 get() = requireNotNull(appContext.reactContext) { " React Application Context is null" }
3536
37+ private fun getBluetoothDevice (macAddress : String? ): BluetoothDevice {
38+ val bluetoothManager = context.getSystemService(Context .BLUETOOTH_SERVICE ) as BluetoothManager
39+ val adapter = bluetoothManager?.adapter ? : throw Exception (" No bluetooth adapter" )
40+
41+ return adapter.getRemoteDevice(macAddress)
42+ }
43+
3644 override fun definition () = ModuleDefinition {
3745 Name (MODULE_NAME )
3846
3947 AsyncFunction (" eraseImage" ) { macAddress: String? , promise: Promise ->
40- if (this @ReactNativeMcuManagerModule.bluetoothAdapter == null ) {
41- throw Exception (" No bluetooth adapter" )
42- }
43-
4448 try {
45- val device: BluetoothDevice = bluetoothAdapter.getRemoteDevice (macAddress)
49+ val device: BluetoothDevice = getBluetoothDevice (macAddress)
4650
4751 val transport = McuMgrBleTransport (context, device)
4852 transport.connect(device).timeout(60000 ).await()
@@ -63,15 +67,11 @@ class ReactNativeMcuManagerModule : Module() {
6367 updateOptions: UpdateOptions ,
6468 progressCallback: JavaScriptFunction <Unit >,
6569 stateCallback: JavaScriptFunction <Unit > ->
66- if (this @ReactNativeMcuManagerModule.bluetoothAdapter == null ) {
67- throw Exception (" No bluetooth adapter" )
68- }
69-
7070 if (upgrades.contains(id)) {
7171 throw Exception (" Update ID already present" )
7272 }
7373
74- val device: BluetoothDevice = bluetoothAdapter.getRemoteDevice (macAddress)
74+ val device: BluetoothDevice = getBluetoothDevice (macAddress)
7575 val updateFileUri = Uri .parse(updateFileUriString)
7676
7777 val upgrade = DeviceUpgrade (
@@ -128,11 +128,7 @@ class ReactNativeMcuManagerModule : Module() {
128128 }
129129
130130 AsyncFunction (" resetDevice" ) { macAddress: String , promise: Promise ->
131- if (this @ReactNativeMcuManagerModule.bluetoothAdapter == null ) {
132- throw Exception (" No bluetooth adapter" )
133- }
134-
135- val device: BluetoothDevice = bluetoothAdapter.getRemoteDevice(macAddress)
131+ val device: BluetoothDevice = getBluetoothDevice(macAddress)
136132
137133 val transport = McuMgrBleTransport (context, device)
138134 transport.connect(device).timeout(60000 ).await()
0 commit comments