Преглед изворни кода

蓝牙钥匙连接逻辑重构,引入未连接Mac集合和是否正在准备标志

Frankensteinly пре 10 месеци
родитељ
комит
39f1967668

+ 77 - 26
app/src/main/java/com/grkj/iscs/BusinessManager.kt

@@ -56,6 +56,14 @@ import pub.devrel.easypermissions.AfterPermissionGranted
  */
 object BusinessManager {
 
+    // 已连接的蓝牙钥匙集合(TODO 现在的和界面共用,是所有的,要改掉)
+    var deviceList: MutableList<BleBean> = mutableListOf()
+    // TODO 待连接的钥匙Mac集合
+    val notConnectedList: MutableList<String> = mutableListOf()
+    // TODO 是否正在进行准备流程
+    var isPreparing: Boolean = false
+
+    // TODO 归还设备是否需要登录
     var NEED_AUTH = true
 
     // 归还设备是否需要登录及角色验证
@@ -126,6 +134,8 @@ object BusinessManager {
                                         if (it != null && !it.macAddress.isNullOrEmpty()) {
                                             ModBusController.updateKeyMac(dockBean.addr.toInt(), keyBean.isLeft, it.macAddress)
                                             showKeyReturnDialog(it.macAddress, isLeft, dockBean.addr.toInt())
+                                            notConnectedList.add(it.macAddress)
+                                            connectKey()
                                         } else {
                                             ToastUtils.tip(R.string.get_key_info_fail)
                                         }
@@ -289,7 +299,7 @@ object BusinessManager {
     }
 
     /**
-     * 检查钥匙和锁具数量
+     * 检查钥匙和锁具数量 TODO 钥匙要是存在的、有RFID、有Mac、连接的
      *
      * @param needLockCount 需要的锁具的数量(可能在别的机柜取过)
      */
@@ -328,6 +338,38 @@ object BusinessManager {
     /****************************************** 蓝牙 ******************************************/
     /******************************************蓝牙通用准备******************************************/
 
+    /**
+     * 连接钥匙,单个mac走完prepare再进行下一个
+     */
+    fun connectKey() {
+        if (notConnectedList.isEmpty()) {
+            return
+        }
+        if (isPreparing) {
+            Executor.delayOnMain(1000) {
+                connectKey()
+            }
+        } else {
+            isPreparing = true
+            val mac = notConnectedList[0]
+            prepareBle(mac, ActivityUtils.currentActivity() as BaseActivity<*>, null) { isDone, bleBean ->
+                Executor.runOnMain {
+                    if (deviceList.any { it.bleDevice.mac == mac }) {
+                        notConnectedList.remove(mac)
+                    }
+                    isPreparing = false
+                    if (notConnectedList.isNotEmpty()) {
+                        connectKey()
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * @param loadingCallBack 是否显示loading、loading文字、流程是否结束
+     * @param prepareDoneCallBack 蓝牙连接是否成功、蓝牙连接对象
+     */
     fun prepareBle(
         mac: String,
         activity: AppCompatActivity,
@@ -352,43 +394,42 @@ object BusinessManager {
 
             override fun onScanStarted(success: Boolean) {
                 LogUtil.d("扫描开始:${success}")
-                BleUtil.instance?.deviceList?.clear()
+//                deviceList.clear()
             }
 
             override fun onScanning(bleDevice: BleDevice?) {
                 bleDevice?.let {
-                    Log.d("doScanBle", "扫描到的设备:${it.mac}")
+                    LogUtil.d("扫描到的设备:${it.mac}")
+                    // TODO 在这里进行连接
                     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                         if (!it.name.isNullOrBlank()) {
-                            BleUtil.instance?.deviceList?.add(BleBean(it))
-                        } else {
-
-                        }
+                            deviceList.add(BleBean(it))
+                            if (notConnectedList.any { itMac -> itMac == bleDevice.mac }) {
+                                doConnect(it, loadingCallBack, prepareDoneCallBack)
+                            } else {}
+                        } else {}
                     } else {
-                        BleUtil.instance?.deviceList?.add(BleBean(it))
+                        deviceList.add(BleBean(it))
                     }
                 }
             }
 
             override fun onScanFinished(scanResultList: MutableList<BleDevice>?) {
-                //                if (BleUtil.instance?.deviceList?.isEmpty() == true) {
+                //                if (deviceList.isEmpty() == true) {
 //                    ToastUtils.tip(R.string.ble_no_device_found)
 //                    loadingCallBack?.invoke(false, null, false)
 //                    return
 //                }
-//                BleUtil.instance?.getBleDeviceByMac(mac)?.bleDevice?.let {
+//                getBleDeviceByMac(mac)?.bleDevice?.let {
 //                    doConnect(it, loadingCallBack, prepareDoneCallBack)
 //                }
 //                scanResultList?.find { it.mac == mac }?.let {
                 loadingCallBack?.invoke(false, null, null)
-                if (BleUtil.instance?.deviceList?.isEmpty() == true) {
-                    ToastUtils.tip(R.string.ble_no_device_found)
+                if (deviceList.isEmpty()) {
+                    LogUtil.w("No ble device found")
                     loadingCallBack?.invoke(false, null, false)
                     return
                 }
-                BleUtil.instance?.getBleDeviceByMac(mac)?.bleDevice?.let {
-                    doConnect(it, loadingCallBack, prepareDoneCallBack)
-                }
             }
         })
     }
@@ -421,8 +462,7 @@ object BusinessManager {
                     LogUtil.i("onConnectSuccess : $bleDevice")
                     bleDevice?.let {
                         val bleBean = BleBean(it)
-                        ToastUtils.tip("连接成功")
-                        BleUtil.instance?.deviceList?.add(bleBean)
+                        deviceList.add(bleBean)
                         // 设置MTU
                         Executor.delayOnMain(200) {
                             BleUtil.instance?.setMtu(it)
@@ -437,8 +477,15 @@ object BusinessManager {
                 override fun onDisConnected(isActiveDisConnected: Boolean, device: BleDevice?, gatt: BluetoothGatt?, status: Int) {
                     loadingCallBack?.invoke(false, null, false)
                     ToastUtils.tip(CommonUtils.getStr(R.string.ble_disconnect))
-                    BleUtil.instance?.getBleDeviceByMac(device?.mac)?.let {
-                        BleUtil.instance?.deviceList?.remove(it)
+                    getBleDeviceByMac(device?.mac)?.let {
+                        deviceList.remove(it)
+                    }
+                    // TODO 待定
+                    if (!isActiveDisConnected) {
+                        // TODO 断开和重连之间最好间隔一段时间,否则可能会出现长时间连接不上的情况
+                        Executor.delayOnMain(200) {
+                            prepareBle(bleDevice.mac, ActivityUtils.currentActivity() as BaseActivity<*>, loadingCallBack, prepareDoneCallBack)
+                        }
                     }
                 }
             })
@@ -519,6 +566,10 @@ object BusinessManager {
 
     /******************************************蓝牙通用准备结束******************************************/
 
+    fun getBleDeviceByMac(mac: String?): BleBean? {
+        return deviceList.find { it.bleDevice.mac == mac }
+    }
+
     /**
      * 下发工作票
      */
@@ -532,7 +583,7 @@ object BusinessManager {
             if (done) {
                 Executor.delayOnMain(500) {
                     // TODO 蓝牙准备操作
-//                    val bleBean = BleUtil.instance?.getBleDeviceByMac(mac)
+//                    val bleBean = getBleDeviceByMac(mac)
 //                    if (bleBean == null) {
 //                        ToastUtils.tip(R.string.simple_key_is_not_connected)
 //                        return@delayOnMain
@@ -557,7 +608,7 @@ object BusinessManager {
             if (done) {
                 Executor.delayOnMain(500) {
                     // TODO 蓝牙准备操作
-//                    val bleBean = BleUtil.instance?.getBleDeviceByMac(mac)
+//                    val bleBean = getBleDeviceByMac(mac)
 //                    if (bleBean == null) {
 //                        ToastUtils.tip(R.string.simple_key_is_not_connected)
 //                        return@delayOnMain
@@ -661,7 +712,7 @@ object BusinessManager {
      */
     private fun handleToken(bleDevice: BleDevice, byteArray: ByteArray) {
         LogUtil.i("handleToken : ${byteArray.toHexStrings()}")
-        BleUtil.instance?.getBleDeviceByMac(bleDevice.mac)?.let {
+        getBleDeviceByMac(bleDevice.mac)?.let {
             it.token = byteArrayOf(byteArray[11], byteArray[12], byteArray[13], byteArray[14])
 
             println("Token 赋值 ${it.token?.toHexStrings()} : ${bleDevice.mac}")
@@ -701,7 +752,7 @@ object BusinessManager {
             if ((res == 0x00.toByte() || res == 0x02.toByte())) {
                 // TODO 要判断res
                 BleCmdManager.sendWorkTicket(
-                    BleUtil.instance?.getBleDeviceByMac(bleBean.bleDevice.mac)?.ticketSend!!,
+                    getBleDeviceByMac(bleBean.bleDevice.mac)?.ticketSend!!,
                     if (res == 0x00.toByte()) idx + 1 else idx,
                     bleBean.bleDevice,
                     object : CustomBleWriteCallback() {
@@ -750,7 +801,7 @@ object BusinessManager {
         val size = byteArray[10].toUByte() + byteArray[11].toUByte()
         println("工作票数据 : $total : $idx : $size")
         // 数据组装
-        BleUtil.instance?.getBleDeviceByMac(bleDevice.mac)?.let {
+        getBleDeviceByMac(bleDevice.mac)?.let {
             it.ticketStatus += byteArray.copyOfRange(12, 12 + size.toInt())
         }
         // TODO 缺少res处理
@@ -767,7 +818,7 @@ object BusinessManager {
             })
         } else {
             loadingCallBack?.invoke(false, "工作票完成状态读取完成", null)
-            BleUtil.instance?.getBleDeviceByMac(bleDevice.mac)?.let {
+            getBleDeviceByMac(bleDevice.mac)?.let {
                 println("工作票完成接收 : ${String(it.ticketStatus)}")
                 // TD:Ticket Done
                 loadingCallBack?.invoke(false, "TD${String(it.ticketStatus)}", true)
@@ -823,7 +874,7 @@ object BusinessManager {
      * 获取工作票完成情况分包
      */
     private fun getTicketStatusPart(idx: ByteArray, total: ByteArray, res: ByteArray, bleDevice: BleDevice, callback: CustomBleWriteCallback?) {
-        BleUtil.instance?.getBleDeviceByMac(bleDevice.mac)?.let {
+        getBleDeviceByMac(bleDevice.mac)?.let {
             BleUtil.instance?.write(it.bleDevice, cmd = BleCmdManager.assembleData(it, REQ_WORK_TICKET_RESULT_PART + idx + total + res), writeCallback = callback)
         }
     }

+ 0 - 7
app/src/main/java/com/grkj/iscs/ble/BleUtil.kt

@@ -20,9 +20,6 @@ import com.grkj.iscs.ble.BleConst.SERVICE_UUID
  */
 class BleUtil private constructor() {
 
-    // 已连接的设备集合(TODO 现在的和界面共用,是所有的,要改掉)
-    var deviceList: MutableList<BleBean> = mutableListOf()
-
     companion object {
         var instance: BleUtil? = null
             get() {
@@ -53,10 +50,6 @@ class BleUtil private constructor() {
         }
     }
 
-    fun getBleDeviceByMac(mac: String?): BleBean? {
-        return deviceList.find { it.bleDevice.mac == mac }
-    }
-
     fun scan(bleScanCallback: CustomBleScanCallback) {
         if (BleManager.getInstance().isSupportBle) {
             if (BleManager.getInstance().isBlueEnable) {