|
@@ -195,17 +195,23 @@ class SerialPort:
|
|
|
# 同步接收模式:send_and_wait 活动时暂停后台读取线程,防止响应被读线程抢走
|
|
# 同步接收模式:send_and_wait 活动时暂停后台读取线程,防止响应被读线程抢走
|
|
|
self._sync_receive_active = False
|
|
self._sync_receive_active = False
|
|
|
self._sync_lock = threading.Lock()
|
|
self._sync_lock = threading.Lock()
|
|
|
- # 串口发送队列:所有发送指令统一排队,按最小间隔逐个发送,避免总线冲突
|
|
|
|
|
|
|
+ # 串口发送队列:所有发送指令统一排队,按固定节拍(发送起点间隔)逐个发送,
|
|
|
|
|
+ # 既避免总线冲突,也保证相邻指令(如 0x80 保活 与 0x03 读卡)不会背靠背贴得太近。
|
|
|
self._cmd_queue = queue.Queue()
|
|
self._cmd_queue = queue.Queue()
|
|
|
- self._cmd_min_interval = 0.10 # 相邻指令最小间隔 100ms
|
|
|
|
|
- self._last_cmd_time = 0
|
|
|
|
|
|
|
+ self._cmd_min_interval = 0.20 # 相邻指令「发送起点」最小间隔(秒),默认值
|
|
|
|
|
+ try:
|
|
|
|
|
+ import config as _app_config
|
|
|
|
|
+ self._cmd_min_interval = float(getattr(_app_config, 'SERIAL_CMD_INTERVAL', 0.20))
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ pass
|
|
|
|
|
+ self._next_cmd_time = 0.0 # 下一条指令允许开始发送的时刻(发送起点锚点)
|
|
|
self._cmd_worker_thread = threading.Thread(target=self._cmd_worker, daemon=True)
|
|
self._cmd_worker_thread = threading.Thread(target=self._cmd_worker, daemon=True)
|
|
|
self._cmd_worker_thread.start()
|
|
self._cmd_worker_thread.start()
|
|
|
# 启动后台重连监控线程,确保断线后可持续自动恢复
|
|
# 启动后台重连监控线程,确保断线后可持续自动恢复
|
|
|
self._start_reconnect_monitor()
|
|
self._start_reconnect_monitor()
|
|
|
|
|
|
|
|
def _cmd_worker(self):
|
|
def _cmd_worker(self):
|
|
|
- """串口发送队列工作线程:统一按最小间隔逐个发送指令"""
|
|
|
|
|
|
|
+ """串口发送队列工作线程:统一按「发送起点」固定节拍逐个发送指令"""
|
|
|
logger.info("启动串口发送队列工作线程")
|
|
logger.info("启动串口发送队列工作线程")
|
|
|
while True:
|
|
while True:
|
|
|
try:
|
|
try:
|
|
@@ -213,12 +219,17 @@ class SerialPort:
|
|
|
if item is None:
|
|
if item is None:
|
|
|
break
|
|
break
|
|
|
|
|
|
|
|
- # 确保相邻指令最小间隔
|
|
|
|
|
- elapsed = time.time() - self._last_cmd_time
|
|
|
|
|
- if elapsed < self._cmd_min_interval:
|
|
|
|
|
- time.sleep(self._cmd_min_interval - elapsed)
|
|
|
|
|
|
|
+ # 以「开始发送的时刻」为锚保证等间隔:把本条命令排到上一条起拍之后
|
|
|
|
|
+ # 满一个节拍。若上一条命令本身耗时超过一个节拍(如读卡等满超时),
|
|
|
|
|
+ # 则不补觉、立刻发(半双工总线上不可能重叠,也不回溯过去的时间)。
|
|
|
|
|
+ now = time.time()
|
|
|
|
|
+ if now < self._next_cmd_time:
|
|
|
|
|
+ time.sleep(self._next_cmd_time - now)
|
|
|
|
|
|
|
|
cmd_type = item.get('type')
|
|
cmd_type = item.get('type')
|
|
|
|
|
+ # 记录本条「发送起点」,下一条以此为基准排满一个节拍
|
|
|
|
|
+ send_start = time.time()
|
|
|
|
|
+ self._next_cmd_time = send_start + self._cmd_min_interval
|
|
|
try:
|
|
try:
|
|
|
if cmd_type == 'send_and_wait':
|
|
if cmd_type == 'send_and_wait':
|
|
|
result = self._do_send_and_wait(
|
|
result = self._do_send_and_wait(
|
|
@@ -241,8 +252,6 @@ class SerialPort:
|
|
|
logger.error(f"执行串口命令失败: {e}")
|
|
logger.error(f"执行串口命令失败: {e}")
|
|
|
result = {'error': str(e)}
|
|
result = {'error': str(e)}
|
|
|
|
|
|
|
|
- self._last_cmd_time = time.time()
|
|
|
|
|
-
|
|
|
|
|
callback = item.get('callback')
|
|
callback = item.get('callback')
|
|
|
if callback:
|
|
if callback:
|
|
|
callback(result)
|
|
callback(result)
|