Phase 5: shared worker base, self-rescheduling polls, driver robustness

gui/qt_workers.py — one QueueWorker base replaces the per-device command
queue + dispatch + signal boilerplate. The loop blocks on the queue
instead of waking 10-20x/second forever (test_idle_worker_does_not_spin
asserts an idle worker burns ~no CPU). PollingQueueWorker adds
self-rescheduling polling: the next poll is queued only after the
previous finishes, so a device slower than the interval can't accumulate
a backlog (test_polling_never_overlaps_or_backs_up).

Helios responsiveness — the concrete bug that motivated the above: a free
running 1 s QTimer queued a status poll that took ~2 s, so the queue grew
for as long as the panel stayed connected.
- helios_laser._query reads until the CR terminator instead of sleeping a
  fixed 0.05 + 0.2 s per query
- one _query_int() helper replaces five copies of parse-with-logging
- polling is now driven by the worker; HeliosWindow's QTimer is gone
- dropped __del__, which disabled the laser and wrote to the serial port
  from the garbage collector at an unpredictable time

helios_test_app.py — the worker was moveToThread'd but every call site
invoked its methods directly, so all serial I/O (including the sleeps)
ran on the GUI thread; Query All froze the UI for ~2 s. Calls now go
through a queued signal to a pyqtSlot. Also: connect/disconnect cycles
leaked a QThread + worker + 9 connections each time; 16 copies of the
not-connected guard collapse to _require_connection(); the Query Power
button called a method that has never existed (AttributeError popup) and
is now disabled and documented in KNOWN_ISSUES.

DCBiasImageWidget preallocates its image and uses set_data/set_clim, so
the live preview stops rebuilding the array and the whole artist tree per
row (O(rows^2) over a scan).

bbd20x: connect() now raises when no bays respond instead of reporting
success on the wrong port; disconnect() joins with a timeout so a wedged
reader can't hang shutdown; one _channel_for() helper replaces four
copy-pasted axis mappings; hardcoded travel limits become TRAVEL_MM; the
joke error strings are gone.

