2025-10-18 21:11:16 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
import time
|
|
|
|
|
import serial
|
|
|
|
|
from serial.serialutil import SerialException
|
|
|
|
|
|
|
|
|
|
|
2025-10-26 05:07:24 +00:00
|
|
|
def open_serial(port: str, baud: int, *, timeout: float = 0.1, reset: bool = False, **kwargs) -> serial.Serial:
|
2025-10-18 21:11:16 +00:00
|
|
|
try:
|
2025-10-26 05:07:24 +00:00
|
|
|
ser = serial.Serial(port, baud, timeout=timeout, **kwargs)
|
2025-10-18 21:11:16 +00:00
|
|
|
except Exception as e:
|
2025-10-23 13:59:30 +00:00
|
|
|
raise SerialException(f"cannot open {port}: {e}")
|
2025-10-18 21:11:16 +00:00
|
|
|
|
|
|
|
|
# default: release control lines
|
|
|
|
|
try:
|
|
|
|
|
ser.dtr = False
|
|
|
|
|
ser.rts = False
|
|
|
|
|
except Exception:
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
if reset:
|
|
|
|
|
try:
|
|
|
|
|
ser.dtr = True
|
|
|
|
|
ser.rts = True
|
|
|
|
|
time.sleep(0.05)
|
|
|
|
|
ser.dtr = False
|
|
|
|
|
ser.rts = False
|
|
|
|
|
except Exception:
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
# clear any pending bytes
|
|
|
|
|
try:
|
|
|
|
|
ser.reset_input_buffer()
|
|
|
|
|
ser.reset_output_buffer()
|
|
|
|
|
except Exception:
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
return ser
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def safe_close(ser: serial.Serial | None) -> None:
|
2025-10-23 13:59:30 +00:00
|
|
|
"""
|
|
|
|
|
Close a serial port, ignoring errors.
|
|
|
|
|
"""
|
2025-10-18 21:11:16 +00:00
|
|
|
if ser is None:
|
|
|
|
|
return
|
|
|
|
|
try:
|
|
|
|
|
ser.close()
|
|
|
|
|
except Exception:
|
|
|
|
|
pass
|