Browse Source

485 fix

dev
MTing 3 weeks ago
parent
commit
a3163cd4de
  1. 2
      app/build.gradle
  2. 25
      app/src/main/java/com/ouxuan/oxface/device/Ox485.java

2
app/build.gradle

@ -12,7 +12,7 @@ android {
minSdk 21 minSdk 21
targetSdk 35 targetSdk 35
versionCode 1 versionCode 1
versionName "1.0.0.1"
versionName "1.0.0.2"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

25
app/src/main/java/com/ouxuan/oxface/device/Ox485.java

@ -218,28 +218,31 @@ public class Ox485 {
// 数据包过滤只处理以[15, 3, 4, 0]开头的正常响应数据包 // 数据包过滤只处理以[15, 3, 4, 0]开头的正常响应数据包
if (!isNormalResponsePacket(bytes)) { if (!isNormalResponsePacket(bytes)) {
LogManager.logInfo(TAG, "Ox485接收到非正常响应数据包,已过滤: " + hexData + ", 期望格式: [15, 3, 4, 0]"); LogManager.logInfo(TAG, "Ox485接收到非正常响应数据包,已过滤: " + hexData + ", 期望格式: [15, 3, 4, 0]");
// 即用即连模式下收到任何数据都关闭连接
closeAndCleanup(serialPortManager);
// 对于非正常数据包不关闭连接继续等待正确的数据
return; return;
} }
// 取消超时处理
// 取消超时处理 - 只有收到正确的数据包才取消超时
cancelTimeout(); cancelTimeout();
// 解析人数数据 // 解析人数数据
int peopleNum = get485PeopleNum(bytes); int peopleNum = get485PeopleNum(bytes);
if (peopleNum >= 0) { if (peopleNum >= 0) {
LogManager.logInfo(TAG, "485获取人数成功: " + peopleNum); LogManager.logInfo(TAG, "485获取人数成功: " + peopleNum);
// 完成后关闭连接
// 立即关闭连接避免后续无用数据干扰
closeAndCleanup(serialPortManager); closeAndCleanup(serialPortManager);
if (callback != null) { if (callback != null) {
mainHandler.post(() -> callback.onSuccess(peopleNum)); mainHandler.post(() -> callback.onSuccess(peopleNum));
} }
} else { } else {
String errorMsg = "485数据解析失败,数据: " + hexData; String errorMsg = "485数据解析失败,数据: " + hexData;
LogManager.logError(TAG, errorMsg); LogManager.logError(TAG, errorMsg);
// 完成后关闭连接
// 数据解析失败关闭连接
closeAndCleanup(serialPortManager); closeAndCleanup(serialPortManager);
if (callback != null) { if (callback != null) {
mainHandler.post(() -> callback.onError(errorMsg)); mainHandler.post(() -> callback.onError(errorMsg));
} }
@ -607,11 +610,18 @@ public class Ox485 {
private void closeAndCleanup(SerialPortManager serialPortManager) { private void closeAndCleanup(SerialPortManager serialPortManager) {
if (serialPortManager != null) { if (serialPortManager != null) {
try { try {
// 取消超时任务避免在关闭过程中触发超时回调
cancelTimeout();
// 等待一小段时间确保正在接收的数据能够被处理
// 这是为了解决数据在串口关闭后才被处理的问题
Thread.sleep(200);
// 先停止读写线程 // 先停止读写线程
serialPortManager.stopReadThread(); serialPortManager.stopReadThread();
serialPortManager.stopSendThread(); serialPortManager.stopSendThread();
// 等待一小段时间确保线程停止
// 再次等待确保线程完全停止
Thread.sleep(100); Thread.sleep(100);
// 关闭串口 // 关闭串口
@ -621,9 +631,6 @@ public class Ox485 {
LogManager.logError(TAG, "关闭485串口时发生异常: " + e.getMessage(), e); LogManager.logError(TAG, "关闭485串口时发生异常: " + e.getMessage(), e);
} }
} }
// 强制清理超时任务
cancelTimeout();
} }
/** /**

Loading…
Cancel
Save