From 81e21a21e6b18c195cda37236943b0dc007c7541 Mon Sep 17 00:00:00 2001 From: xiaowusky Date: Mon, 3 Jul 2023 16:13:05 +0800 Subject: [PATCH] =?UTF-8?q?desc:=E4=B8=B2=E5=8F=A3=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../safetywatcher/watcher/port/GasUtils.kt | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/yinuo/safetywatcher/watcher/port/GasUtils.kt b/app/src/main/java/com/yinuo/safetywatcher/watcher/port/GasUtils.kt index 3e7ee5b..6b82a94 100644 --- a/app/src/main/java/com/yinuo/safetywatcher/watcher/port/GasUtils.kt +++ b/app/src/main/java/com/yinuo/safetywatcher/watcher/port/GasUtils.kt @@ -1,15 +1,21 @@ package com.yinuo.safetywatcher.watcher.port +import android.os.Handler +import android.os.Looper import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.Runnable import kotlinx.coroutines.delay import kotlinx.coroutines.launch object GasUtils { private const val BAUD_RATE = 9600 private const val FULL_MSG_SIZE = 9 + private const val CHECK_TIME = 10000L private val mPortFlags = booleanArrayOf(false, false, false, false) + private val mPortRunnable = hashMapOf() + private val mHandler = Handler(Looper.getMainLooper()) fun initPort() { openPorts() @@ -19,7 +25,7 @@ object GasUtils { private fun openPorts() { if (!mPortFlags[0]) { PlatformMultiPortUtils.openPort("/dev/tyyS0", BAUD_RATE) { - mPortFlags[0] = true + setFlag(0) if (it.isNotEmpty() && it.size >= FULL_MSG_SIZE) { val checkSum = getCheckSum(it) // 校验通过 @@ -42,12 +48,23 @@ object GasUtils { } } + private fun setFlag(index: Int) { + var flagRunnable = mPortRunnable[index] + if (flagRunnable == null) { + flagRunnable = FlagRunnable(index) + mPortRunnable[index] = flagRunnable + } + mHandler.removeCallbacks(flagRunnable) + mPortFlags[index] = true + mHandler.postDelayed(flagRunnable, CHECK_TIME) + } + // 监控串口状态 @OptIn(DelicateCoroutinesApi::class) private fun watchPortFlag() { GlobalScope.launch(Dispatchers.Default) { while (true) { - delay(30000) + delay(CHECK_TIME) launch(Dispatchers.Main) { openPorts() } @@ -65,4 +82,10 @@ object GasUtils { } return (sum.inv() + 1).toByte() } + + class FlagRunnable(private val index: Int) : Runnable { + override fun run() { + mPortFlags[index] = false + } + } } \ No newline at end of file