From a3163cd4de44acf55f499fbcb4ad63a77aeaaf02 Mon Sep 17 00:00:00 2001 From: MTing Date: Fri, 26 Sep 2025 09:34:18 +0800 Subject: [PATCH] 485 fix --- app/build.gradle | 2 +- .../main/java/com/ouxuan/oxface/device/Ox485.java | 37 +++++++++++++--------- 2 files changed, 23 insertions(+), 16 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index edc5e83..04d6421 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -12,7 +12,7 @@ android { minSdk 21 targetSdk 35 versionCode 1 - versionName "1.0.0.1" + versionName "1.0.0.2" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" diff --git a/app/src/main/java/com/ouxuan/oxface/device/Ox485.java b/app/src/main/java/com/ouxuan/oxface/device/Ox485.java index 025c925..f16dd5b 100644 --- a/app/src/main/java/com/ouxuan/oxface/device/Ox485.java +++ b/app/src/main/java/com/ouxuan/oxface/device/Ox485.java @@ -211,35 +211,38 @@ public class Ox485 { public void onDataReceived(byte[] bytes) { long timeInterval = (System.nanoTime() - lastRecvTime) / 1000000; lastRecvTime = System.nanoTime(); - + String hexData = ByteUtils.bytesToHexString(bytes); LogManager.logInfo(TAG, "Ox485接收到数据: " + hexData + ", 字节数组: " + java.util.Arrays.toString(bytes) + ", 数据长度: " + bytes.length); - + // 数据包过滤:只处理以[15, 3, 4, 0]开头的正常响应数据包 if (!isNormalResponsePacket(bytes)) { LogManager.logInfo(TAG, "Ox485接收到非正常响应数据包,已过滤: " + hexData + ", 期望格式: [15, 3, 4, 0]"); - // 即用即连模式下,收到任何数据都关闭连接 - closeAndCleanup(serialPortManager); + // 对于非正常数据包,不关闭连接,继续等待正确的数据 return; } - - // 取消超时处理 + + // 取消超时处理 - 只有收到正确的数据包才取消超时 cancelTimeout(); - + // 解析人数数据 int peopleNum = get485PeopleNum(bytes); if (peopleNum >= 0) { LogManager.logInfo(TAG, "485获取人数成功: " + peopleNum); - // 完成后关闭连接 + + // 立即关闭连接,避免后续无用数据干扰 closeAndCleanup(serialPortManager); + if (callback != null) { mainHandler.post(() -> callback.onSuccess(peopleNum)); } } else { String errorMsg = "485数据解析失败,数据: " + hexData; LogManager.logError(TAG, errorMsg); - // 完成后关闭连接 + + // 数据解析失败,关闭连接 closeAndCleanup(serialPortManager); + if (callback != null) { mainHandler.post(() -> callback.onError(errorMsg)); } @@ -607,13 +610,20 @@ public class Ox485 { private void closeAndCleanup(SerialPortManager serialPortManager) { if (serialPortManager != null) { try { + // 取消超时任务,避免在关闭过程中触发超时回调 + cancelTimeout(); + + // 等待一小段时间,确保正在接收的数据能够被处理 + // 这是为了解决数据在串口关闭后才被处理的问题 + Thread.sleep(200); + // 先停止读写线程 serialPortManager.stopReadThread(); serialPortManager.stopSendThread(); - - // 等待一小段时间确保线程停止 + + // 再次等待,确保线程完全停止 Thread.sleep(100); - + // 关闭串口 serialPortManager.closeSerialPort(); LogManager.logInfo(TAG, "485串口已关闭并清理资源"); @@ -621,9 +631,6 @@ public class Ox485 { LogManager.logError(TAG, "关闭485串口时发生异常: " + e.getMessage(), e); } } - - // 强制清理超时任务 - cancelTimeout(); } /**