Make firmware sweep cancellable to prevent shutdown deadlock

send_with_timeout now uses a 2s per-byte timeout with a deadline
loop instead of one long blocking read, checking a cancel event
between reads. SerialBridge.disconnect() sets the cancel event
before acquiring the lock, so a blocked firmware sweep aborts
within ~2s and releases the lock for clean port shutdown.
This commit is contained in:
Ryan Malloy 2026-02-14 16:56:14 -07:00
parent 2ee2f47275
commit c6ac958ee8
2 changed files with 55 additions and 9 deletions

View file

@ -63,6 +63,7 @@ class SerialBridge:
def __init__(self, protocol: CarryoutG2Protocol) -> None:
self._proto = protocol
self._lock = threading.Lock()
self._cancel = threading.Event()
self._menu = Menu.UNKNOWN
self._connected = False
@ -158,13 +159,20 @@ class SerialBridge:
self._menu = self._detect_menu()
def disconnect(self) -> None:
"""Close the serial connection."""
"""Close the serial connection.
Signals cancellation first to unblock any long-running serial
reads (e.g. firmware sweep), then acquires the lock to close
the port cleanly.
"""
self._cancel.set()
with self._lock:
with contextlib.suppress(Exception):
self._go_to_root()
self._proto.disconnect()
self._connected = False
self._menu = Menu.UNKNOWN
self._cancel.clear() # reset for potential reconnect
@property
def is_connected(self) -> bool:
@ -424,9 +432,11 @@ class SerialBridge:
# Move to start position and wait for prompt.
self._send(f"a 0 {start_az}")
# Execute firmware sweep with extended timeout.
# Pass cancel event so disconnect() can interrupt the read.
response = self._proto.send_with_timeout(
f"azscanwxp 0 {span} {step_cdeg} {num_xponders}",
timeout=timeout,
cancel=self._cancel,
)
# Parse streaming output lines.