BusinessManager.kt 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138
  1. package com.grkj.iscs_mars
  2. //todo 所有蓝牙包替换com.clj. -> com.clj.
  3. import android.content.Context
  4. import android.content.Intent
  5. import androidx.appcompat.app.AppCompatActivity
  6. import androidx.lifecycle.MutableLiveData
  7. import com.clj.fastble.BleManager
  8. import com.clj.fastble.data.BleDevice
  9. import com.clj.fastble.exception.BleException
  10. import com.google.gson.Gson
  11. import com.grkj.iscs_mars.ble.BleBean
  12. import com.grkj.iscs_mars.ble.BleCmdManager
  13. import com.grkj.iscs_mars.ble.BleConnectionManager
  14. import com.grkj.iscs_mars.ble.BleConst
  15. import com.grkj.iscs_mars.ble.BleConst.STATUS_READY
  16. import com.grkj.iscs_mars.ble.BleConst.STATUS_WORK
  17. import com.grkj.iscs_mars.ble.BleUtil
  18. import com.grkj.iscs_mars.ble.CustomBleWriteCallback
  19. import com.grkj.iscs_mars.extentions.removeLeadingZeros
  20. import com.grkj.iscs_mars.extentions.serialNo
  21. import com.grkj.iscs_mars.extentions.startsWith
  22. import com.grkj.iscs_mars.extentions.toHexStrings
  23. import com.grkj.iscs_mars.modbus.DockBean
  24. import com.grkj.iscs_mars.modbus.ModBusController
  25. import com.grkj.iscs_mars.modbus.ModBusController.dockList
  26. import com.grkj.iscs_mars.modbus.ModBusController.getOneKey
  27. import com.grkj.iscs_mars.model.Constants
  28. import com.grkj.iscs_mars.model.Constants.USER_TYPE_LOCKER
  29. import com.grkj.iscs_mars.model.DeviceConst.DEVICE_TYPE_CARD
  30. import com.grkj.iscs_mars.model.DeviceConst.DEVICE_TYPE_FINGERPRINT
  31. import com.grkj.iscs_mars.model.DeviceConst.DEVICE_TYPE_KEY
  32. import com.grkj.iscs_mars.model.DeviceConst.DEVICE_TYPE_LOCK
  33. import com.grkj.iscs_mars.model.DeviceConst.DOCK_TYPE_ELEC_LOCK_BOARD
  34. import com.grkj.iscs_mars.model.DeviceConst.DOCK_TYPE_KEY
  35. import com.grkj.iscs_mars.model.DeviceConst.DOCK_TYPE_LOCK
  36. import com.grkj.iscs_mars.model.DeviceConst.DOCK_TYPE_PORTABLE
  37. import com.grkj.iscs_mars.model.DictAndSystemConstants
  38. import com.grkj.iscs_mars.model.ISCSDomainData
  39. import com.grkj.iscs_mars.model.bo.DeviceTakeUpdateBO
  40. import com.grkj.iscs_mars.model.bo.UpdateKeyReturnBO
  41. import com.grkj.iscs_mars.model.bo.WorkTicketGetBO
  42. import com.grkj.iscs_mars.model.bo.WorkTicketSendBO
  43. import com.grkj.iscs_mars.model.bo.WorkTicketSendBO.LockListBO
  44. import com.grkj.iscs_mars.model.eventmsg.CurrentModeMsg
  45. import com.grkj.iscs_mars.model.eventmsg.DeviceExceptionMsg
  46. import com.grkj.iscs_mars.model.eventmsg.DeviceTakeUpdateMsg
  47. import com.grkj.iscs_mars.model.eventmsg.LoadingMsg
  48. import com.grkj.iscs_mars.model.eventmsg.MsgEvent
  49. import com.grkj.iscs_mars.model.eventmsg.MsgEventConstants
  50. import com.grkj.iscs_mars.model.eventmsg.MsgEventConstants.MSG_EVENT_CURRENT_MODE
  51. import com.grkj.iscs_mars.model.eventmsg.MsgEventConstants.MSG_EVENT_DEVICE_EXCEPTION
  52. import com.grkj.iscs_mars.model.eventmsg.MsgEventConstants.MSG_EVENT_DEVICE_TAKE_UPDATE
  53. import com.grkj.iscs_mars.model.eventmsg.MsgEventConstants.MSG_EVENT_LOADING
  54. import com.grkj.iscs_mars.model.eventmsg.MsgEventConstants.MSG_EVENT_SWITCH_COLLECTION_UPDATE
  55. import com.grkj.iscs_mars.model.eventmsg.MsgEventConstants.MSG_EVENT_SWITCH_MODE
  56. import com.grkj.iscs_mars.model.eventmsg.MsgEventConstants.MSG_EVENT_UPDATE_TICKET_PROGRESS
  57. import com.grkj.iscs_mars.model.eventmsg.SwitchModeMsg
  58. import com.grkj.iscs_mars.model.eventmsg.UpdateTicketProgressMsg
  59. import com.grkj.iscs_mars.model.vo.dict.CommonDictRespVO
  60. import com.grkj.iscs_mars.model.vo.hardware.CabinetSlotsRespVo
  61. import com.grkj.iscs_mars.model.vo.hardware.SwitchListReqVO
  62. import com.grkj.iscs_mars.model.vo.key.KeyPageRespVO
  63. import com.grkj.iscs_mars.model.vo.lock.LockPageRespVO
  64. import com.grkj.iscs_mars.model.vo.lock.LockTakeUpdateReqVO
  65. import com.grkj.iscs_mars.model.vo.ticket.LockPointUpdateReqVO
  66. import com.grkj.iscs_mars.model.vo.ticket.TicketDetailRespVO
  67. import com.grkj.iscs_mars.service.CheckKeyInfoTask
  68. import com.grkj.iscs_mars.util.ActivityUtils
  69. import com.grkj.iscs_mars.util.CommonUtils
  70. import com.grkj.iscs_mars.util.Executor
  71. import com.grkj.iscs_mars.util.NetApi
  72. import com.grkj.iscs_mars.util.SPUtils
  73. import com.grkj.iscs_mars.util.ToastUtils
  74. import com.grkj.iscs_mars.util.log.LogUtil
  75. import com.grkj.iscs_mars.view.activity.LoginActivity
  76. import com.grkj.iscs_mars.view.base.BaseActivity
  77. import com.grkj.iscs_mars.view.dialog.TipDialog
  78. import com.sik.cronjob.managers.CronJobScanner
  79. import com.sik.sikcore.SIKCore
  80. import com.sik.sikcore.date.TimeUtils
  81. import com.sik.sikcore.thread.ThreadUtils
  82. import kotlinx.coroutines.Dispatchers
  83. import kotlinx.coroutines.async
  84. import kotlinx.coroutines.suspendCancellableCoroutine
  85. import kotlinx.coroutines.withContext
  86. import kotlin.coroutines.resume
  87. /**
  88. * 业务层管理
  89. */
  90. object BusinessManager {
  91. // 消息总线
  92. val mEventBus = MutableLiveData<MsgEvent>()
  93. @JvmStatic
  94. @Volatile
  95. // 已连接的蓝牙钥匙集合
  96. var deviceList: MutableList<BleBean> = mutableListOf()
  97. // Modbus数据页面监听
  98. class DeviceListener(
  99. val key: Any, val callBack: (DockBean) -> Unit
  100. )
  101. private val listeners = ArrayList<DeviceListener>()
  102. private var initListener: (() -> Unit)? = null
  103. /**
  104. * 断开连接任务
  105. */
  106. private val disconnectJob: HashMap<String, String> = hashMapOf()
  107. // 归还设备是否需要登录
  108. var NEED_AUTH = true
  109. // 归还设备是否需要登录及角色验证
  110. var CAN_RETURN = true
  111. get() {
  112. val loginUser = SPUtils.getLoginUser(MyApplication.instance!!.applicationContext!!)
  113. return (NEED_AUTH && loginUser != null) || !NEED_AUTH
  114. }
  115. // 设备待取列表(需要报给后台的列表,等实际取完再上报)
  116. @JvmStatic
  117. val mDeviceTakeList = mutableListOf<DeviceTakeUpdateBO>()
  118. // 是否是测试人员登录的
  119. var isTestMode = false
  120. // 有问题的钥匙的列表 - rfid
  121. var mExceptionKeyList = mutableListOf<String>()
  122. /**
  123. * 初始化消息总线
  124. */
  125. fun initMsgEventBus() {
  126. mEventBus.observeForever {
  127. LogUtil.i("msgEvent : $it")
  128. when (it.code) {
  129. // loading消息
  130. MSG_EVENT_LOADING -> {
  131. Executor.runOnMain {
  132. val loadingMsg = it.data as LoadingMsg
  133. (ActivityUtils.currentActivity() as BaseActivity<*>).handleLoading(
  134. loadingMsg.isShow, loadingMsg.loadingText
  135. )
  136. }
  137. }
  138. // 设备取出
  139. MSG_EVENT_DEVICE_TAKE_UPDATE -> {
  140. handleDeviceTake(it.data as DeviceTakeUpdateMsg)
  141. }
  142. MsgEventConstants.MSG_EVENT_INIT_KEY_COMPLETE -> {
  143. val job = CronJobScanner.scanJobs(CheckKeyInfoTask())
  144. MyApplication.cronJobManager.registerJobs(job)
  145. }
  146. // 钥匙当前模式
  147. MSG_EVENT_CURRENT_MODE -> {
  148. handleCurrentMode(it.data as CurrentModeMsg)
  149. }
  150. // 钥匙切换模式结果
  151. MSG_EVENT_SWITCH_MODE -> {
  152. when ((it.data as SwitchModeMsg).job) {
  153. // 工作模式
  154. 1 -> {
  155. if (it.data.res == 1) {
  156. // 只能在这里断开,不能全部断开
  157. BleManager.getInstance().disconnect(it.data.bleBean.bleDevice)
  158. deviceList.removeIf { device -> device.bleDevice.mac == it.data.bleBean.bleDevice.mac }
  159. // 打开钥匙卡扣
  160. val keyBean =
  161. ModBusController.getKeyByMac(it.data.bleBean.bleDevice.mac)
  162. if (keyBean == null) {
  163. sendEventMsg(
  164. MsgEvent(
  165. MSG_EVENT_LOADING,
  166. LoadingMsg(false, "未找到钥匙信息", false)
  167. )
  168. )
  169. ToastUtils.tip(R.string.key_not_exists)
  170. } else {
  171. sendLoadingEventMsg(CommonUtils.getStr(R.string.take_out_key_tip))
  172. val dock =
  173. ModBusController.getDockByKeyMac(it.data.bleBean.bleDevice.mac)
  174. keyBean.isReady = false
  175. ModBusController.controlKeyBuckle(
  176. true, keyBean.isLeft, dock?.addr
  177. )
  178. ModBusController.updateKeyReadyStatus(
  179. it.data.bleBean.bleDevice.mac, false, 1
  180. )
  181. ToastUtils.tip(R.string.take_out_key)
  182. }
  183. } else {
  184. LogUtil.e("切换工作模式失败 : ${it.data.bleBean.bleDevice.mac}")
  185. Executor.delayOnMain(500) {
  186. switchWorkMode(it.data.bleBean.bleDevice, false)
  187. }
  188. }
  189. }
  190. // 待机模式
  191. 2 -> {
  192. if (it.data.res == 1) {
  193. ModBusController.updateKeyReadyStatus(
  194. it.data.bleBean.bleDevice.mac, true, 2
  195. )
  196. // 延时再次获取当前状态,触发handleCurrentMode里工作票下发状态检查
  197. Executor.delayOnMain(500) {
  198. getCurrentStatus(1, it.data.bleBean.bleDevice)
  199. }
  200. } else {
  201. LogUtil.e("切换待机模式失败 : ${it.data.bleBean.bleDevice.mac}")
  202. Executor.delayOnMain(500) {
  203. switchReadyMode(it.data.bleBean.bleDevice)
  204. }
  205. }
  206. }
  207. }
  208. }
  209. MSG_EVENT_SWITCH_COLLECTION_UPDATE -> {
  210. ThreadUtils.runOnIO {
  211. val switchStatus =
  212. NetApi.getDictData(DictAndSystemConstants.KEY_SWITCH_STATUS)
  213. val switchListReqVOS = ModBusController.getSwitchData().map {
  214. SwitchListReqVO(
  215. it.idx.toString(),
  216. if (it.enabled) switchStatus?.find { it.dictLabel == "打开" }?.dictValue else switchStatus?.find { it.dictLabel == "关闭" }?.dictValue,
  217. TimeUtils.nowString(TimeUtils.DEFAULT_DATE_HOUR_MIN_SEC_FORMAT)
  218. )
  219. }
  220. NetApi.updateSwitchList(switchListReqVOS) {
  221. LogUtil.i("开关更新完成")
  222. }
  223. }
  224. }
  225. }
  226. }
  227. }
  228. /**
  229. * 连接一把存在的可连接的钥匙
  230. */
  231. fun connectExistsKey(exceptKeyMac: List<String> = listOf()) {
  232. ThreadUtils.runOnIO {
  233. cancelDisconnectAllJob()
  234. val connectedDevice = BleManager.getInstance().allConnectedDevice
  235. if (connectedDevice.isNotEmpty() && connectedDevice.subtract(exceptKeyMac.toSet())
  236. .isNotEmpty()
  237. ) {
  238. LogUtil.i("已有钥匙连接")
  239. return@runOnIO
  240. }
  241. // —— 串行请求1 & 2 ——
  242. val slotsPage = getSlotsPage()
  243. // —— 并行加载字典(或按需串行也行) ——
  244. val slotStatus =
  245. async { fetchDict<CommonDictRespVO>(DictAndSystemConstants.KEY_SLOT_STATUS) }
  246. val keyStatus =
  247. async { fetchDict<CommonDictRespVO>(DictAndSystemConstants.KEY_KEY_STATUS) }
  248. val slotType =
  249. async { fetchDict<CommonDictRespVO>(DictAndSystemConstants.KEY_SLOT_TYPE) }
  250. // 等待字典加载完成
  251. val slotStatusList = slotStatus.await()
  252. val keyStatusList = keyStatus.await()
  253. val slotTypeList = slotType.await()
  254. withContext(Dispatchers.Default) {
  255. val keyPage = withContext(Dispatchers.IO) { getKeyPage() }
  256. getOneKey(
  257. slotsPage?.records?.filter {
  258. it.slotType == slotTypeList.find { d -> d.dictLabel == "钥匙" }?.dictValue && it.status == slotStatusList.find { d -> d.dictLabel == "异常" }?.dictValue
  259. }?.toMutableList() ?: mutableListOf(),
  260. (keyPage?.records?.filter { it.exStatus == keyStatusList.find { d -> d.dictLabel == "异常" }?.dictValue }
  261. ?.map { it.keyNfc ?: "" }?.toMutableList() ?: mutableListOf()),
  262. exceptKeyMac
  263. )
  264. }
  265. }
  266. }
  267. /****************************************** ModBus ******************************************/
  268. /**
  269. * 链接底座
  270. */
  271. fun connectDock(isNeedInit: Boolean = false) {
  272. ModBusController.interruptReadTrashBinStatus(false)
  273. ModBusController.start(MyApplication.instance!!.applicationContext)
  274. ModBusController.unregisterListener(MyApplication.instance!!.applicationContext)
  275. if (isNeedInit) {
  276. ModBusController.initDevicesStatus()
  277. }
  278. }
  279. /**
  280. * 断开底座链接
  281. */
  282. fun disconnectDock() {
  283. ModBusController.stop()
  284. }
  285. /**
  286. * 注册状态监听
  287. */
  288. fun registerStatusListener(key: Any, listener: (DockBean) -> Unit) {
  289. listeners.add(DeviceListener(key, listener))
  290. }
  291. /**
  292. * 注册初始化监听
  293. */
  294. fun registerInitListener(listener: () -> Unit) {
  295. this.initListener = listener
  296. }
  297. /**
  298. * 取消注册初始化监听
  299. */
  300. fun unRegisterInitListener() {
  301. this.initListener = null
  302. }
  303. /**
  304. * 取消注册状态监听
  305. */
  306. fun unregisterListener(key: Any) {
  307. val it = listeners.iterator()
  308. while (it.hasNext()) {
  309. if (it.next().key == key) {
  310. it.remove()
  311. }
  312. }
  313. }
  314. /**
  315. * 总的监听,做预处理,其余的所有监听均使用本监听处理后的数据,只允许调用一次
  316. */
  317. fun registerMainListener() {
  318. ModBusController.registerStatusListener(this) { res ->
  319. deviceStatusHandle(res)
  320. }
  321. }
  322. /**
  323. * 获取最多电量的钥匙
  324. */
  325. fun getMaxPowerKey(): DockBean.KeyBean {
  326. return ModBusController.getMaxPowerKey()
  327. }
  328. /**
  329. * 硬件状态
  330. * 1、检测到有钥匙
  331. * 2、上锁
  332. * 3、开启充电
  333. * 4、蓝牙连接
  334. * 5、蓝牙数据通讯
  335. */
  336. private fun deviceStatusHandle(res: Any) {
  337. LogUtil.i("硬件状态:${(res as List<ByteArray>).map { it.toHexStrings() }}")
  338. if (res.isEmpty() || res.any { it.isEmpty() }) {
  339. var tipStr = CommonUtils.getStr(R.string.no_response_board_exists) + " : "
  340. val addressList = mutableListOf<String>()
  341. ModBusController.modBusManager?.mSlaveAddressList?.forEach { itDock ->
  342. if (res.none { it.isNotEmpty() && it[0] == itDock }) {
  343. addressList.add("0x${String.format("%02X", itDock)}")
  344. }
  345. }
  346. tipStr += addressList
  347. ToastUtils.tip(tipStr)
  348. }
  349. res.forEachIndexed { index, bytes ->
  350. val dockBean = ModBusController.updateStatus(bytes) ?: return@forEachIndexed
  351. ModBusController.isInitReady = true
  352. if (!CAN_RETURN) {
  353. return@forEachIndexed
  354. }
  355. when (dockBean.type) {
  356. DOCK_TYPE_KEY -> {
  357. dockBean.getKeyList().forEach { keyBean ->
  358. deviceKeyHandler(dockBean, keyBean)
  359. }
  360. }
  361. DOCK_TYPE_LOCK -> {
  362. dockBean.getLockList().forEach { lockBean ->
  363. deviceLockHandler(dockBean, lockBean)
  364. }
  365. }
  366. DOCK_TYPE_ELEC_LOCK_BOARD -> {
  367. // TODO 占位
  368. }
  369. DOCK_TYPE_PORTABLE -> {
  370. // TODO 便携式待完善
  371. dockBean.deviceList.forEach { deviceBean ->
  372. if (deviceBean.isExist) {
  373. when (deviceBean.type) {
  374. DEVICE_TYPE_KEY -> {
  375. deviceKeyHandler(dockBean, deviceBean as DockBean.KeyBean)
  376. }
  377. DEVICE_TYPE_LOCK -> {
  378. deviceLockHandler(dockBean, deviceBean as DockBean.LockBean)
  379. }
  380. DEVICE_TYPE_CARD -> {
  381. ModBusController.readPortalCaseCardRfid(dockBean.addr) { res ->
  382. if (res.size < 11) {
  383. LogUtil.e("Portal Case card rfid error")
  384. return@readPortalCaseCardRfid
  385. }
  386. val rfid = res.copyOfRange(3, 11).toHexStrings(false)
  387. .removeLeadingZeros()
  388. LogUtil.i("卡片RFID : $rfid")
  389. }
  390. }
  391. DEVICE_TYPE_FINGERPRINT -> {
  392. }
  393. }
  394. }
  395. }
  396. }
  397. }
  398. Executor.delayOnMain(200) {
  399. if (!ISCSDomainData.isDeviceRegistration) {
  400. listeners.forEach { it.callBack(dockBean) }
  401. }
  402. }
  403. }
  404. Executor.delayOnMain(200) {
  405. if (ISCSDomainData.isDeviceRegistration) {
  406. initListener?.invoke()
  407. }
  408. }
  409. }
  410. /**
  411. * 挂锁处理
  412. */
  413. private fun deviceLockHandler(
  414. dockBean: DockBean,
  415. lockBean: DockBean.LockBean
  416. ) {
  417. if (lockBean.isExist) {
  418. ModBusController.readLockRfid(dockBean.addr, lockBean.idx) { res ->
  419. if (res.size < 11) {
  420. LogUtil.e("Lock rfid error")
  421. return@readLockRfid
  422. }
  423. val rfid =
  424. res.copyOfRange(3, 11).toHexStrings(false).removeLeadingZeros()
  425. ModBusController.updateLockRfid(
  426. dockBean.addr, lockBean.idx, rfid
  427. )
  428. ThreadUtils.runOnIO {
  429. val lockStatusReq =
  430. async { fetchDict<CommonDictRespVO>(DictAndSystemConstants.KEY_PAD_LOCK_STATUS) }
  431. val slotStatus =
  432. async { fetchDict<CommonDictRespVO>(DictAndSystemConstants.KEY_SLOT_STATUS) }
  433. val slotType =
  434. async { fetchDict<CommonDictRespVO>(DictAndSystemConstants.KEY_SLOT_TYPE) }
  435. val slotsPageReq = async { getSlotsPage() }
  436. var lockStatus = lockStatusReq.await()
  437. val slotsPage = slotsPageReq.await()
  438. val slotStatusList = slotStatus.await()
  439. val slotTypeList = slotType.await()
  440. NetApi.getIsLockPage { lockData ->
  441. //锁rfid未异常正常请求锁数据,关锁
  442. if (rfid in (lockData?.records?.filter { it.exStatus == lockStatus.find { it.dictLabel == "异常" }?.dictValue }
  443. ?.map { it.lockNfc }?.toMutableList()
  444. ?: mutableListOf())
  445. ) {
  446. ToastUtils.tip(
  447. MyApplication.instance?.applicationContext!!.getString(
  448. R.string.lock_exception_tag
  449. )
  450. )
  451. } else if (slotsPage?.records?.filter {
  452. it.slotType == slotTypeList.find { d -> d.dictLabel == "锁" }?.dictValue && it.status == slotStatusList.find { d -> d.dictLabel == "异常" }?.dictValue
  453. }
  454. ?.find { it.row?.toInt() == dockBean.row && (lockBean.idx + 1) == it.col?.toInt() } != null) {
  455. ToastUtils.tip(
  456. MyApplication.instance?.applicationContext!!.getString(
  457. R.string.slot_exception_tag
  458. )
  459. )
  460. } else {
  461. NetApi.getLockInfo(rfid) {
  462. if (it != null) {
  463. // TODO 考虑快速拿取
  464. ModBusController.controlLockBuckle(
  465. false, dockBean.addr, lockBean.idx
  466. ) { itRst ->
  467. if (itRst.isNotEmpty()) {
  468. // 上报锁具信息
  469. NetApi.updateLockReturn(
  470. rfid,
  471. MyApplication.instance!!.serialNo()
  472. ) {}
  473. }
  474. }
  475. }
  476. }
  477. }
  478. }
  479. }
  480. }
  481. } else {
  482. LogUtil.i("挂锁取出-:${lockBean.rfid}")
  483. sendEventMsg(
  484. MsgEvent(
  485. MSG_EVENT_DEVICE_TAKE_UPDATE,
  486. DeviceTakeUpdateMsg(DEVICE_TYPE_LOCK, lockBean.rfid)
  487. )
  488. )
  489. }
  490. }
  491. private fun deviceKeyHandler(dockBean: DockBean, keyBean: DockBean.KeyBean) {
  492. if (keyBean.isExist) {
  493. // 放回钥匙,读取rfid
  494. ModBusController.readKeyRfid(
  495. dockBean.addr, if (keyBean.isLeft) 0 else 1
  496. ) { isLeft, res ->
  497. if (!ISCSDomainData.isDeviceRegistration) {
  498. ModBusController.controlKeyCharge(
  499. true, keyBean.isLeft, dockBean.addr
  500. )
  501. }
  502. if (res.size < 11) {
  503. LogUtil.e("Key rfid error")
  504. return@readKeyRfid
  505. }
  506. val rfid =
  507. res.copyOfRange(3, 11).toHexStrings(false).removeLeadingZeros()
  508. ThreadUtils.runOnIO {
  509. val slotStatus =
  510. async { fetchDict<CommonDictRespVO>(DictAndSystemConstants.KEY_SLOT_STATUS) }
  511. val slotType =
  512. async { fetchDict<CommonDictRespVO>(DictAndSystemConstants.KEY_SLOT_TYPE) }
  513. val slotsPageReq = async { getSlotsPage() }
  514. val keyStatusReq =
  515. async { fetchDict<CommonDictRespVO>(DictAndSystemConstants.KEY_KEY_STATUS) }
  516. val keyPageReq = async { getKeyPage() }
  517. var keyStatus = keyStatusReq.await()
  518. var keyData = keyPageReq.await()
  519. val slotsPage = slotsPageReq.await()
  520. val slotStatusList = slotStatus.await()
  521. val slotTypeList = slotType.await()
  522. //锁钥匙未异常正常请求锁数据,关锁
  523. if (rfid in (keyData?.records?.filter { it.exStatus == keyStatus.find { it.dictLabel == "异常" }?.dictValue }
  524. ?.map { it.keyNfc }?.toMutableList()
  525. ?: mutableListOf())
  526. ) {
  527. ToastUtils.tip(
  528. MyApplication.instance?.applicationContext!!.getString(
  529. R.string.key_exception_tag
  530. )
  531. )
  532. } else if (slotsPage?.records?.filter {
  533. it.slotType == slotTypeList.find { d -> d.dictLabel == "钥匙" }?.dictValue && it.status == slotStatusList.find { d -> d.dictLabel == "异常" }?.dictValue
  534. }
  535. ?.find { it.row?.toInt() == dockBean.row && it.col?.toInt() == (dockBean.col + (if (keyBean.isLeft) 0 else 1) * 2) } != null) {
  536. ToastUtils.tip(
  537. MyApplication.instance?.applicationContext!!.getString(
  538. R.string.slot_exception_tag
  539. )
  540. )
  541. } else {
  542. ModBusController.updateKeyRfid(
  543. dockBean.addr, keyBean.isLeft, rfid
  544. )
  545. // 放回钥匙,上锁
  546. ModBusController.controlKeyBuckle(
  547. false, keyBean.isLeft, dockBean.addr
  548. ) {
  549. NetApi.getKeyInfo(rfid) {
  550. ModBusController.updateKeyNewHardware(
  551. dockBean.addr, true, it == null
  552. )
  553. if (it != null && !it.macAddress.isNullOrEmpty()) {
  554. ModBusController.updateKeyMac(
  555. dockBean.addr, keyBean.isLeft, it.macAddress
  556. )
  557. ModBusController.updateKeyReadyStatus(
  558. it.macAddress, false, 5
  559. )
  560. } else {
  561. LogUtil.e("Get key info fail : $rfid")
  562. if (!ISCSDomainData.isDeviceRegistration) {
  563. ToastUtils.tip(R.string.get_key_info_fail)
  564. }
  565. ModBusController.controlKeyBuckle(
  566. true, keyBean.isLeft, dockBean.addr
  567. )
  568. }
  569. }
  570. }
  571. }
  572. }
  573. }
  574. } else if (!keyBean.isCharging) {//增加充电判断,防止无线充电干扰锁仓状态导致判断为取出
  575. // 移出待连监听集合,防止connectKey循环失败
  576. keyBean.mac?.let {
  577. unregisterConnectListener(it)
  578. }
  579. sendEventMsg(
  580. MsgEvent(
  581. MSG_EVENT_DEVICE_TAKE_UPDATE,
  582. DeviceTakeUpdateMsg(DEVICE_TYPE_KEY, keyBean.rfid)
  583. )
  584. )
  585. }
  586. }
  587. /**
  588. * 更新所有锁仓状态
  589. */
  590. fun updateAllBuckleStatus(done: () -> Unit) {
  591. ModBusController.updateAllBuckleStatus(done)
  592. }
  593. /**
  594. * 更新开关状态
  595. */
  596. fun updateSwitchStatus(done: () -> Unit) {
  597. ModBusController.updateSwitchStatus(done)
  598. }
  599. /**
  600. * 钥匙归还提示确认弹框,当前策略:作业票未完成禁止归还钥匙
  601. */
  602. private fun showKeyReturnDialog(onConfirm: () -> Unit) {
  603. val ctx = ActivityUtils.currentActivity() as BaseActivity<*>
  604. val dlg = TipDialog(ctx)
  605. dlg.setTip(ctx.getString(R.string.key_return_tip))
  606. dlg.setType(TipDialog.TYPE_CONFIRM)
  607. // 加个选择判断,如果是直接取消弹框而不是点击“确定”,当成确定
  608. var state = 0
  609. dlg.setConfirmListener {
  610. state = 1
  611. onConfirm.invoke()
  612. }
  613. dlg.setOnDismissListener {
  614. if (state == 0) {
  615. onConfirm.invoke()
  616. }
  617. }
  618. dlg.show()
  619. }
  620. fun readLockBuckleStatus() {
  621. // TODO slaveIdx暂时写死,调试用
  622. ModBusController.readBuckleStatus(true, 0) { type, res ->
  623. LogUtil.i("单slave卡扣状态 : $type - ${res.toHexStrings()}")
  624. when (type) {
  625. 0 -> {
  626. val isLeftLock = (res[4].toInt() shr 0) and 0x1 == 1
  627. val isRightLock = (res[4].toInt() shr 4) and 0x1 == 1
  628. LogUtil.i("锁具底座卡扣状态 : $isLeftLock - $isRightLock")
  629. }
  630. 1 -> {
  631. val tempList = mutableListOf<Boolean>()
  632. for (i in 0..7) {
  633. tempList.add((res[4].toInt() shr i) and 0x1 == 1)
  634. }
  635. LogUtil.i("锁具底座卡扣1-8状态 : $tempList")
  636. }
  637. 2 -> {
  638. val lock9Status = (res[4].toInt() shr 0) and 0x1 == 1
  639. val lock10Status = (res[4].toInt() shr 1) and 0x1 == 1
  640. LogUtil.i("锁具底座卡扣9、10状态 : $lock9Status - $lock10Status")
  641. }
  642. }
  643. }
  644. }
  645. fun readKeyBuckleStatus() {
  646. // TODO slaveIdx暂时写死,调试用
  647. ModBusController.readBuckleStatus(false, 1) { type, res ->
  648. LogUtil.i("单slave卡扣状态 : $type - ${res.toHexStrings()}")
  649. // TODO 待验证
  650. when (type) {
  651. 0 -> {
  652. val isLeftLock = (res[4].toInt() shr 0) and 0x1 == 1
  653. val isRightLock = (res[4].toInt() shr 4) and 0x1 == 1
  654. LogUtil.i("钥匙底座卡扣状态 : $isLeftLock - $isRightLock")
  655. }
  656. 1 -> {
  657. val tempList = mutableListOf<Boolean>()
  658. for (i in 0..7) {
  659. tempList.add((res[4].toInt() shr i) and 0x1 == 1)
  660. }
  661. LogUtil.i("锁具底座卡扣1-8状态 : $tempList")
  662. }
  663. 2 -> {
  664. val lock9Status = (res[4].toInt() shr 0) and 0x1 == 1
  665. val lock10Status = (res[4].toInt() shr 1) and 0x1 == 1
  666. LogUtil.i("锁具底座卡扣9、10状态 : $lock9Status - $lock10Status")
  667. }
  668. }
  669. }
  670. }
  671. // 1. 把 NetApi.get…Page 包成 suspend 函数
  672. private suspend fun getSlotsPage(): CabinetSlotsRespVo? = suspendCancellableCoroutine { cont ->
  673. NetApi.getIsLockCabinetSlotsPage { slots ->
  674. cont.resume(slots)
  675. }
  676. }
  677. private suspend fun getLocksPage(): LockPageRespVO? = suspendCancellableCoroutine { cont ->
  678. NetApi.getIsLockPage { locks ->
  679. cont.resume(locks)
  680. }
  681. }
  682. private suspend fun getKeyPage(): KeyPageRespVO? = suspendCancellableCoroutine { cont ->
  683. NetApi.getIsKeyPage { keys ->
  684. cont.resume(keys)
  685. cont.cancel()
  686. }
  687. }
  688. // 2. 把原本同步的字典查询留在 IO 线程
  689. private suspend fun <T> fetchDict(key: String): List<T> = withContext(Dispatchers.IO) {
  690. @Suppress("UNCHECKED_CAST") NetApi.getDictData(key) as List<T>
  691. }
  692. // 3. 重写 checkEquipCount
  693. fun checkEquipCount(
  694. needLockCount: Int,
  695. isNeedKey: Boolean,
  696. callBack: (Pair<Byte, DockBean.KeyBean?>?, MutableMap<Byte, MutableList<DockBean.LockBean>>) -> Unit
  697. ) {
  698. // 你可以改成接收 CoroutineScope 或者直接在全局 Scope 启动
  699. ThreadUtils.runOnMain {
  700. sendLoadingEventMsg(MyApplication.instance?.applicationContext!!.getString(R.string.check_key_and_lock))
  701. try {
  702. // —— 串行请求1 & 2 ——
  703. val slotsPage = getSlotsPage()
  704. val locksPage = getLocksPage()
  705. // —— 并行加载字典(或按需串行也行) ——
  706. val lockStatus =
  707. async { fetchDict<CommonDictRespVO>(DictAndSystemConstants.KEY_PAD_LOCK_STATUS) }
  708. val slotStatus =
  709. async { fetchDict<CommonDictRespVO>(DictAndSystemConstants.KEY_SLOT_STATUS) }
  710. val slotType =
  711. async { fetchDict<CommonDictRespVO>(DictAndSystemConstants.KEY_SLOT_TYPE) }
  712. val keyStatus =
  713. async { fetchDict<CommonDictRespVO>(DictAndSystemConstants.KEY_KEY_STATUS) }
  714. // 等待字典加载完成
  715. val lockStatusList = lockStatus.await()
  716. val slotStatusList = slotStatus.await()
  717. val slotTypeList = slotType.await()
  718. val keyStatusList = keyStatus.await()
  719. // —— 在 Default 线程做计算密集操作 ——
  720. val lockMap = withContext(Dispatchers.Default) {
  721. ModBusController.getLocks(
  722. needLockCount,
  723. slotsPage?.records?.filter {
  724. it.slotType == slotTypeList.find { d -> d.dictLabel == "锁" }?.dictValue && it.status == slotStatusList.find { d -> d.dictLabel == "异常" }?.dictValue
  725. }?.toMutableList() ?: mutableListOf(),
  726. locksPage?.records?.filter { it.exStatus == lockStatusList.find { d -> d.dictLabel == "异常" }?.dictValue }
  727. ?.map { it.lockNfc ?: "" }?.toMutableList() ?: mutableListOf()
  728. )
  729. }
  730. val actualLockCount = lockMap.values.sumBy { it.size }
  731. // 如果锁不够,提前清空并立刻返回
  732. if (actualLockCount < needLockCount) {
  733. ToastUtils.tip(
  734. MyApplication.instance!!.getString(R.string.lock_is_not_enough)
  735. )
  736. callBack(null, mutableMapOf())
  737. return@runOnMain
  738. }
  739. // —— 如果需钥匙,再请求并计算 ——
  740. var keyPair: Pair<Byte, DockBean.KeyBean?>? = null
  741. if (isNeedKey) {
  742. val keyPage = withContext(Dispatchers.IO) { getKeyPage() }
  743. keyPair = withContext(Dispatchers.Default) {
  744. getOneKey(
  745. slotsPage?.records?.filter {
  746. it.slotType == slotTypeList.find { d -> d.dictLabel == "钥匙" }?.dictValue && it.status == slotStatusList.find { d -> d.dictLabel == "异常" }?.dictValue
  747. }?.toMutableList() ?: mutableListOf(),
  748. keyPage?.records?.filter { it.exStatus == keyStatusList.find { d -> d.dictLabel == "异常" }?.dictValue }
  749. ?.map { it.keyNfc ?: "" }?.toMutableList() ?: mutableListOf()
  750. )
  751. }
  752. if (keyPair == null) {
  753. ToastUtils.tip(
  754. MyApplication.instance!!.getString(R.string.no_available_key)
  755. )
  756. }
  757. }
  758. // —— 全部计算完毕,在主线程一次性回调 ——
  759. callBack(keyPair, lockMap)
  760. } catch (e: Exception) {
  761. // 根据需求处理异常,或把异常信息也通过 callback 返回
  762. sendLoadingEventMsg(null, false)
  763. e.printStackTrace()
  764. ToastUtils.tip("检查设备异常:${e.message}")
  765. }
  766. }
  767. }
  768. /**
  769. * 获取开关量数据
  770. */
  771. fun getSwitchData(): MutableList<DockBean.SwitchBean> {
  772. return ModBusController.getSwitchData()
  773. }
  774. /****************************************** 蓝牙 ******************************************/
  775. /******************************************蓝牙通用准备******************************************/
  776. /**
  777. * 注册连接监听
  778. */
  779. fun registerConnectListener(
  780. mac: String, connectNow: Boolean = false, callBack: ((
  781. Boolean, BleBean?
  782. ) -> Unit)? = null
  783. ) {
  784. BleConnectionManager.registerConnectListener(mac, connectNow, callBack)
  785. }
  786. /**
  787. * 连接监听反注册
  788. */
  789. fun unregisterConnectListener(mac: String, bleBean: BleBean? = null) {
  790. BleConnectionManager.unregisterConnectListener(mac, bleBean)
  791. }
  792. /******************************************蓝牙通用准备结束******************************************/
  793. fun getBleDeviceByMac(mac: String?): BleBean? {
  794. return deviceList.find { it.bleDevice.mac == mac }
  795. }
  796. fun getBleBeanByRfid(nfc: String?): BleBean? {
  797. nfc ?: return null
  798. ModBusController.getKeyByRfid(nfc)?.mac?.let { itMac ->
  799. return getBleDeviceByMac(itMac)
  800. }
  801. return null
  802. }
  803. /**
  804. * 启动断连任务
  805. */
  806. fun launchDisconnectJob(mac: String) {
  807. val jobId = ThreadUtils.runOnIODelayed(Constants.BLE_DISCONNECT_DELAY_TIME) {
  808. val bleBean = getBleDeviceByMac(mac)
  809. bleBean?.bleDevice?.let {
  810. BleManager.getInstance().disconnect(it)
  811. }
  812. }
  813. disconnectJob[mac] = jobId
  814. }
  815. /**
  816. * 启动断连所有设备任务
  817. */
  818. fun launchDisconnectAllJob() {
  819. deviceList.forEach { bleBean ->
  820. val jobId = ThreadUtils.runOnIODelayed(Constants.BLE_DISCONNECT_DELAY_TIME) {
  821. val bleBean = getBleDeviceByMac(bleBean.bleDevice.mac)
  822. bleBean?.bleDevice?.let {
  823. BleManager.getInstance().disconnect(it)
  824. deviceList.removeIf { it == bleBean }
  825. }
  826. }
  827. disconnectJob[bleBean.bleDevice.mac] = jobId
  828. }
  829. }
  830. /**
  831. * 取消断连所有设备任务
  832. */
  833. fun cancelDisconnectAllJob() {
  834. disconnectJob.forEach {
  835. ThreadUtils.cancel(it.value)
  836. }
  837. }
  838. /**
  839. * 取消断连任务
  840. */
  841. fun cancelDisconnectJob(mac: String) {
  842. val jobId = disconnectJob[mac]
  843. jobId?.let {
  844. ThreadUtils.cancel(it)
  845. }
  846. }
  847. /**
  848. * 下发工作票
  849. */
  850. private fun sendTicketBusiness(
  851. isLock: Boolean,
  852. mac: String,
  853. ticketDetail: TicketDetailRespVO,
  854. lockList: MutableList<String?>?,
  855. activity: AppCompatActivity,
  856. isNeedLoading: Boolean = false,
  857. ) {
  858. registerConnectListener(mac, true) { isDone, bleBean ->
  859. if (!isDone) {
  860. sendTicketBusiness(isLock, mac, ticketDetail, lockList, activity, isNeedLoading)
  861. return@registerConnectListener
  862. }
  863. if (bleBean == null) {
  864. // ToastUtils.tip(R.string.simple_key_is_not_connected)
  865. LogUtil.e("sendTicketBusiness fail : $mac, bleBean is null")
  866. return@registerConnectListener
  867. }
  868. // 单bleBean json赋值
  869. bleBean.retryCount = 0
  870. bleBean.ticketSend = generateTicketSendJson(isLock, ticketDetail, lockList)
  871. bleBean.ticketSend?.let { itJson ->
  872. sendTicketWithRetry(itJson, bleBean.bleDevice, isNeedLoading)
  873. }
  874. }
  875. }
  876. /**
  877. * 带重试的下发工作票,重试次数3,间隔500ms
  878. */
  879. private fun sendTicketWithRetry(
  880. json: String,
  881. bleDevice: BleDevice,
  882. isNeedLoading: Boolean = false,
  883. maxRetries: Int = 3,
  884. delayMillis: Long = 500
  885. ) {
  886. var retryCount = 0
  887. fun attemptSend() {
  888. sendTicket(json, bleDevice, isNeedLoading) { sendRst ->
  889. if (!sendRst && retryCount < maxRetries) {
  890. retryCount++
  891. // 等待一段时间后再次尝试
  892. Executor.delayOnMain(delayMillis) {
  893. LogUtil.i("Retry attempt, mac : ${bleDevice.mac}, retryCount : $retryCount")
  894. attemptSend()
  895. }
  896. }
  897. }
  898. }
  899. attemptSend()
  900. }
  901. /**
  902. * 读取工作票完成情况
  903. */
  904. private fun getTicketStatusBusiness(
  905. mac: String, isNeedLoading: Boolean = false
  906. ) {
  907. registerConnectListener(mac, true) { isDone, bleBean ->
  908. if (isDone) {
  909. Executor.delayOnMain(500) {
  910. getTicketStatusWithRetry(bleBean!!.bleDevice, isNeedLoading)
  911. }
  912. } else {
  913. if (isNeedLoading) sendEventMsg(
  914. MsgEvent(
  915. MSG_EVENT_LOADING, LoadingMsg(false, null, false)
  916. )
  917. )
  918. }
  919. }
  920. }
  921. private fun getTicketStatusWithRetry(
  922. bleDevice: BleDevice,
  923. isNeedLoading: Boolean = false,
  924. maxRetries: Int = 3,
  925. delayMillis: Long = 500
  926. ) {
  927. var retryCount = 0
  928. fun attemptSend() {
  929. getTicketStatus(bleDevice, isNeedLoading) { sendRst ->
  930. if (!sendRst && retryCount < maxRetries) {
  931. retryCount++
  932. // 等待一段时间后再次尝试
  933. Executor.delayOnMain(delayMillis) {
  934. LogUtil.i("Retry attempt, mac : ${bleDevice.mac}, retryCount : $retryCount")
  935. attemptSend()
  936. }
  937. }
  938. }
  939. }
  940. attemptSend()
  941. }
  942. private fun sendTicket(
  943. jsonStr: String,
  944. bleDevice: BleDevice,
  945. isNeedLoading: Boolean = false,
  946. processCallback: ((Boolean) -> Unit)? = null
  947. ) {
  948. if (isNeedLoading) sendEventMsg(
  949. MsgEvent(
  950. MSG_EVENT_LOADING,
  951. LoadingMsg(true, CommonUtils.getStr(R.string.start_to_send_ticket), null)
  952. )
  953. )
  954. BleCmdManager.sendWorkTicket(
  955. jsonStr, bleDevice = bleDevice, callback = object : CustomBleWriteCallback() {
  956. override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
  957. LogUtil.i("sendTicket success")
  958. if (isNeedLoading) sendEventMsg(
  959. MsgEvent(
  960. MSG_EVENT_LOADING,
  961. LoadingMsg(true, CommonUtils.getStr(R.string.sending_ticket), null)
  962. )
  963. )
  964. }
  965. override fun onWriteFailure(exception: BleException?) {
  966. LogUtil.e("sendTicket fail : ${bleDevice.mac}")
  967. if (isNeedLoading) sendEventMsg(
  968. MsgEvent(
  969. MSG_EVENT_LOADING,
  970. LoadingMsg(false, CommonUtils.getStr(R.string.send_ticket_fail), null)
  971. )
  972. )
  973. processCallback?.invoke(false)
  974. }
  975. })
  976. }
  977. /**
  978. * 生成下发工作票Json
  979. *
  980. * @param vo 工作票详情
  981. */
  982. private fun generateTicketSendJson(
  983. isLock: Boolean, vo: TicketDetailRespVO, lockList: MutableList<String?>?
  984. ): String {
  985. LogUtil.i("generateTicketSendJson : $lockList")
  986. val bo = WorkTicketSendBO(
  987. cardNo = SPUtils.getLoginUser(MyApplication.instance!!.applicationContext)?.userCardList?.get(
  988. 0
  989. ),
  990. )
  991. CommonUtils.getDiffHours(vo.ticketEndTime)?.let {
  992. bo.effectiveTime = it
  993. }
  994. // 有配置则用配置,没用则填充默认密码
  995. bo.password =
  996. SPUtils.getLoginUser(MyApplication.instance!!.applicationContext)?.keyCode ?: "123456"
  997. val dataBO = WorkTicketSendBO.DataBO(
  998. taskCode = vo.ticketId.toString(), codeId = 1
  999. )
  1000. val taskList = ArrayList<WorkTicketSendBO.DataBO.DataListBO>()
  1001. vo.ticketPointsVOList?.let { itList ->
  1002. itList.forEach { pointVO ->
  1003. if (vo.noUnlockTicketPointsVOSet?.any { it.pointId == pointVO.pointId } == true && isLock == false) {
  1004. return@forEach
  1005. }
  1006. val task = WorkTicketSendBO.DataBO.DataListBO(
  1007. dataId = pointVO.pointId?.toInt(),
  1008. equipRfidNo = pointVO.pointNfc,
  1009. equipName = pointVO.pointName,
  1010. target = if (isLock) 0 else 1
  1011. )
  1012. if (!isLock) {
  1013. task.infoRfidNo = pointVO.lockNfc
  1014. }
  1015. pointVO.prePointId?.let {
  1016. task.prevId = it.toInt()
  1017. }
  1018. // TODO partCode待补充
  1019. taskList.add(task)
  1020. }
  1021. }
  1022. dataBO.dataList = taskList
  1023. bo.data = mutableListOf(dataBO)
  1024. if (isLock) {
  1025. // TODO 挂锁数组
  1026. if (!lockList.isNullOrEmpty()) {
  1027. bo.lockList = mutableListOf()
  1028. lockList.forEachIndexed { index, s ->
  1029. if (s.isNullOrEmpty()) {
  1030. LogUtil.w("Lock nfc is null or empty")
  1031. return@forEachIndexed
  1032. }
  1033. bo.lockList?.add(LockListBO(index + 1, s))
  1034. }
  1035. }
  1036. }
  1037. // TODO partList 待补充
  1038. val jsonStr = Gson().toJson(bo)
  1039. LogUtil.i("json : $jsonStr")
  1040. return jsonStr
  1041. }
  1042. /**
  1043. * 生成下空发工作票Json
  1044. *
  1045. * @param vo 工作票详情
  1046. */
  1047. fun generateEmptyTicketSendJson(): String {
  1048. // 构造一个所有字段都为空/默认值的 WorkTicketSendBO
  1049. val bo = WorkTicketSendBO(
  1050. cardNo = "", // 空卡号
  1051. effectiveTime = 0, // 默认有效时长
  1052. password = "" // 空密码
  1053. ).apply {
  1054. // data 列表留空
  1055. data = mutableListOf()
  1056. // lockList 留空(如果字段非空,再设置为 emptyList())
  1057. lockList = mutableListOf()
  1058. }
  1059. // 转成 JSON 并返回
  1060. val jsonStr = Gson().toJson(bo)
  1061. LogUtil.i("generateEmptyTicketJson: $jsonStr")
  1062. return jsonStr
  1063. }
  1064. fun handleRsp(
  1065. bleBean: BleBean,
  1066. byteArray: ByteArray,
  1067. isNeedLoading: Boolean = false,
  1068. prepareDoneCallBack: ((Boolean, BleBean?) -> Unit)?
  1069. ) {
  1070. // TODO Token校验
  1071. // val len = byteArray[2].toInt()
  1072. // val token = byteArray.copyOfRange(len + 7, len + 11)
  1073. // if (token.contentEquals(bleBean.token)) {
  1074. // LogUtil.i("Token is right")
  1075. // } else {
  1076. // LogUtil.e("Token is wrong")
  1077. // }
  1078. when {
  1079. // 获取令牌
  1080. byteArray.startsWith(BleConst.RSP_GET_TOKEN) -> BleCmdManager.handleToken(
  1081. bleBean.bleDevice, byteArray
  1082. ) { isSuccess ->
  1083. if (isSuccess) {
  1084. prepareDoneCallBack?.invoke(true, bleBean)
  1085. }
  1086. }
  1087. // 工作模式切换
  1088. byteArray.startsWith(BleConst.RSP_SWITCH_MODE) -> {
  1089. handleSwitchModeResult(byteArray, isNeedLoading) { res, job ->
  1090. sendEventMsg(
  1091. MsgEvent(
  1092. MSG_EVENT_SWITCH_MODE, SwitchModeMsg(job.toInt(), res.toInt(), bleBean)
  1093. )
  1094. )
  1095. }
  1096. }
  1097. // 工作票下发
  1098. byteArray.startsWith(BleConst.RSP_SEND_WORK_TICKET) -> handleWorkTicketResult(
  1099. bleBean, byteArray, isNeedLoading
  1100. )
  1101. // 获取设备当前状态
  1102. byteArray.startsWith(BleConst.RSP_CURRENT_STATUS) -> BleCmdManager.handleCurrentStatus(
  1103. byteArray
  1104. ) {
  1105. sendEventMsg(MsgEvent(MSG_EVENT_CURRENT_MODE, CurrentModeMsg(bleBean, it)))
  1106. }
  1107. // 获取设备工作票完成情况
  1108. byteArray.startsWith(BleConst.RSP_WORK_TICKET_RESULT) && byteArray[3] == 0x02.toByte() -> handleTicketStatus(
  1109. bleBean.bleDevice, byteArray, isNeedLoading
  1110. )
  1111. byteArray.startsWith(BleConst.RSP_POWER_STATUS) -> {
  1112. val power = byteArray[4].toInt()
  1113. ModBusController.getKeyByMac(bleBean.bleDevice.mac)?.power = power
  1114. if (power < 50) {//如果电量小于50就打开仓位充电
  1115. ModBusController.controlKeyCharge(true, bleBean.bleDevice.mac) {
  1116. LogUtil.i("钥匙: ${bleBean.bleDevice.mac} 开始充电")
  1117. }
  1118. }
  1119. }
  1120. }
  1121. }
  1122. /**
  1123. * 工作模式切换结果
  1124. * job : 0x01:工作模式 0x02:待机模式
  1125. * res : 0x01:成功 0x02:失败
  1126. */
  1127. private fun handleSwitchModeResult(
  1128. byteArray: ByteArray,
  1129. isNeedLoading: Boolean = false,
  1130. callBack: ((Byte, Byte) -> Unit)? = null
  1131. ) {
  1132. BleCmdManager.handleSwitchModeResult(byteArray) { job, res ->
  1133. if (res == 0x01.toByte() && job == 0x01.toByte()) {
  1134. LogUtil.i("切换工作模式成功")
  1135. if (isNeedLoading) sendEventMsg(
  1136. MsgEvent(
  1137. MSG_EVENT_LOADING, LoadingMsg(false, "切换工作模式成功", null)
  1138. )
  1139. )
  1140. } else if (res == 0x01.toByte() && job == 0x02.toByte()) {
  1141. LogUtil.i("切换待机模式成功")
  1142. if (isNeedLoading) sendEventMsg(
  1143. MsgEvent(
  1144. MSG_EVENT_LOADING, LoadingMsg(false, "切换待机模式成功", null)
  1145. )
  1146. )
  1147. } else {
  1148. LogUtil.e("切换模式失败 : ${job.toInt()} - ${res.toInt()}")
  1149. if (isNeedLoading) sendEventMsg(
  1150. MsgEvent(
  1151. MSG_EVENT_LOADING, LoadingMsg(false, null, null)
  1152. )
  1153. )
  1154. }
  1155. callBack?.invoke(res, job)
  1156. }
  1157. }
  1158. /**
  1159. * 工作票下发结果
  1160. * res:0x00:成功 0x01:失败 0x02:传输超时 0x0D:当前IDX超出范围 0x0E:当前数据CRC校验失败 0x14:JSON结构错误 0x63:未知错误
  1161. */
  1162. private fun handleWorkTicketResult(
  1163. bleBean: BleBean, byteArray: ByteArray, isNeedLoading: Boolean = false
  1164. ) {
  1165. BleCmdManager.handleWorkTicketResult(bleBean, byteArray) { isSuccess, rst ->
  1166. if (isNeedLoading) sendEventMsg(
  1167. MsgEvent(
  1168. MSG_EVENT_LOADING, LoadingMsg(false, null, null)
  1169. )
  1170. )
  1171. if (isSuccess) {
  1172. // 下发完毕,切换工作模式
  1173. LogUtil.i("工作票下发完毕")
  1174. if (isNeedLoading) sendEventMsg(
  1175. MsgEvent(
  1176. MSG_EVENT_LOADING, LoadingMsg(true, "切换钥匙为工作模式", null)
  1177. )
  1178. )
  1179. Executor.delayOnIO(800) {
  1180. //切换到工作模式
  1181. switchWorkMode(bleBean.bleDevice, isNeedLoading)
  1182. }
  1183. } else {
  1184. sendLoadingEventMsg(null, false)
  1185. if (bleBean.retryCount < 3) {
  1186. Executor.delayOnMain(500) {
  1187. bleBean.retryCount++
  1188. sendLoadingEventMsg(MyApplication.instance!!.getString(R.string.start_to_send_ticket))
  1189. sendTicketWithRetry(bleBean.ticketSend!!, bleBean.bleDevice, isNeedLoading)
  1190. }
  1191. } else {
  1192. ToastUtils.tip(R.string.send_ticket_fail)
  1193. LogUtil.e("Send ticket fail")
  1194. ModBusController.getKeyByMac(bleBean.bleDevice.mac)?.let { itKey ->
  1195. mDeviceTakeList.removeIf { it.deviceType == DEVICE_TYPE_KEY && it.nfc == itKey.rfid }
  1196. }
  1197. }
  1198. }
  1199. }
  1200. }
  1201. /**
  1202. * 获取当前钥匙的状态
  1203. */
  1204. fun getCurrentStatus(
  1205. from: Int,
  1206. bleDevice: BleDevice,
  1207. retryCount: Int = 0,
  1208. timeoutCallBack: ((Boolean) -> Unit)? = null
  1209. ) {
  1210. LogUtil.i("getCurrentStatus - ${bleDevice.mac} - from : $from")
  1211. var isTimeout = true
  1212. // 加1秒防止早于onWriteFailure开始处理导致多次处理
  1213. Executor.delayOnMain((BleUtil.OPERATE_TIMEOUT + 1).toLong()) {
  1214. if (isTimeout) {
  1215. LogUtil.e("getCurrentStatus timeout : mac = ${bleDevice.mac}, retryCount = $retryCount")
  1216. if (retryCount > 0) {
  1217. Executor.delayOnMain(1000) {
  1218. getCurrentStatus(from, bleDevice, retryCount - 1, timeoutCallBack)
  1219. }
  1220. } else {
  1221. ModBusController.getKeyByMac(bleDevice.mac)?.rfid?.let {
  1222. addExceptionKey(it)
  1223. timeoutCallBack?.invoke(true)
  1224. }
  1225. }
  1226. }
  1227. }
  1228. BleCmdManager.getCurrentStatus(bleDevice, object : CustomBleWriteCallback() {
  1229. override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
  1230. LogUtil.i("getCurrentStatus success : ${bleDevice.mac}")
  1231. isTimeout = false
  1232. timeoutCallBack?.invoke(false)
  1233. }
  1234. override fun onWriteFailure(exception: BleException?) {
  1235. LogUtil.i("getCurrentStatus fail : ${bleDevice.mac}")
  1236. isTimeout = false
  1237. Executor.delayOnMain(1000) {
  1238. getCurrentStatus(from, bleDevice, timeoutCallBack = timeoutCallBack)
  1239. }
  1240. }
  1241. })
  1242. }
  1243. /**
  1244. * 获取电池电量
  1245. */
  1246. fun getBatteryPower(bleDevice: BleDevice) {
  1247. LogUtil.i("获取电池电量:${bleDevice.mac}")
  1248. BleCmdManager.getPower(bleDevice.mac, object : CustomBleWriteCallback() {
  1249. override fun onWriteSuccess(p0: Int, p1: Int, p2: ByteArray?) {
  1250. LogUtil.i("发送获取电池电量命令成功:${bleDevice.mac}")
  1251. }
  1252. override fun onWriteFailure(p0: BleException?) {
  1253. ThreadUtils.runOnIODelayed(500) {
  1254. LogUtil.i("发送获取电池电量命令失败:${bleDevice.mac}")
  1255. getBatteryPower(bleDevice)
  1256. }
  1257. }
  1258. })
  1259. }
  1260. /**
  1261. * 切换工作模式
  1262. */
  1263. private fun switchWorkMode(bleDevice: BleDevice, isNeedLoading: Boolean = false) {
  1264. LogUtil.i("switchWorkMode - ${bleDevice.mac}")
  1265. BleCmdManager.switchMode(STATUS_WORK, bleDevice, object : CustomBleWriteCallback() {
  1266. override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
  1267. LogUtil.i("switch mode work success : ${bleDevice.mac}")
  1268. }
  1269. override fun onWriteFailure(exception: BleException?) {
  1270. LogUtil.e("switch mode work fail : ${exception?.code} - ${exception?.description}")
  1271. Executor.delayOnMain(500) {
  1272. switchWorkMode(bleDevice, isNeedLoading)
  1273. }
  1274. }
  1275. })
  1276. }
  1277. /**
  1278. * 处理工作票完成情况
  1279. */
  1280. private fun handleTicketStatus(
  1281. bleDevice: BleDevice, byteArray: ByteArray, isNeedLoading: Boolean = false
  1282. ) {
  1283. BleCmdManager.handleTicketStatus(bleDevice, byteArray) { ticketJson ->
  1284. if (ticketJson.isNullOrEmpty()) {
  1285. return@handleTicketStatus
  1286. }
  1287. if (isNeedLoading) sendEventMsg(
  1288. MsgEvent(
  1289. MSG_EVENT_LOADING, LoadingMsg(false, "工作票完成状态读取完成", null)
  1290. )
  1291. )
  1292. LogUtil.i("Get ticket status complete : ${bleDevice.mac}")
  1293. // TD:Ticket Done
  1294. if (isNeedLoading) sendEventMsg(
  1295. MsgEvent(
  1296. MSG_EVENT_LOADING, LoadingMsg(false, "TD$ticketJson}", true)
  1297. )
  1298. )
  1299. val workTicketGetBO = try {
  1300. Gson().fromJson(ticketJson, WorkTicketGetBO::class.java)
  1301. } catch (e: Exception) {
  1302. null
  1303. }
  1304. if (workTicketGetBO == null) {
  1305. ToastUtils.tip(R.string.ticket_data_error)
  1306. return@handleTicketStatus
  1307. }
  1308. // 判断workTicketGetBO里是否有未完成的
  1309. ThreadUtils.runOnIO {
  1310. val finishedStatus = workTicketGetBO.hasFinished()
  1311. LogUtil.i("作业票结束情况:${finishedStatus}")
  1312. if (finishedStatus.first) {
  1313. Executor.delayOnMain(500) {
  1314. handleKeyReturn(bleDevice, workTicketGetBO, finishedStatus.second)
  1315. //检查钥匙是否代取,如果是的话给钥匙
  1316. val keyBean = ModBusController.getKeyByMac(bleDevice.mac)
  1317. mDeviceTakeList.find { it.deviceType == DEVICE_TYPE_KEY && it.nfc == keyBean?.rfid }
  1318. ?.let { itKey ->
  1319. sendLoadingEventMsg(
  1320. MyApplication.instance?.applicationContext!!.getString(
  1321. R.string.ble_connecting
  1322. )
  1323. )
  1324. handleGiveKey(itKey)
  1325. }
  1326. }
  1327. } else {
  1328. // 当前策略:作业票未完成禁止归还钥匙
  1329. withContext(Dispatchers.Main) {
  1330. showKeyReturnDialog {
  1331. sendLoadingEventMsg(null, false)
  1332. ToastUtils.tip(R.string.continue_the_ticket)
  1333. BleManager.getInstance().disconnect(bleDevice)
  1334. deviceList.removeIf { device -> device.bleDevice.mac == bleDevice.mac }
  1335. // 打开卡扣,防止初始化的时候选择不处理钥匙导致无法使用
  1336. val dock = ModBusController.getDockByKeyMac(bleDevice.mac)
  1337. val keyBean = dock?.getKeyList()?.find { it.mac == bleDevice.mac }
  1338. keyBean?.let {
  1339. ModBusController.controlKeyBuckle(true, keyBean.isLeft, dock.addr)
  1340. }
  1341. }
  1342. }
  1343. }
  1344. }
  1345. }
  1346. }
  1347. /**
  1348. * ticketFinished主要是后端的作业票是否已经结束,结束了,就直接修改状态就好了
  1349. */
  1350. private fun handleKeyReturn(
  1351. bleDevice: BleDevice, workTicketGetBO: WorkTicketGetBO?, ticketFinished: Boolean
  1352. ) {
  1353. val dock = ModBusController.getDockByKeyMac(bleDevice.mac)
  1354. val keyBean = dock?.getKeyList()?.find { it.mac == bleDevice.mac }
  1355. keyBean?.let {
  1356. ModBusController.controlKeyBuckle(false, keyBean.isLeft, dock.addr)
  1357. }
  1358. if (ticketFinished) {
  1359. mDeviceTakeList.removeIf { it.nfc == keyBean?.rfid }
  1360. switchReadyMode(bleDevice)
  1361. } else {
  1362. // 上报隔离点状态
  1363. val keyNfc = ModBusController.getKeyByMac(bleDevice.mac)?.rfid ?: "key rfid lost"
  1364. workTicketGetBO?.data?.forEach { data ->
  1365. val updateList = mutableListOf<LockPointUpdateReqVO>()
  1366. data.dataList?.forEach { dataListDTO ->
  1367. data.taskCode?.toLong()?.let {
  1368. SPUtils.returnKey(it)
  1369. }
  1370. val updateVO = LockPointUpdateReqVO(
  1371. data.taskCode?.toLong(),
  1372. dataListDTO.infoRfidNo,
  1373. dataListDTO.equipRfidNo,
  1374. keyNfc,
  1375. dataListDTO.target,
  1376. dataListDTO.status
  1377. )
  1378. updateList.add(updateVO)
  1379. }
  1380. sendLoadingEventMsg(null, false)
  1381. if (CAN_RETURN) {
  1382. // 上报点位钥匙绑定
  1383. NetApi.updateLockPointBatch(updateList) { isSuccess, msg, code ->
  1384. LogUtil.i("还锁操作:${isSuccess},${msg},${code}")
  1385. if (isSuccess) {
  1386. // 上报钥匙归还
  1387. NetApi.updateKeyReturn(
  1388. data.taskCode?.toLong()!!,
  1389. keyNfc!!,
  1390. MyApplication.instance!!.serialNo()
  1391. ) { isSuccess, msg, code ->
  1392. if (!isSuccess && msg != MyApplication.instance?.applicationContext!!.getString(
  1393. R.string.ticket_lost
  1394. )
  1395. ) {
  1396. SPUtils.saveUpdateKeyReturn(
  1397. MyApplication.instance!!,
  1398. UpdateKeyReturnBO(data.taskCode?.toLong()!!, keyNfc!!)
  1399. )
  1400. if (msg == MyApplication.instance?.applicationContext!!.getString(
  1401. R.string.ticket_lost
  1402. )
  1403. ) {
  1404. sendEventMsg(
  1405. MsgEvent(
  1406. MsgEventConstants.MSG_EVENT_TICKET_FINISHED, null
  1407. )
  1408. )
  1409. }
  1410. ToastUtils.tip(R.string.key_return_success)
  1411. } else {
  1412. ToastUtils.tip(R.string.key_return_success)
  1413. }
  1414. }
  1415. data.taskCode?.toLong()?.let {
  1416. sendEventMsg(
  1417. MsgEvent(
  1418. MSG_EVENT_UPDATE_TICKET_PROGRESS,
  1419. UpdateTicketProgressMsg(it)
  1420. )
  1421. )
  1422. }
  1423. // 确认归还,切换为待机模式
  1424. switchReadyMode(bleDevice)
  1425. } else {
  1426. ThreadUtils.runOnMain {
  1427. // 当前策略:作业票未完成禁止归还钥匙
  1428. showKeyReturnDialog {
  1429. sendLoadingEventMsg(null, false)
  1430. ToastUtils.tip(R.string.continue_the_ticket)
  1431. BleManager.getInstance().disconnect(bleDevice)
  1432. deviceList.removeIf { device -> device.bleDevice.mac == bleDevice.mac }
  1433. // 打开卡扣,防止初始化的时候选择不处理钥匙导致无法使用
  1434. if (workTicketGetBO.data?.all { it.dataList?.all { it.closed == 1 } == true } == true) {
  1435. workTicketGetBO.data?.firstOrNull()?.taskCode?.toLong()
  1436. ?.let {
  1437. checkStepAndTicketDetailThenSendTicket(
  1438. it,
  1439. bleDevice.mac
  1440. )
  1441. }
  1442. } else {
  1443. val dock = ModBusController.getDockByKeyMac(bleDevice.mac)
  1444. val keyBean =
  1445. dock?.getKeyList()?.find { it.mac == bleDevice.mac }
  1446. keyBean?.let {
  1447. ModBusController.controlKeyBuckle(
  1448. true, keyBean.isLeft, dock.addr
  1449. )
  1450. }
  1451. }
  1452. }
  1453. }
  1454. SPUtils.clearUpdateKeyReturn(MyApplication.instance!!)
  1455. SPUtils.clearUpdateLockPoint(MyApplication.instance!!)
  1456. }
  1457. }
  1458. } else {
  1459. SPUtils.saveUpdateLockPoint(MyApplication.instance!!, updateList)
  1460. SPUtils.saveUpdateKeyReturn(
  1461. MyApplication.instance!!,
  1462. UpdateKeyReturnBO(data.taskCode?.toLong()!!, keyNfc!!)
  1463. )
  1464. // 保存待发数据,切换为待机模式
  1465. switchReadyMode(bleDevice)
  1466. }
  1467. }
  1468. }
  1469. }
  1470. /**
  1471. * 处理虚拟钥匙取出,如果作业的全部点位已经上锁更新钥匙的状态使用
  1472. */
  1473. fun handleVirtualKeyGive(taskCode: Long, keyNfc: String, done: () -> Unit) {
  1474. // 上报钥匙归还
  1475. NetApi.updateKeyTake(taskCode, keyNfc, MyApplication.instance!!.serialNo()) { isSuccess ->
  1476. if (isSuccess) {
  1477. done()
  1478. }
  1479. }
  1480. }
  1481. /**
  1482. * 处理虚拟钥匙归还,如果作业的全部点位已经上锁更新钥匙的状态使用
  1483. */
  1484. fun handleVirtualKeyReturn(taskCode: Long, keyNfc: String, done: () -> Unit) {
  1485. // 上报钥匙归还
  1486. NetApi.updateKeyReturn(
  1487. taskCode, keyNfc, MyApplication.instance!!.serialNo()
  1488. ) { isSuccess, msg, code ->
  1489. if (!isSuccess && msg != MyApplication.instance?.applicationContext!!.getString(
  1490. R.string.ticket_lost
  1491. )
  1492. ) {
  1493. SPUtils.saveUpdateKeyReturn(
  1494. MyApplication.instance!!, UpdateKeyReturnBO(taskCode, keyNfc)
  1495. )
  1496. if (msg == MyApplication.instance?.applicationContext!!.getString(
  1497. R.string.ticket_lost
  1498. )
  1499. ) {
  1500. sendEventMsg(
  1501. MsgEvent(
  1502. MsgEventConstants.MSG_EVENT_TICKET_FINISHED, null
  1503. )
  1504. )
  1505. }
  1506. } else {
  1507. done()
  1508. sendEventMsg(
  1509. MsgEvent(
  1510. MSG_EVENT_UPDATE_TICKET_PROGRESS, UpdateTicketProgressMsg(taskCode)
  1511. )
  1512. )
  1513. }
  1514. }
  1515. }
  1516. fun switchReadyMode(bleDevice: BleDevice) {
  1517. BleCmdManager.switchMode(STATUS_READY, bleDevice, object : CustomBleWriteCallback() {
  1518. override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
  1519. LogUtil.i("switch mode ready success : ${bleDevice.mac}")
  1520. }
  1521. override fun onWriteFailure(exception: BleException?) {
  1522. LogUtil.e("switch mode ready fail : ${bleDevice.mac}")
  1523. Executor.delayOnMain(300) {
  1524. switchReadyMode(bleDevice)
  1525. }
  1526. }
  1527. })
  1528. }
  1529. /**
  1530. * 获取工作票完成情况
  1531. */
  1532. private fun getTicketStatus(
  1533. bleDevice: BleDevice,
  1534. isNeedLoading: Boolean = false,
  1535. processCallback: ((Boolean) -> Unit)? = null
  1536. ) {
  1537. if (isNeedLoading) sendEventMsg(
  1538. MsgEvent(
  1539. MSG_EVENT_LOADING, LoadingMsg(true, "开始获取工作票", null)
  1540. )
  1541. )
  1542. BleCmdManager.getTicketStatus(bleDevice, object : CustomBleWriteCallback() {
  1543. override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
  1544. if (isNeedLoading) sendEventMsg(
  1545. MsgEvent(
  1546. MSG_EVENT_LOADING, LoadingMsg(false, "工作票获取成功", null)
  1547. )
  1548. )
  1549. LogUtil.i("getTicketStatus success")
  1550. }
  1551. override fun onWriteFailure(exception: BleException?) {
  1552. if (isNeedLoading) sendEventMsg(
  1553. MsgEvent(
  1554. MSG_EVENT_LOADING, LoadingMsg(false, "工作票获取失败", false)
  1555. )
  1556. )
  1557. processCallback?.invoke(false)
  1558. LogUtil.e("getTicketStatus fail")
  1559. }
  1560. })
  1561. }
  1562. /**
  1563. * 添加待更新取出状态的设备
  1564. */
  1565. fun addDeviceTake(deviceType: Int, ticketId: Long, nfc: String?) {
  1566. LogUtil.i("addDeviceTake : $deviceType - $ticketId - $nfc")
  1567. mDeviceTakeList.removeIf { it.deviceType == deviceType && it.nfc == nfc }
  1568. mDeviceTakeList.add(DeviceTakeUpdateBO(deviceType, ticketId, nfc!!))
  1569. }
  1570. fun removeDeviceTake(deviceType: Int, nfc: String?) {
  1571. LogUtil.i("removeDeviceTake : $deviceType - $nfc")
  1572. mDeviceTakeList.removeIf { it.deviceType == deviceType && it.nfc == nfc }
  1573. }
  1574. private fun handleDeviceTake(deviceTakeUpdateBO: DeviceTakeUpdateMsg, rfid: String? = null) {
  1575. LogUtil.i("$deviceTakeUpdateBO")
  1576. when (deviceTakeUpdateBO.deviceType) {
  1577. // 钥匙
  1578. 0 -> {
  1579. mDeviceTakeList.find { it.deviceType == DEVICE_TYPE_KEY && it.nfc == deviceTakeUpdateBO.nfc }
  1580. ?.let { info ->
  1581. sendLoadingEventMsg(null, false)
  1582. SPUtils.takeKey(info.ticketId)
  1583. NetApi.updateKeyTake(
  1584. info.ticketId, info.nfc, MyApplication.instance?.serialNo()!!
  1585. ) { isSuccess ->
  1586. if (isSuccess) {
  1587. mDeviceTakeList.removeIf { it.deviceType == DEVICE_TYPE_KEY && it.nfc == info.nfc }
  1588. sendEventMsg(
  1589. MsgEvent(
  1590. MSG_EVENT_UPDATE_TICKET_PROGRESS,
  1591. UpdateTicketProgressMsg(info.ticketId)
  1592. )
  1593. )
  1594. //钥匙取出之后重新再连一把钥匙待机
  1595. ModBusController.getKeyByRfid(
  1596. info.nfc
  1597. )?.mac?.let {
  1598. unregisterConnectListener(it)
  1599. }
  1600. //待机数不够就再连一把,但不能是原来那把
  1601. NetApi.getMySelfState {
  1602. if (it) {
  1603. ModBusController.getKeyByRfid(
  1604. info.nfc
  1605. )?.mac?.let {
  1606. val maxPowerMac = getMaxPowerKey().mac
  1607. if (maxPowerMac != it) {
  1608. connectExistsKey(listOf(it ?: ""))
  1609. launchDisconnectJob(it ?: "")
  1610. }
  1611. }
  1612. }
  1613. }
  1614. }
  1615. }
  1616. } ?: sendLoadingEventMsg(null, false)
  1617. }
  1618. // 挂锁
  1619. 1 -> {
  1620. mDeviceTakeList.find { it.deviceType == DEVICE_TYPE_LOCK && it.nfc == deviceTakeUpdateBO.nfc }
  1621. ?.let { info ->
  1622. NetApi.updateLockTake(
  1623. mutableListOf(
  1624. LockTakeUpdateReqVO(
  1625. info.ticketId, info.nfc, MyApplication.instance?.serialNo()!!
  1626. )
  1627. )
  1628. ) { isSuccess ->
  1629. Executor.runOnMain {
  1630. if (isSuccess == false) {
  1631. LogUtil.e("Lock take report fail")
  1632. ToastUtils.tip(R.string.lock_take_report_fail)
  1633. SPUtils.saveTicketTakeLockException(info.ticketId)
  1634. mDeviceTakeList.removeIf { it.deviceType == DEVICE_TYPE_LOCK && it.nfc == info.nfc }
  1635. mDeviceTakeList.removeIf { it.deviceType == DEVICE_TYPE_KEY && it.ticketId == info.ticketId }
  1636. sendLoadingEventMsg(null, false)
  1637. return@runOnMain
  1638. }
  1639. // 检查是不是要发钥匙了
  1640. mDeviceTakeList.removeIf { it.deviceType == DEVICE_TYPE_LOCK && it.nfc == info.nfc }
  1641. // 检查当前工作票是否取完挂锁
  1642. if (mDeviceTakeList.any { it.deviceType == DEVICE_TYPE_LOCK && it.ticketId == info.ticketId }) {
  1643. LogUtil.i("Waiting all locks to take out")
  1644. sendLoadingEventMsg(
  1645. MyApplication.instance?.applicationContext?.getString(
  1646. R.string.take_out_lock_tip,
  1647. mDeviceTakeList.count { it.deviceType == DEVICE_TYPE_LOCK && it.ticketId == info.ticketId })
  1648. )
  1649. ToastUtils.tip(R.string.take_out_rest_locks)
  1650. return@runOnMain
  1651. } else {
  1652. LogUtil.i("All locks are taken")
  1653. sendLoadingEventMsg(null, false)
  1654. }
  1655. if (SPUtils.getTicketTakeLockException(info.ticketId)) {
  1656. ToastUtils.tip(R.string.current_ticket_report_lock_take_exception_tip)
  1657. return@runOnMain
  1658. }
  1659. // 检查有无当前工作票的钥匙
  1660. mDeviceTakeList.find { it.deviceType == DEVICE_TYPE_KEY && it.ticketId == info.ticketId }
  1661. ?.let { itKey ->
  1662. sendLoadingEventMsg(
  1663. MyApplication.instance?.applicationContext!!.getString(
  1664. R.string.ble_connecting
  1665. )
  1666. )
  1667. handleGiveKey(itKey)
  1668. }
  1669. }
  1670. }
  1671. }
  1672. }
  1673. }
  1674. }
  1675. /**
  1676. * 分配钥匙
  1677. */
  1678. private fun handleGiveKey(deviceTakeUpdateBO: DeviceTakeUpdateBO) {
  1679. getBleDeviceByMac(ModBusController.getKeyByRfid(deviceTakeUpdateBO.nfc)?.mac)?.let {
  1680. getCurrentStatus(
  1681. 2,
  1682. getBleDeviceByMac(ModBusController.getKeyByRfid(deviceTakeUpdateBO.nfc)?.mac)!!.bleDevice
  1683. ) {
  1684. if (!it) {
  1685. return@getCurrentStatus
  1686. }
  1687. LogUtil.w("handleGiveKey timeout")
  1688. removeDeviceTake(DEVICE_TYPE_KEY, deviceTakeUpdateBO.nfc)
  1689. checkEquipCount(0, true) { keyPair, lockMap ->
  1690. if (keyPair == null) {
  1691. ThreadUtils.runOnMain {
  1692. val tipDialog = TipDialog(SIKCore.getApplication())
  1693. tipDialog.setTip(
  1694. SIKCore.getApplication().getString(R.string.key_take_error_tip)
  1695. )
  1696. tipDialog.setConfirmListener {
  1697. tipDialog.dismiss()
  1698. sendEventMsg(
  1699. MsgEvent(
  1700. MSG_EVENT_DEVICE_EXCEPTION,
  1701. DeviceExceptionMsg(DEVICE_TYPE_KEY, deviceTakeUpdateBO.nfc)
  1702. )
  1703. )
  1704. }
  1705. tipDialog.show()
  1706. }
  1707. } else {
  1708. addDeviceTake(
  1709. DEVICE_TYPE_KEY, deviceTakeUpdateBO.ticketId, keyPair.second?.rfid!!
  1710. )
  1711. handleGiveKey(
  1712. DeviceTakeUpdateBO(
  1713. DEVICE_TYPE_KEY, deviceTakeUpdateBO.ticketId, keyPair.second?.rfid!!
  1714. )
  1715. )
  1716. }
  1717. }
  1718. }
  1719. } ?: run {
  1720. ThreadUtils.runOnMain {
  1721. val tipDialog = TipDialog(SIKCore.getApplication())
  1722. tipDialog.setTip(SIKCore.getApplication().getString(R.string.key_take_error_tip))
  1723. tipDialog.setConfirmListener {
  1724. tipDialog.dismiss()
  1725. sendEventMsg(
  1726. MsgEvent(
  1727. MSG_EVENT_DEVICE_EXCEPTION,
  1728. DeviceExceptionMsg(DEVICE_TYPE_KEY, deviceTakeUpdateBO.nfc)
  1729. )
  1730. )
  1731. }
  1732. tipDialog.show()
  1733. }
  1734. }
  1735. }
  1736. /**
  1737. * 根据当前模式进行处理
  1738. */
  1739. private fun handleCurrentMode(currentModeMsg: CurrentModeMsg) {
  1740. when (currentModeMsg.mode) {
  1741. // 工作模式
  1742. 0x01.toByte() -> {
  1743. // 读工作票
  1744. getTicketStatusBusiness(currentModeMsg.bleBean.bleDevice.mac)
  1745. }
  1746. // 待机模式
  1747. 0x02.toByte() -> {
  1748. // 根据情况看是否需要下发工作票
  1749. ModBusController.getKeyByMac(currentModeMsg.bleBean.bleDevice.mac)?.let { key ->
  1750. // 判断是否有待取的钥匙
  1751. val updateBo =
  1752. mDeviceTakeList.find { it.deviceType == DEVICE_TYPE_KEY && key.rfid == it.nfc }
  1753. if (mDeviceTakeList.any { it.deviceType == DEVICE_TYPE_LOCK && it.ticketId == updateBo?.ticketId }) {
  1754. //todo 如果有钥匙待取但是对应的作业票的锁还有的,就不发
  1755. return
  1756. }
  1757. updateBo?.let { itBO ->
  1758. NetApi.getStepDetail(itBO.ticketId) {
  1759. var step = 0
  1760. it?.filter { it.stepStatus == "1" }
  1761. ?.maxByOrNull { it.stepIndex!! }?.stepIndex?.let {
  1762. step = it
  1763. }
  1764. NetApi.getTicketDetail(itBO.ticketId) { ticketDetail, _ ->
  1765. if (ticketDetail == null) {
  1766. return@getTicketDetail
  1767. }
  1768. val role = ticketDetail?.ticketUserVOList?.find {
  1769. it.userId == SPUtils.getLoginUser(MyApplication.instance?.applicationContext!!)?.userId && it.userType == USER_TYPE_LOCKER
  1770. }
  1771. if (role == null) {
  1772. ToastUtils.tip(R.string.you_are_not_locker_tip)
  1773. return@getTicketDetail
  1774. }
  1775. if (step == 4) { // 上锁工作票
  1776. sendTicketBusiness(
  1777. true,
  1778. currentModeMsg.bleBean.bleDevice.mac,
  1779. ticketDetail,
  1780. ticketDetail.ticketLockVOList?.filter { it.lockStatus != "2" }
  1781. ?.map { it.lockNfc }?.toMutableList(),
  1782. ActivityUtils.currentActivity() as BaseActivity<*>,
  1783. true
  1784. )
  1785. } else if (step == 7) { // 解锁工作票
  1786. sendTicketBusiness(
  1787. false,
  1788. currentModeMsg.bleBean.bleDevice.mac,
  1789. ticketDetail,
  1790. null,
  1791. ActivityUtils.currentActivity() as BaseActivity<*>,
  1792. true
  1793. )
  1794. }
  1795. }
  1796. }
  1797. } ?: let {
  1798. ModBusController.updateKeyReadyStatus(
  1799. currentModeMsg.bleBean.bleDevice.mac, true, 4
  1800. )
  1801. sendLoadingEventMsg(null, false)
  1802. //连上之后没有工作票要下发就断开 看是否还有设备等待连接,没有就不断开,有就让路,一般是初始化的时候
  1803. launchDisconnectJob(currentModeMsg.bleBean.bleDevice.mac)
  1804. NetApi.getMySelfState {
  1805. if (it) {
  1806. val maxPowerMac = getMaxPowerKey().mac
  1807. if (maxPowerMac != currentModeMsg.bleBean.bleDevice.mac) {
  1808. connectExistsKey(
  1809. listOf(
  1810. currentModeMsg.bleBean.bleDevice.mac ?: ""
  1811. )
  1812. )
  1813. launchDisconnectJob(currentModeMsg.bleBean.bleDevice.mac ?: "")
  1814. }
  1815. } else {
  1816. launchDisconnectJob(currentModeMsg.bleBean.bleDevice.mac ?: "")
  1817. }
  1818. }
  1819. }
  1820. }
  1821. }
  1822. // 故障模式
  1823. 0x03.toByte() -> {
  1824. // TODO 上报?
  1825. ToastUtils.tip(
  1826. "${currentModeMsg.bleBean.bleDevice.mac} : " + "${CommonUtils.getStr(R.string.key_is_in_failure_mode)}"
  1827. )
  1828. }
  1829. }
  1830. }
  1831. /**
  1832. * 检查步骤和作业票详情并且下发作业票
  1833. */
  1834. private fun checkStepAndTicketDetailThenSendTicket(ticketId: Long, mac: String) {
  1835. NetApi.getStepDetail(ticketId) {
  1836. var step = 0
  1837. it?.filter { it.stepStatus == "1" }
  1838. ?.maxByOrNull { it.stepIndex!! }?.stepIndex?.let {
  1839. step = it
  1840. }
  1841. NetApi.getTicketDetail(ticketId) { ticketDetail, _ ->
  1842. if (ticketDetail == null) {
  1843. return@getTicketDetail
  1844. }
  1845. val role = ticketDetail?.ticketUserVOList?.find {
  1846. it.userId == SPUtils.getLoginUser(MyApplication.instance?.applicationContext!!)?.userId && it.userType == USER_TYPE_LOCKER
  1847. }
  1848. if (role == null) {
  1849. ToastUtils.tip(R.string.you_are_not_locker_tip)
  1850. return@getTicketDetail
  1851. }
  1852. if (step == 4) { // 上锁工作票
  1853. sendTicketBusiness(
  1854. true,
  1855. mac,
  1856. ticketDetail,
  1857. ticketDetail.ticketLockVOList?.filter { it.lockStatus != "2" }
  1858. ?.map { it.lockNfc }?.toMutableList(),
  1859. ActivityUtils.currentActivity() as BaseActivity<*>,
  1860. true
  1861. )
  1862. } else if (step == 7) { // 解锁工作票
  1863. sendTicketBusiness(
  1864. false,
  1865. mac,
  1866. ticketDetail,
  1867. null,
  1868. ActivityUtils.currentActivity() as BaseActivity<*>,
  1869. true
  1870. )
  1871. }
  1872. }
  1873. }
  1874. }
  1875. fun submitKeyData(context: Context) {
  1876. if (!CAN_RETURN) return
  1877. val updateList = SPUtils.getUpdateLockPoint(context)
  1878. if (updateList.isNotEmpty()) {
  1879. NetApi.updateLockPointBatch(updateList) { isSuccess, msg, code ->
  1880. LogUtil.i("submitKeyData还锁操作:${isSuccess},${msg},${code}")
  1881. if (isSuccess || code == 500) {
  1882. SPUtils.clearUpdateLockPoint(context)
  1883. SPUtils.clearUpdateKeyReturn(context)
  1884. }
  1885. }
  1886. }
  1887. val returnList =
  1888. SPUtils.getUpdateKeyReturn(context).filter { it.keyNfc.isNotEmpty() }.toMutableList()
  1889. if (returnList.isEmpty()) {
  1890. return
  1891. }
  1892. val itemsToRemove = returnList.toList()
  1893. var count = 0
  1894. itemsToRemove.forEach { itData ->
  1895. NetApi.updateKeyReturn(
  1896. itData.ticketId, itData.keyNfc, context.serialNo()
  1897. ) { isSuccess, msg, code ->
  1898. count++
  1899. if (isSuccess || msg == MyApplication.instance?.applicationContext!!.getString(
  1900. R.string.ticket_lost
  1901. )
  1902. ) {
  1903. returnList.remove(itData)
  1904. getBleBeanByRfid(itData.keyNfc)?.bleDevice?.let {
  1905. switchReadyMode(it)
  1906. }
  1907. if (msg == MyApplication.instance?.applicationContext!!.getString(
  1908. R.string.ticket_lost
  1909. )
  1910. ) {
  1911. sendEventMsg(
  1912. MsgEvent(
  1913. MsgEventConstants.MSG_EVENT_TICKET_FINISHED, null
  1914. )
  1915. )
  1916. }
  1917. }
  1918. if (count == itemsToRemove.size) {
  1919. if (returnList.isEmpty()) {
  1920. SPUtils.clearUpdateKeyReturn(context)
  1921. } else {
  1922. returnList.forEach {
  1923. SPUtils.saveUpdateKeyReturn(context, it)
  1924. }
  1925. }
  1926. }
  1927. }
  1928. }
  1929. }
  1930. fun sendLoadingEventMsg(str: String?, isShow: Boolean = true) {
  1931. sendEventMsg(MsgEvent(MSG_EVENT_LOADING, LoadingMsg(isShow, str, false)))
  1932. }
  1933. fun logout(context: Context) {
  1934. reConnectKey()
  1935. NetApi.logout()
  1936. // 关所有有设备的卡扣
  1937. dockList.filter { it.type == DOCK_TYPE_LOCK || it.type == DOCK_TYPE_PORTABLE }
  1938. .forEach { dockBean ->
  1939. val hasLockIdxList =
  1940. dockBean.getLockList().filter { it.isExist }.map { it.idx } as MutableList<Int>
  1941. val noLockIdxList =
  1942. dockBean.getLockList().filter { !it.isExist }.map { it.idx } as MutableList<Int>
  1943. ModBusController.controlLockBuckle(false, dockBean.addr, hasLockIdxList)
  1944. ModBusController.controlLockBuckle(true, dockBean.addr, noLockIdxList)
  1945. }
  1946. dockList.filter { it.type == DOCK_TYPE_KEY || it.type == DOCK_TYPE_PORTABLE }
  1947. .forEach { dockBean ->
  1948. dockBean.getKeyList().forEach { key ->
  1949. if (key.isExist) {
  1950. NetApi.getKeyInfo(key.rfid.toString()) {
  1951. if (it != null && !it.macAddress.isNullOrEmpty()) {
  1952. ModBusController.updateKeyMac(
  1953. dockBean.addr, key.isLeft, it.macAddress
  1954. )
  1955. } else {
  1956. ModBusController.controlKeyBuckle(
  1957. true, key.isLeft, dockBean.addr
  1958. )
  1959. }
  1960. }
  1961. } else {
  1962. ModBusController.controlKeyBuckle(true, key.isLeft, dockBean.addr)
  1963. }
  1964. }
  1965. }
  1966. launchDisconnectAllJob()
  1967. sendLoadingEventMsg(null, false)
  1968. context.startActivity(Intent(context, LoginActivity::class.java).apply {
  1969. flags = Intent.FLAG_ACTIVITY_NEW_TASK
  1970. })
  1971. }
  1972. /**
  1973. * 钥匙重新连接,清除内部作业票,清除所有代取设备重新分配
  1974. */
  1975. private fun reConnectKey() {
  1976. val keyList = mDeviceTakeList.filter { it.deviceType == DEVICE_TYPE_KEY }
  1977. // 不拿的设备不归你,下次登录重新按需分配
  1978. // 尽早clear,防止触发handleCurrentMode导致重新下发作业票
  1979. mDeviceTakeList.clear()
  1980. // 连接后直接切换待机模式,让钥匙作业票失效并且重新准备完毕
  1981. keyList.forEach {
  1982. val mac = ModBusController.getKeyByRfid(it.nfc)?.mac
  1983. if (mac == null) {
  1984. NetApi.getKeyInfo(it.nfc) { keyInfo ->
  1985. keyInfo?.macAddress?.let { itMac ->
  1986. registerConnectListener(itMac) { isDone, bleBean ->
  1987. if (isDone && bleBean != null) {
  1988. switchReadyMode(bleBean.bleDevice)
  1989. }
  1990. }
  1991. }
  1992. }
  1993. } else {
  1994. registerConnectListener(mac) { isDone, bleBean ->
  1995. if (isDone && bleBean != null) {
  1996. switchReadyMode(bleBean.bleDevice)
  1997. }
  1998. }
  1999. }
  2000. }
  2001. }
  2002. /**
  2003. * 强制使用setValue,防止postValue造成数据丢失
  2004. */
  2005. fun sendEventMsg(msgEvent: MsgEvent) {
  2006. Executor.runOnMain {
  2007. mEventBus.value = msgEvent
  2008. }
  2009. }
  2010. fun addExceptionKey(rfid: String) {
  2011. LogUtil.w("addExceptionKey: $rfid")
  2012. if (mExceptionKeyList.contains(rfid)) {
  2013. return
  2014. }
  2015. mExceptionKeyList.add(rfid)
  2016. }
  2017. fun removeExceptionKey(key: String) {
  2018. LogUtil.i("removeExceptionKey: $key")
  2019. mExceptionKeyList.remove(key)
  2020. }
  2021. }