serial_port.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. import serial
  2. import serial.tools.list_ports
  3. import threading
  4. import time
  5. import logging
  6. import platform
  7. import glob
  8. import queue
  9. from dataclasses import dataclass
  10. # 配置日志
  11. logging.basicConfig(
  12. level=logging.INFO,
  13. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
  14. )
  15. logger = logging.getLogger('serial_port')
  16. @dataclass
  17. class SerialConfig:
  18. """串口配置数据类"""
  19. port: str
  20. baudrate: int = 115200
  21. bytesize: int = serial.EIGHTBITS
  22. parity: str = serial.PARITY_NONE
  23. stopbits: int = serial.STOPBITS_ONE
  24. timeout: float = 1.0
  25. xonxoff: bool = False
  26. rtscts: bool = False
  27. dsrdtr: bool = False
  28. class SerialPort:
  29. """串口通信类,提供串口连接、读写和状态管理功能"""
  30. def __init__(self):
  31. self.ser = None
  32. self.is_connected = False
  33. self.lock = threading.RLock() # 使用可重入锁
  34. self.read_thread = None
  35. self.stop_event = threading.Event()
  36. self.data_callback = None
  37. self.send_callback = None
  38. self.status_callback = None
  39. self.error_callback = None
  40. self.current_config = None
  41. self.reconnect_attempts = 0
  42. self.max_reconnect_attempts = 3
  43. self.raw_response_buffer = []
  44. self._reconnect_monitor_thread = None
  45. # 同步接收模式:send_and_wait 活动时暂停后台读取线程,防止响应被读线程抢走
  46. self._sync_receive_active = False
  47. self._sync_lock = threading.Lock()
  48. # 串口发送队列:所有发送指令统一排队,按固定节拍(发送起点间隔)逐个发送,
  49. # 既避免总线冲突,也保证相邻指令(如 0x80 保活 与 0x03 读卡)不会背靠背贴得太近。
  50. self._cmd_queue = queue.Queue()
  51. self._cmd_min_interval = 0.05 # 相邻指令「发送起点」最小间隔(秒),默认值
  52. self._post_tx_delay = 0.005 # 发完一帧到开始接收的等待(秒)
  53. self._rx_poll_interval = 0.002 # 接收轮询粒度(秒)
  54. self._rx_tail = 0.005 # 收够最小长度后等待总线静默的时间(秒)
  55. try:
  56. import config as _app_config
  57. self._cmd_min_interval = float(getattr(_app_config, 'SERIAL_CMD_INTERVAL', 0.05))
  58. self._post_tx_delay = float(getattr(_app_config, 'SERIAL_POST_TX_DELAY', 0.005))
  59. self._rx_poll_interval = float(getattr(_app_config, 'SERIAL_RX_POLL_INTERVAL', 0.002))
  60. self._rx_tail = float(getattr(_app_config, 'SERIAL_RX_TAIL', 0.005))
  61. except Exception:
  62. pass
  63. self._next_cmd_time = 0.0 # 下一条指令允许开始发送的时刻(发送起点锚点)
  64. self._cmd_worker_thread = threading.Thread(target=self._cmd_worker, daemon=True)
  65. self._cmd_worker_thread.start()
  66. # 启动后台重连监控线程,确保断线后可持续自动恢复
  67. self._start_reconnect_monitor()
  68. def _cmd_worker(self):
  69. """串口发送队列工作线程:统一按「发送起点」固定节拍逐个发送指令"""
  70. logger.info("启动串口发送队列工作线程")
  71. while True:
  72. try:
  73. item = self._cmd_queue.get()
  74. if item is None:
  75. break
  76. # 以「开始发送的时刻」为锚保证等间隔:把本条命令排到上一条起拍之后
  77. # 满一个节拍。若上一条命令本身耗时超过一个节拍(如读卡等满超时),
  78. # 则不补觉、立刻发(半双工总线上不可能重叠,也不回溯过去的时间)。
  79. now = time.time()
  80. if now < self._next_cmd_time:
  81. time.sleep(self._next_cmd_time - now)
  82. cmd_type = item.get('type')
  83. # 记录本条「发送起点」,下一条以此为基准排满一个节拍
  84. send_start = time.time()
  85. self._next_cmd_time = send_start + self._cmd_min_interval
  86. try:
  87. if cmd_type == 'send_and_wait':
  88. result = self._do_send_and_wait(
  89. item['data'],
  90. timeout=item.get('timeout', 2.0),
  91. min_response_bytes=item.get('min_response_bytes', 1)
  92. )
  93. elif cmd_type == 'wait_response':
  94. result = self._do_wait_response(
  95. timeout=item.get('timeout', 2.0),
  96. min_response_bytes=item.get('min_response_bytes', 1)
  97. )
  98. elif cmd_type == 'send_raw':
  99. result = self._do_send_raw(item['data'])
  100. elif cmd_type == 'send_data':
  101. result = self._do_send_data(item['data'], item.get('encoding', 'utf-8'))
  102. else:
  103. result = {'error': f'未知命令类型: {cmd_type}'}
  104. except Exception as e:
  105. logger.error(f"执行串口命令失败: {e}")
  106. result = {'error': str(e)}
  107. callback = item.get('callback')
  108. if callback:
  109. callback(result)
  110. except Exception as e:
  111. logger.error(f"串口发送队列工作线程异常: {e}")
  112. logger.info("串口发送队列工作线程结束")
  113. def _write_and_flush(self, data: bytes) -> int:
  114. """写串口并 flush(tcdrain),确保最后一位真正发完"""
  115. sent = self.ser.write(data)
  116. self.ser.flush()
  117. return sent
  118. def _do_send_raw(self, data: bytes):
  119. """实际执行 send_raw(在队列工作线程中调用)"""
  120. try:
  121. with self.lock:
  122. if not self.is_connected or not self.ser or not self.ser.is_open:
  123. return False, "serial port not connected"
  124. bytes_sent = self._write_and_flush(data)
  125. if self.send_callback and data:
  126. self.send_callback(data.hex())
  127. return True, "send ok"
  128. except Exception as e:
  129. error_msg = f"send raw failed: {str(e)}"
  130. logger.error(error_msg)
  131. if self.error_callback:
  132. self.error_callback(error_msg)
  133. return False, error_msg
  134. def _do_send_data(self, data, encoding='utf-8'):
  135. """实际执行 send_data(在队列工作线程中调用)"""
  136. try:
  137. with self.lock:
  138. if not self.is_connected or not self.ser or not self.ser.is_open:
  139. return False, "串口未连接"
  140. # 确保数据以换行符结束
  141. if isinstance(data, str):
  142. if not data.endswith('\n'):
  143. data += '\n'
  144. bytes_data = data.encode(encoding)
  145. elif isinstance(data, bytes):
  146. if not data.endswith(b'\n'):
  147. bytes_data = data + b'\n'
  148. else:
  149. bytes_data = data
  150. else:
  151. raise TypeError("数据必须是字符串或字节类型")
  152. bytes_sent = self._write_and_flush(bytes_data)
  153. logger.debug(f"发送数据到串口: {bytes_data.hex()[:50]}... (共{bytes_sent}字节)")
  154. return True, "发送成功"
  155. except Exception as e:
  156. error_msg = f"发送失败: {str(e)}"
  157. logger.error(error_msg)
  158. if self.error_callback:
  159. self.error_callback(error_msg)
  160. return False, error_msg
  161. def _emit_received_data(self, data: bytes):
  162. """把接收到的原始数据推送给 data_callback(与后台读线程行为一致)"""
  163. if not data or not self.data_callback:
  164. return
  165. hex_data = data.hex()
  166. self.data_callback(hex_data)
  167. try:
  168. decoded = data.decode('utf-8').strip()
  169. if decoded:
  170. self.data_callback(decoded)
  171. except Exception:
  172. pass
  173. def _do_send_and_wait(self, data: bytes, timeout: float = 2.0, min_response_bytes: int = 1) -> bytes:
  174. """实际执行 send_and_wait(在队列工作线程中调用)。
  175. 大线架量(上百台)时本函数是轮询的主要耗时来源,故:
  176. - 发完不固定睡 30ms,只留极短的收发器换向间隔;
  177. - 收够 min_response_bytes 后不再固定睡 50ms,改为等总线静默 SERIAL_RX_TAIL 即返回。
  178. """
  179. # 进入同步接收模式,暂停后台读取线程
  180. with self._sync_lock:
  181. self._sync_receive_active = True
  182. try:
  183. # 阶段 1:发送数据并清空缓冲区
  184. with self.lock:
  185. if not self.ser or not self.ser.is_open:
  186. return b''
  187. self.raw_response_buffer.clear()
  188. self.ser.reset_input_buffer()
  189. self._write_and_flush(data)
  190. if self._post_tx_delay > 0:
  191. time.sleep(self._post_tx_delay)
  192. if self.send_callback and data:
  193. self.send_callback(data.hex())
  194. # 阶段 2:等待响应。由于后台读线程已暂停,这里独占串口读取。
  195. response = b''
  196. start = time.time()
  197. last_data_time = start
  198. while time.time() - start < timeout:
  199. # 先清掉缓冲区内可能残留的报文(正常情况下 sync 模式下读线程不会写入)
  200. chunk = b''
  201. with self.lock:
  202. while self.raw_response_buffer:
  203. try:
  204. chunk += bytes.fromhex(self.raw_response_buffer.pop(0))
  205. except Exception:
  206. pass
  207. try:
  208. if self.ser and self.ser.is_open and self.ser.in_waiting > 0:
  209. chunk += self.ser.read(self.ser.in_waiting)
  210. except Exception:
  211. pass
  212. if chunk:
  213. response += chunk
  214. last_data_time = time.time()
  215. # 收够最小长度且总线已静默 -> 一帧结束,立即返回(不再固定等 50ms)
  216. if len(response) >= min_response_bytes and (time.time() - last_data_time) >= self._rx_tail:
  217. self._emit_received_data(response)
  218. return response
  219. time.sleep(self._rx_poll_interval)
  220. self._emit_received_data(response)
  221. return response
  222. finally:
  223. # 退出同步接收模式,恢复后台读取线程
  224. with self._sync_lock:
  225. self._sync_receive_active = False
  226. def _do_wait_response(self, timeout: float = 2.0, min_response_bytes: int = 1) -> bytes:
  227. """实际执行 wait_response(在队列工作线程中调用)。
  228. 与 _do_send_and_wait 的区别:
  229. - 不发送任何数据(不 write),因此不触发 send_callback,不会在前端产生空 JSON;
  230. - 不清空接收缓冲(不 reset_input_buffer),避免把从机已回的应答冲掉。
  231. 用于发送完指令(send_raw)后专门等待从机应答。
  232. 收到 min_response_bytes 字节后,继续等到总线空闲(100ms 无新数据)再返回,
  233. 以便把回显与真实应答一并收齐后再交由调用方解析。
  234. """
  235. # 进入同步接收模式,暂停后台读取线程,独占串口读取
  236. with self._sync_lock:
  237. self._sync_receive_active = True
  238. try:
  239. response = b''
  240. start = time.time()
  241. last_data_time = start
  242. while time.time() - start < timeout:
  243. # 从后台读线程缓冲 + 串口硬件缓冲两处收集
  244. chunk = b''
  245. with self.lock:
  246. while self.raw_response_buffer:
  247. try:
  248. chunk += bytes.fromhex(self.raw_response_buffer.pop(0))
  249. except Exception:
  250. pass
  251. try:
  252. if self.ser and self.ser.is_open and self.ser.in_waiting > 0:
  253. chunk += self.ser.read(self.ser.in_waiting)
  254. except Exception:
  255. pass
  256. if chunk:
  257. response += chunk
  258. last_data_time = time.time()
  259. # 收够最小长度后,等总线空闲再返回,避免回显导致提前返回而漏掉真实应答
  260. if len(response) >= min_response_bytes:
  261. if time.time() - last_data_time > 0.1:
  262. self._emit_received_data(response)
  263. return response
  264. time.sleep(0.01)
  265. self._emit_received_data(response)
  266. return response
  267. finally:
  268. with self._sync_lock:
  269. self._sync_receive_active = False
  270. def list_ports(self):
  271. """列出系统中可用的串口"""
  272. ports = []
  273. try:
  274. # 首先尝试使用serial.tools.list_ports
  275. try:
  276. detected_ports = [port.device for port in serial.tools.list_ports.comports()]
  277. ports.extend(detected_ports)
  278. except Exception as e:
  279. logger.warning(f"使用serial.tools.list_ports失败: {str(e)}")
  280. # 根据不同平台进行补充查找
  281. system = platform.system()
  282. if system == 'Windows':
  283. try:
  284. import winreg
  285. # 在Windows系统中读取注册表
  286. key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
  287. r'HARDWARE\DEVICEMAP\SERIALCOMM')
  288. i = 0
  289. while True:
  290. try:
  291. port, value, _ = winreg.EnumValue(key, i)
  292. if value not in ports:
  293. ports.append(value)
  294. i += 1
  295. except OSError:
  296. break
  297. except Exception as e:
  298. logger.error(f"读取Windows串口注册表失败: {str(e)}")
  299. elif system == 'Darwin': # macOS
  300. # 使用glob查找/dev/tty.*设备
  301. darwin_ports = glob.glob('/dev/tty.*')
  302. # 过滤掉不需要的端口
  303. for port in darwin_ports:
  304. if not ('Bluetooth' in port or 'debug' in port or 'com.apple' in port) and port not in ports:
  305. ports.append(port)
  306. elif system == 'Linux':
  307. # 使用glob查找Linux系统中的串口
  308. linux_ports = glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*')
  309. for port in linux_ports:
  310. if port not in ports:
  311. ports.append(port)
  312. logger.info(f"找到 {len(ports)} 个可用串口: {ports}")
  313. except Exception as e:
  314. logger.error(f"列出串口时出错: {str(e)}")
  315. return sorted(ports) # 排序返回
  316. def connect(self, port, baudrate=9600, timeout=1, **kwargs):
  317. """连接到串口"""
  318. try:
  319. # 构建配置
  320. config = SerialConfig(
  321. port=port,
  322. baudrate=baudrate,
  323. timeout=timeout,
  324. **kwargs
  325. )
  326. with self.lock:
  327. if self.is_connected:
  328. # RLock 允许递归,避免死锁
  329. self.disconnect()
  330. # serial.Serial() 可能阻塞(端口被占用等),不要在持有锁的情况下调用,
  331. # 否则 disconnect() 会长时间等待锁而无法响应。
  332. logger.info(f"尝试连接串口: {port}, 波特率: {baudrate}")
  333. ser = serial.Serial(
  334. port=config.port,
  335. baudrate=config.baudrate,
  336. bytesize=config.bytesize,
  337. parity=config.parity,
  338. stopbits=config.stopbits,
  339. timeout=config.timeout,
  340. xonxoff=config.xonxoff,
  341. rtscts=config.rtscts,
  342. dsrdtr=config.dsrdtr
  343. )
  344. # 检查连接是否成功
  345. if not ser.is_open:
  346. ser.close()
  347. raise Exception("串口打开失败")
  348. with self.lock:
  349. self.ser = ser
  350. self.is_connected = True
  351. self.stop_event.clear()
  352. self.current_config = config
  353. self.reconnect_attempts = 0
  354. # 启动读取线程
  355. self.read_thread = threading.Thread(target=self._read_loop, daemon=True)
  356. self.read_thread.start()
  357. if self.status_callback:
  358. self.status_callback(True)
  359. logger.info(f"已连接到 {port},波特率 {baudrate}")
  360. return True, f"已连接到 {port},波特率 {baudrate}"
  361. except Exception as e:
  362. error_msg = f"连接失败: {str(e)}"
  363. logger.error(error_msg)
  364. if self.status_callback:
  365. self.status_callback(False)
  366. if self.error_callback:
  367. self.error_callback(error_msg)
  368. return False, error_msg
  369. def disconnect(self):
  370. """断开串口连接"""
  371. try:
  372. logger.info("断开串口连接")
  373. # 阶段 0:清空发送队列中待执行的指令,避免断开后再发数据
  374. try:
  375. while not self._cmd_queue.empty():
  376. self._cmd_queue.get_nowait()
  377. except Exception:
  378. pass
  379. # 阶段 1:通知读取线程退出,不要在持有锁的情况下 join,
  380. # 否则读取线程异常时调用 _close_on_error 会拿不到锁而死锁。
  381. with self.lock:
  382. self.stop_event.set()
  383. if self.read_thread and self.read_thread.is_alive():
  384. self.read_thread.join(timeout=2.0)
  385. if self.read_thread.is_alive():
  386. logger.warning("读取线程未能正常终止")
  387. # 阶段 2:关闭串口并清理状态
  388. with self.lock:
  389. if self.ser and self.ser.is_open:
  390. try:
  391. self.ser.close()
  392. except Exception as e:
  393. logger.error(f"关闭串口时出错: {str(e)}")
  394. self.ser = None
  395. self.is_connected = False
  396. self.current_config = None
  397. if self.status_callback:
  398. self.status_callback(False)
  399. return True, "已断开连接"
  400. except Exception as e:
  401. error_msg = f"断开连接失败: {str(e)}"
  402. logger.error(error_msg)
  403. if self.error_callback:
  404. self.error_callback(error_msg)
  405. return False, error_msg
  406. def _read_loop(self):
  407. """读取串口数据的循环"""
  408. logger.info("启动串口读取线程")
  409. while not self.stop_event.is_set():
  410. try:
  411. # send_and_wait 正在同步接收时,后台读线程让出总线,
  412. # 避免读线程把响应抢走导致同步调用超时。
  413. with self._sync_lock:
  414. sync_active = self._sync_receive_active
  415. if sync_active:
  416. time.sleep(0.001)
  417. continue
  418. if self.ser and self.ser.is_open:
  419. # 使用in_waiting提高效率
  420. if self.ser.in_waiting > 0:
  421. data = self.ser.read(self.ser.in_waiting)
  422. # 默认将原始数据以十六进制存入缓冲区
  423. hex_data = data.hex()
  424. with self.lock:
  425. self.raw_response_buffer.append(hex_data)
  426. if self.data_callback:
  427. self.data_callback(hex_data)
  428. # 如果能解码为文本,也通知回调
  429. try:
  430. decoded_data = data.decode('utf-8').strip()
  431. if decoded_data and self.data_callback:
  432. self.data_callback(decoded_data)
  433. except:
  434. pass
  435. time.sleep(0.001)
  436. except Exception as e:
  437. error_msg = f"读取串口数据错误: {str(e)}"
  438. logger.error(error_msg)
  439. if self.error_callback:
  440. self.error_callback(error_msg)
  441. # 读取线程只负责关闭当前连接并通知,重连由独立监控线程负责,
  442. # 避免在读取线程内调用 connect() 造成自连接/自 join 的问题
  443. self._close_on_error()
  444. break
  445. # 线程结束时清理资源
  446. logger.info("串口读取线程结束")
  447. def _close_on_error(self):
  448. """读取异常时关闭串口并触发状态回调,但不直接重连"""
  449. with self.lock:
  450. if self.ser and self.ser.is_open:
  451. try:
  452. self.ser.close()
  453. except Exception:
  454. pass
  455. self.ser = None
  456. self.is_connected = False
  457. if self.status_callback:
  458. try:
  459. self.status_callback(False)
  460. except Exception:
  461. pass
  462. logger.warning("串口因读取错误已关闭,等待重连监控线程恢复")
  463. def _start_reconnect_monitor(self):
  464. """启动独立后台线程,在串口断开时持续尝试重连"""
  465. if getattr(self, '_reconnect_monitor_thread', None) and self._reconnect_monitor_thread.is_alive():
  466. return
  467. self._reconnect_monitor_thread = threading.Thread(target=self._reconnect_monitor, daemon=True)
  468. self._reconnect_monitor_thread.start()
  469. def _reconnect_monitor(self):
  470. """后台重连监控:只要保存过配置就无限重试,成功则重置计数"""
  471. logger.info("启动串口重连监控线程")
  472. while True:
  473. try:
  474. with self.lock:
  475. connected = self.is_connected
  476. config = self.current_config
  477. if not connected and config is not None:
  478. self.reconnect_attempts += 1
  479. attempt = self.reconnect_attempts
  480. logger.warning(f"重连监控尝试连接串口... (第{attempt}次)")
  481. success, msg = self.connect(
  482. port=config.port,
  483. baudrate=config.baudrate,
  484. timeout=config.timeout,
  485. bytesize=config.bytesize,
  486. parity=config.parity,
  487. stopbits=config.stopbits,
  488. xonxoff=config.xonxoff,
  489. rtscts=config.rtscts,
  490. dsrdtr=config.dsrdtr
  491. )
  492. if not success:
  493. # 指数退避,最长 30 秒
  494. delay = min(30, 2 + attempt * 2)
  495. logger.warning(f"重连失败: {msg},{delay}秒后再次尝试")
  496. time.sleep(delay)
  497. else:
  498. logger.info("串口重连成功")
  499. else:
  500. # 已连接或未保存配置时,重置失败计数并降低检查频率
  501. if connected:
  502. self.reconnect_attempts = 0
  503. time.sleep(3)
  504. except Exception as e:
  505. logger.error(f"重连监控线程异常: {e}")
  506. time.sleep(5)
  507. def send_data(self, data, encoding='utf-8'):
  508. """发送数据到串口(入队,由队列工作线程统一发送)"""
  509. result_container = {}
  510. event = threading.Event()
  511. def callback(result):
  512. result_container['result'] = result
  513. event.set()
  514. self._cmd_queue.put({
  515. 'type': 'send_data',
  516. 'data': data,
  517. 'encoding': encoding,
  518. 'callback': callback
  519. })
  520. # 最多等待 5 秒,避免队列卡死导致调用方永远阻塞
  521. if not event.wait(5):
  522. return False, "串口发送队列超时"
  523. return result_container.get('result', (False, "未知错误"))
  524. def set_data_callback(self, callback):
  525. """设置数据接收回调函数"""
  526. self.data_callback = callback
  527. def set_send_callback(self, callback):
  528. """设置数据发送回调函数"""
  529. self.send_callback = callback
  530. def set_status_callback(self, callback):
  531. """设置状态变化回调函数"""
  532. self.status_callback = callback
  533. def set_error_callback(self, callback):
  534. """设置错误回调函数"""
  535. self.error_callback = callback
  536. def get_status(self):
  537. """获取当前连接状态"""
  538. with self.lock:
  539. return {
  540. 'connected': self.is_connected,
  541. 'config': self.current_config,
  542. 'has_error': self.reconnect_attempts > 0
  543. }
  544. def _should_reconnect(self):
  545. """判断是否应该尝试重连"""
  546. self.reconnect_attempts += 1
  547. return self.reconnect_attempts <= self.max_reconnect_attempts
  548. def send_raw(self, data: bytes):
  549. """send raw binary data without adding newline(入队,由队列工作线程统一发送)"""
  550. result_container = {}
  551. event = threading.Event()
  552. def callback(result):
  553. result_container['result'] = result
  554. event.set()
  555. self._cmd_queue.put({
  556. 'type': 'send_raw',
  557. 'data': data,
  558. 'callback': callback
  559. })
  560. # 最多等待 5 秒,避免队列卡死导致调用方永远阻塞
  561. if not event.wait(5):
  562. return False, "串口发送队列超时"
  563. return result_container.get('result', (False, "未知错误"))
  564. def flush_input(self):
  565. """清空输入缓冲区"""
  566. try:
  567. with self.lock:
  568. if self.ser and self.ser.is_open:
  569. self.ser.reset_input_buffer()
  570. return True, "输入缓冲区已清空"
  571. return False, "串口未连接"
  572. except Exception as e:
  573. error_msg = f"清空缓冲区失败: {str(e)}"
  574. logger.error(error_msg)
  575. return False, error_msg
  576. def flush_output(self):
  577. """清空输出缓冲区"""
  578. try:
  579. with self.lock:
  580. if self.ser and self.ser.is_open:
  581. self.ser.reset_output_buffer()
  582. return True, "输出缓冲区已清空"
  583. return False, "串口未连接"
  584. except Exception as e:
  585. error_msg = f"清空缓冲区失败: {str(e)}"
  586. logger.error(error_msg)
  587. return False, error_msg
  588. def send_and_wait(self, data: bytes, timeout: float = 2.0, min_response_bytes: int = 1) -> bytes:
  589. """sync send and wait(入队,由队列工作线程统一发送并等待响应)"""
  590. result_container = {}
  591. event = threading.Event()
  592. def callback(result):
  593. result_container['result'] = result
  594. event.set()
  595. self._cmd_queue.put({
  596. 'type': 'send_and_wait',
  597. 'data': data,
  598. 'timeout': timeout,
  599. 'min_response_bytes': min_response_bytes,
  600. 'callback': callback
  601. })
  602. # 最多等待 timeout + 队列处理余量
  603. wait_time = timeout + 5
  604. if not event.wait(wait_time):
  605. return b''
  606. return result_container.get('result', b'')
  607. def wait_response(self, timeout: float = 2.0, min_response_bytes: int = 1) -> bytes:
  608. """只读取从机应答,不发送任何数据(入队,由队列工作线程统一执行)。
  609. 与 send_and_wait 的区别:不 write 数据、不触发 send_callback、不清空接收缓冲。
  610. 用于发送完指令(send_raw)后等待从机应答,避免发空数据污染前端显示、
  611. 避免清缓冲冲掉已到达的应答。
  612. """
  613. result_container = {}
  614. event = threading.Event()
  615. def callback(result):
  616. result_container['result'] = result
  617. event.set()
  618. self._cmd_queue.put({
  619. 'type': 'wait_response',
  620. 'timeout': timeout,
  621. 'min_response_bytes': min_response_bytes,
  622. 'callback': callback
  623. })
  624. # 最多等待 timeout + 队列处理余量
  625. wait_time = timeout + 5
  626. if not event.wait(wait_time):
  627. return b''
  628. return result_container.get('result', b'')