serial_port.py 28 KB

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