gui/widgets.py adds the shared ConnectionBar / PortSelector / bounded
LogConsole / StatusGrid for the test benches to adopt. 65 tests passing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Thomas Ales
2026-07-28 11:21:29 -05:00
parent afe33249d1
commit 44febe34b8
8 changed files with 833 additions and 444 deletions
+118
View File
@@ -0,0 +1,118 @@
"""Shared Qt worker base for hardware that must be driven off the GUI thread.
Every device worker in this project was the same shape: a command queue, a
`while running: get(timeout=…)` loop, an if/elif dispatch, and a standard
connected/disconnected/failed signal trio. The timeout-poll versions woke
10–20 times a second forever, even with nothing to do; this base blocks on
the queue instead and wakes only when there is work.
"""
from __future__ import annotations
import queue
from PyQt6.QtCore import QObject, pyqtSignal, pyqtSlot
_STOP = object()
class QueueWorker(QObject):
"""Base for a device worker living on its own QThread.
Subclasses register handlers in ``self._handlers`` (command name →
callable) and call ``self._enqueue(name, **kwargs)`` from the GUI thread.
Override ``_on_stop`` to release hardware when the loop exits.
"""
connected = pyqtSignal()
disconnected = pyqtSignal()
connection_failed = pyqtSignal(str)
error_occurred = pyqtSignal(str)
def __init__(self):
super().__init__()
self._cmd_q: queue.Queue = queue.Queue()
self._handlers: dict[str, callable] = {}
self._running = False
self.is_connected = False
# ── Command submission (GUI thread) ───────────────────────────────────────
def _enqueue(self, cmd_type: str, **kwargs):
self._cmd_q.put((cmd_type, kwargs))
def stop_worker(self):
self._cmd_q.put(_STOP)
# ── Worker loop ───────────────────────────────────────────────────────────
@pyqtSlot()
def run(self):
self._running = True
while self._running:
item = self._cmd_q.get() # blocks — no idle wake-ups
if item is _STOP:
break
cmd_type, kwargs = item
handler = self._handlers.get(cmd_type)
if handler is None:
self.error_occurred.emit(f"Unknown command: {cmd_type}")
continue
try:
handler(**kwargs)
except Exception as exc:
self.error_occurred.emit(str(exc))
self._running = False
self._on_stop()
def _on_stop(self):
"""Release hardware when the loop exits. Override as needed."""
class PollingQueueWorker(QueueWorker):
"""QueueWorker that also polls the device on an interval.
The poll is self-rescheduling: the next one is queued only after the
previous finishes, so a device slower than the interval can never
accumulate a backlog of stale poll commands (which is exactly what the
old free-running QTimer did to the Helios laser).
"""
POLL_CMD = "_poll"
def __init__(self, poll_interval_s: float = 1.0):
super().__init__()
self._poll_interval_s = poll_interval_s
self._polling = False
self._handlers[self.POLL_CMD] = self._poll_and_reschedule
def start_polling(self):
if not self._polling:
self._polling = True
self._enqueue(self.POLL_CMD)
def stop_polling(self):
self._polling = False
def _poll_and_reschedule(self):
if not self._polling or not self.is_connected:
self._polling = False
return
try:
self._poll_once()
finally:
if self._polling and self.is_connected:
self._schedule_next_poll()
def _schedule_next_poll(self):
# A timer thread rather than a sleep here, so the worker stays
# responsive to commands during the interval.
import threading
t = threading.Timer(self._poll_interval_s,
lambda: self._enqueue(self.POLL_CMD))
t.daemon = True
t.start()
self._poll_timer = t
def _poll_once(self):
"""Read device state and emit updates. Implemented by subclasses."""
+187
View File
@@ -0,0 +1,187 @@
"""Widgets shared by the main app and the per-device test benches.
Each of these was hand-rolled several times across the apps, with slightly
different behaviour every time (only one log console bounded its buffer,
only one port picker sorted by device type).
"""
from __future__ import annotations
from PyQt6.QtCore import Qt, pyqtSignal
from PyQt6.QtGui import QFont
from PyQt6.QtWidgets import (
QComboBox, QGroupBox, QHBoxLayout, QLabel, QPlainTextEdit, QPushButton,
QVBoxLayout, QWidget,
)
from hardware.serial_util import scored_ports
def set_toggle(btn, checked: bool, text: str, enabled: bool = True):
"""Update a checkable button without re-triggering its toggled signal."""
btn.blockSignals(True)
btn.setChecked(checked)
btn.setText(text)
btn.setEnabled(enabled)
btn.blockSignals(False)
class PortSelector(QWidget):
"""Serial port combo + refresh button, likeliest device first."""
def __init__(self, parent=None):
super().__init__(parent)
row = QHBoxLayout(self)
row.setContentsMargins(0, 0, 0, 0)
self.combo = QComboBox()
self.combo.setMinimumWidth(220)
refresh = QPushButton("⟳")
refresh.setFixedWidth(30)
refresh.setToolTip("Rescan serial ports")
refresh.clicked.connect(self.refresh)
row.addWidget(self.combo, stretch=1)
row.addWidget(refresh)
self.refresh()
def refresh(self):
"""Repopulate the list, preserving the current selection if present."""
current = self.current_port()
self.combo.clear()
for device, label in scored_ports():
self.combo.addItem(label, device)
if self.combo.count() == 0:
self.combo.addItem("(no serial ports found)", None)
elif current:
idx = self.combo.findData(current)
if idx >= 0:
self.combo.setCurrentIndex(idx)
def current_port(self) -> str | None:
return self.combo.currentData()
def set_port(self, device: str):
idx = self.combo.findData(device)
if idx >= 0:
self.combo.setCurrentIndex(idx)
class ConnectionBar(QGroupBox):
"""Port picker + connect toggle + status label.
Emits connect_requested(port) / disconnect_requested(); the owner drives
the state back through on_connected/on_disconnected/on_failed so the
button can never disagree with the hardware.
"""
connect_requested = pyqtSignal(str)
disconnect_requested = pyqtSignal()
def __init__(self, title: str = "Connection", parent=None):
super().__init__(title, parent)
layout = QVBoxLayout(self)
self.port_selector = PortSelector()
layout.addWidget(self.port_selector)
row = QHBoxLayout()
self.toggle = QPushButton("Connect")
self.toggle.setCheckable(True)
self.toggle.toggled.connect(self._on_toggled)
self.status = QLabel("Disconnected")
self.status.setStyleSheet("font-weight: bold;")
row.addWidget(self.toggle)
row.addWidget(self.status, stretch=1)
layout.addLayout(row)
def _on_toggled(self, checked: bool):
if checked:
port = self.port_selector.current_port()
if not port:
set_toggle(self.toggle, False, "Connect")
self.status.setText("No port selected")
return
self.toggle.setText("Connecting…")
self.toggle.setEnabled(False)
self.connect_requested.emit(port)
else:
self.disconnect_requested.emit()
def on_connected(self, detail: str = "Connected"):
set_toggle(self.toggle, True, "Disconnect")
self.status.setText(detail)
self.status.setStyleSheet("font-weight: bold; color: green;")
def on_disconnected(self, detail: str = "Disconnected"):
set_toggle(self.toggle, False, "Connect")
self.status.setText(detail)
self.status.setStyleSheet("font-weight: bold;")
def on_failed(self, message: str):
set_toggle(self.toggle, False, "Connect")
self.status.setText(f"Failed: {message}")
self.status.setStyleSheet("font-weight: bold; color: red;")
class LogConsole(QWidget):
"""Bounded, monospace, auto-scrolling log view with a Clear button.
The block cap is the point: unbounded QTextEdit logs grew for the whole
session in every app that hand-rolled one.
"""
KINDS = {"tx": "→", "rx": "←", "info": "●", "err": "!"}
def __init__(self, max_blocks: int = 2000, parent=None):
super().__init__(parent)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self.view = QPlainTextEdit()
self.view.setReadOnly(True)
self.view.setMaximumBlockCount(max_blocks)
font = QFont("Menlo")
font.setStyleHint(QFont.StyleHint.Monospace)
font.setPointSize(11)
self.view.setFont(font)
layout.addWidget(self.view)
row = QHBoxLayout()
row.addStretch(1)
clear = QPushButton("Clear")
clear.clicked.connect(self.view.clear)
row.addWidget(clear)
layout.addLayout(row)
def log(self, message: str, kind: str = "info"):
self.view.appendPlainText(f"{self.KINDS.get(kind, '●')} {message}")
self.view.verticalScrollBar().setValue(
self.view.verticalScrollBar().maximum())
class StatusGrid(QWidget):
"""Label/value rows with consistent ok/warn/error colouring."""
_COLORS = {"ok": "green", "warn": "#b8860b", "error": "red", "": ""}
def __init__(self, fields: list[str], parent=None):
super().__init__(parent)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self._values: dict[str, QLabel] = {}
for name in fields:
row = QHBoxLayout()
label = QLabel(f"{name}:")
value = QLabel("—")
value.setAlignment(Qt.AlignmentFlag.AlignRight
| Qt.AlignmentFlag.AlignVCenter)
row.addWidget(label)
row.addWidget(value, stretch=1)
layout.addLayout(row)
self._values[name] = value
def set(self, name: str, text: str, state: str = ""):
label = self._values.get(name)
if label is None:
return
label.setText(text)
color = self._COLORS.get(state, "")
label.setStyleSheet(f"color: {color};" if color else "")