desc:串口代码
							parent
							
								
									ea016fd170
								
							
						
					
					
						commit
						b981573529
					
				| @ -0,0 +1,66 @@ | ||||
| package com.yinuo.safetywatcher.watcher.port | ||||
| 
 | ||||
| import kotlinx.coroutines.DelicateCoroutinesApi | ||||
| import kotlinx.coroutines.Dispatchers | ||||
| import kotlinx.coroutines.GlobalScope | ||||
| import kotlinx.coroutines.delay | ||||
| import kotlinx.coroutines.launch | ||||
| 
 | ||||
| object GasUtils { | ||||
|     private const val BAUD_RATE = 9600 | ||||
|     private const val FULL_MSG_SIZE = 9 | ||||
|     private val mPortFlags = booleanArrayOf(false, false, false, false) | ||||
| 
 | ||||
|     fun initPort() { | ||||
|         openPorts() | ||||
|         watchPortFlag() | ||||
|     } | ||||
| 
 | ||||
|     private fun openPorts() { | ||||
|         if (!mPortFlags[0]) { | ||||
|             PlatformMultiPortUtils.openPort("/dev/tyyS0", BAUD_RATE) { | ||||
|                 mPortFlags[0] = true | ||||
|                 if (it.isNotEmpty() && it.size >= FULL_MSG_SIZE) { | ||||
|                     val checkSum = getCheckSum(it) | ||||
|                     // 校验通过 | ||||
|                     if (checkSum == it[8]) { | ||||
|                         val gasName = it[1] | ||||
|                         val gasUnit = it[2] | ||||
|                         val gasValue: Double = (it[4] * 256 + it[5]) / 100.00 | ||||
|                     } | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|         if (!mPortFlags[1]) { | ||||
|             PlatformMultiPortUtils.openPort("/dev/tyyS1", BAUD_RATE) {} | ||||
|         } | ||||
|         if (!mPortFlags[2]) { | ||||
|             PlatformMultiPortUtils.openPort("/dev/tyyS2", BAUD_RATE) {} | ||||
|         } | ||||
|         if (!mPortFlags[3]) { | ||||
|             PlatformMultiPortUtils.openPort("/dev/tyyS3", BAUD_RATE) {} | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     // 监控串口状态 | ||||
|     @OptIn(DelicateCoroutinesApi::class) | ||||
|     private fun watchPortFlag() { | ||||
|         GlobalScope.launch(Dispatchers.Default) { | ||||
|             while (true) { | ||||
|                 delay(30000) | ||||
|                 openPorts() | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| 
 | ||||
|     private fun getCheckSum(bytes: ByteArray?): Byte { | ||||
|         var sum: Int = 0 | ||||
|         bytes?.forEachIndexed { index, byte -> | ||||
|             if (index != 0 && index < FULL_MSG_SIZE - 1) { | ||||
|                 sum += (byte.toInt() and 0xff) | ||||
|             } | ||||
|         } | ||||
|         return (sum.inv() + 1).toByte() | ||||
|     } | ||||
| } | ||||
					Loading…
					
					
				
		Reference in New Issue