|
|
@ -218,28 +218,31 @@ public class Ox485 { |
|
|
|
// 数据包过滤:只处理以[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,11 +610,18 @@ public class Ox485 { |
|
|
|
private void closeAndCleanup(SerialPortManager serialPortManager) { |
|
|
|
if (serialPortManager != null) { |
|
|
|
try { |
|
|
|
// 取消超时任务,避免在关闭过程中触发超时回调 |
|
|
|
cancelTimeout(); |
|
|
|
|
|
|
|
// 等待一小段时间,确保正在接收的数据能够被处理 |
|
|
|
// 这是为了解决数据在串口关闭后才被处理的问题 |
|
|
|
Thread.sleep(200); |
|
|
|
|
|
|
|
// 先停止读写线程 |
|
|
|
serialPortManager.stopReadThread(); |
|
|
|
serialPortManager.stopSendThread(); |
|
|
|
|
|
|
|
// 等待一小段时间确保线程停止 |
|
|
|
// 再次等待,确保线程完全停止 |
|
|
|
Thread.sleep(100); |
|
|
|
|
|
|
|
// 关闭串口 |
|
|
@ -621,9 +631,6 @@ public class Ox485 { |
|
|
|
LogManager.logError(TAG, "关闭485串口时发生异常: " + e.getMessage(), e); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
// 强制清理超时任务 |
|
|
|
cancelTimeout(); |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|