From fc6f90404c9428362f1a0c62bb28eb350c0f248d Mon Sep 17 00:00:00 2001 From: Christian Kolset Date: Mon, 27 Jul 2026 16:56:50 -0600 Subject: Enhance SerialDevice: support write-only channels and improve raw data handling --- devices/serial_device.py | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) (limited to 'devices/serial_device.py') diff --git a/devices/serial_device.py b/devices/serial_device.py index 458aec8..8b8de04 100644 --- a/devices/serial_device.py +++ b/devices/serial_device.py @@ -142,7 +142,10 @@ class SerialDevice(BaseDevice): raw = self._layer.read() if not raw: return {} - # Protocol layers already use channel_id keys — pass through. + if self._fmt not in _GENERIC_FORMATS: + # Protocol layers already key by channel_id — pass through untouched. + # (Write-only channels, e.g. CML "M1_VS", never appear in raw — correctly dropped.) + return raw # Generic (ArduinoLayer) may use arbitrary names — remap by position. mapped: Dict[str, float] = {} raw_vals = list(raw.values()) @@ -276,16 +279,20 @@ class SerialDevice(BaseDevice): elif fmt == "mark10": from api_layers.protocols.mark10 import UNITS as _MARK10_UNITS return [ - ChannelConfig("force", "Force", "N", -5000.0, 5000.0, color=_COLORS[0]), - ChannelConfig("unit_code", "Unit Code", "", 0.0, float(len(_MARK10_UNITS) - 1), color=_COLORS[1]), + ChannelConfig("force", "Force", "N", -5000.0, 5000.0, color=_COLORS[0]), + ChannelConfig("unit_code", "Unit Code", "", 0.0, float(len(_MARK10_UNITS) - 1), color=_COLORS[1]), + # Write-only action channels (no reading — for control buttons) + ChannelConfig("zero", "Zero Gauge", "", 0.0, 1.0, color=_COLORS[2]), + ChannelConfig("cycle_units", "Cycle Units", "", 0.0, 1.0, color=_COLORS[3]), ] elif fmt == "cml": _CMD_UNITS = {"TP": "counts", "TV": "counts/s", "TC": "%×10", "TS": "flags"} + _WRITE_UNITS = {"VS": "counts/s", "MA": "counts"} channels = [] color_idx = 0 for motor in self._motors: + mid = motor.get("motor_id", "M1") for cmd in motor.get("read_cmds", ["TP", "TV", "TC"]): - mid = motor.get("motor_id", "M1") channels.append(ChannelConfig( channel_id=f"{mid}_{cmd}", name=f"{mid} {cmd}", @@ -294,6 +301,16 @@ class SerialDevice(BaseDevice): color=_COLORS[color_idx % len(_COLORS)], )) color_idx += 1 + # Write-only setpoint channels (no reading — for control widgets) + for cmd in ("VS", "MA"): + channels.append(ChannelConfig( + channel_id=f"{mid}_{cmd}", + name=f"{mid} {cmd}", + unit=_WRITE_UNITS.get(cmd, ""), + min_value=-1e6, max_value=1e6, + color=_COLORS[color_idx % len(_COLORS)], + )) + color_idx += 1 return channels or [ChannelConfig("M1_TP", "M1 TP", "counts", color=_COLORS[0])] return [] -- cgit v1.2.3 From c3f07a7ffa320aecb3fca5dd40e7644424bddfb5 Mon Sep 17 00:00:00 2001 From: Christian Kolset Date: Mon, 27 Jul 2026 17:13:41 -0600 Subject: Fix .gitignore: remove duplicate entry for plugins/enabled.json --- .gitignore | 1 + devices/serial_device.py | 2 ++ ui/control_panel.py | 17 +++++++++++------ 3 files changed, 14 insertions(+), 6 deletions(-) (limited to 'devices/serial_device.py') diff --git a/.gitignore b/.gitignore index c2d1427..bcef6d0 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ __pychache__/ .claude/settings.local.json plugins/enabled.json plugins/enabled.json +plugins/enabled.json diff --git a/devices/serial_device.py b/devices/serial_device.py index 8b8de04..ca551c6 100644 --- a/devices/serial_device.py +++ b/devices/serial_device.py @@ -157,6 +157,8 @@ class SerialDevice(BaseDevice): return mapped def write_channel(self, channel_id: str, value: Any) -> bool: + if self.status not in (DeviceStatus.CONNECTED, DeviceStatus.SIMULATED): + return False return self._layer.write(channel_id, int(value)) def get_config_widget(self) -> QWidget: diff --git a/ui/control_panel.py b/ui/control_panel.py index 6e78e89..2b936c4 100644 --- a/ui/control_panel.py +++ b/ui/control_panel.py @@ -33,6 +33,7 @@ from PyQt6.QtCore import Qt, pyqtSignal, QTimer from PyQt6.QtGui import QFont from devices.device_registry import DeviceRegistry +from devices.base_device import DeviceStatus # ══════════════════════════════════════════════════════════════════════════════ @@ -119,13 +120,17 @@ class ControlWidget(QFrame): if self.registry and self.device_id and self.channel_id: dev = self.registry.get_instance(self.device_id) if dev: - ok = dev.write_channel(self.channel_id, value) - if ok: - written = True + if dev.status not in (DeviceStatus.CONNECTED, DeviceStatus.SIMULATED): + print(f"[Control] write_channel({self.channel_id}, {value}) skipped on " + f"{self.device_id} — device status is {dev.status.value}, not connected") else: - print(f"[Control] write_channel({self.channel_id}, {value}) " - f"returned False on {self.device_id} — " - f"check device type and channel ID") + ok = dev.write_channel(self.channel_id, value) + if ok: + written = True + else: + print(f"[Control] write_channel({self.channel_id}, {value}) " + f"returned False on {self.device_id} — " + f"check device type and channel ID") self.value_changed.emit(self.channel_id, value) if self._on_action_fn is not None: -- cgit v1.2.3 From ee4965f4d4d1fc5d40be24b99341620e32386d40 Mon Sep 17 00:00:00 2001 From: Christian Kolset Date: Mon, 27 Jul 2026 17:34:30 -0600 Subject: Enhance protocol layers: implement I/O locking for thread safety in serial communication --- .gitignore | 1 + api_layers/protocols/base_protocol.py | 1 + api_layers/protocols/cml.py | 12 ++++++++---- api_layers/protocols/mark10.py | 14 +++++++++----- api_layers/protocols/modbus_rtu.py | 16 +++++++++------- api_layers/protocols/scpi.py | 13 ++++++++----- devices/serial_device.py | 10 ++++++++++ 7 files changed, 46 insertions(+), 21 deletions(-) (limited to 'devices/serial_device.py') diff --git a/.gitignore b/.gitignore index bcef6d0..7a03d40 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ __pychache__/ plugins/enabled.json plugins/enabled.json plugins/enabled.json +plugins/enabled.json diff --git a/api_layers/protocols/base_protocol.py b/api_layers/protocols/base_protocol.py index 096151d..bb45d6b 100644 --- a/api_layers/protocols/base_protocol.py +++ b/api_layers/protocols/base_protocol.py @@ -30,6 +30,7 @@ class BaseProtocol(ABC): self._cache: Dict[str, float] = {} self._lock = threading.Lock() + self._io_lock = threading.Lock() # guards self._ser — shared by poll thread and write() callers self._running = False self._thread: Optional[threading.Thread] = None self._ser = None diff --git a/api_layers/protocols/cml.py b/api_layers/protocols/cml.py index 67be0d5..6bc85f0 100644 --- a/api_layers/protocols/cml.py +++ b/api_layers/protocols/cml.py @@ -73,9 +73,10 @@ class CMLLayer(BaseProtocol): frame = f"{cmd}\r".encode() else: frame = f"#{motor.address}{cmd}\r".encode() - self._ser.write(frame) - self._ser.flush() - resp = self._ser.readline().decode(errors="replace").strip() + with self._io_lock: + self._ser.write(frame) + self._ser.flush() + resp = self._ser.readline().decode(errors="replace").strip() return _parse_cml_response(resp) def _poll(self) -> Dict[str, float]: @@ -127,7 +128,10 @@ class CMLLayer(BaseProtocol): frame = f"{cmd}{data}\r".encode() else: frame = f"#{motor.address}{cmd}{data}\r".encode() - self._ser.write(frame) + with self._io_lock: + self._ser.write(frame) + self._ser.flush() + self._ser.readline() # discard echo-back so it doesn't desync the next poll read return True except Exception: return False diff --git a/api_layers/protocols/mark10.py b/api_layers/protocols/mark10.py index 4a97892..b7dacb4 100644 --- a/api_layers/protocols/mark10.py +++ b/api_layers/protocols/mark10.py @@ -43,8 +43,9 @@ class Mark10Layer(BaseProtocol): def _poll(self) -> Dict[str, float]: try: - self._ser.write(b"?\r") - resp = self._ser.readline().decode(errors="replace").strip() + with self._io_lock: + self._ser.write(b"?\r") + resp = self._ser.readline().decode(errors="replace").strip() return self._parse(resp) except Exception: return {} @@ -83,7 +84,8 @@ class Mark10Layer(BaseProtocol): if not self._ser: return False try: - self._ser.write(cmd) + with self._io_lock: + self._ser.write(cmd) return True except Exception: return False @@ -92,8 +94,10 @@ class Mark10Layer(BaseProtocol): def zero(self) -> None: if self._ser: - self._ser.write(b"Z\r") + with self._io_lock: + self._ser.write(b"Z\r") def cycle_units(self) -> None: if self._ser: - self._ser.write(b"U\r") + with self._io_lock: + self._ser.write(b"U\r") diff --git a/api_layers/protocols/modbus_rtu.py b/api_layers/protocols/modbus_rtu.py index 68d644e..33f6877 100644 --- a/api_layers/protocols/modbus_rtu.py +++ b/api_layers/protocols/modbus_rtu.py @@ -91,10 +91,11 @@ class ModbusRTULayer(BaseProtocol): def _read_registers(self, fc: int, start: int, count: int) -> List[int]: req = _frame(struct.pack(">BBHH", self.slave_addr, fc, start, count)) - self._ser.write(req) - time.sleep(0.005) - n_bytes = 5 + 2 * count - resp = self._ser.read(n_bytes) + with self._io_lock: + self._ser.write(req) + time.sleep(0.005) + n_bytes = 5 + 2 * count + resp = self._ser.read(n_bytes) if len(resp) < n_bytes: raise IOError(f"Short response {len(resp)}/{n_bytes} bytes") crc_recv = struct.unpack(" bool: req = _frame(struct.pack(">BBHH", self.slave_addr, 0x06, register, value & 0xFFFF)) - self._ser.write(req) - time.sleep(0.005) - resp = self._ser.read(8) + with self._io_lock: + self._ser.write(req) + time.sleep(0.005) + resp = self._ser.read(8) return len(resp) == 8 def write(self, channel_id: str, value) -> bool: diff --git a/api_layers/protocols/scpi.py b/api_layers/protocols/scpi.py index 526ed21..fca5ba4 100644 --- a/api_layers/protocols/scpi.py +++ b/api_layers/protocols/scpi.py @@ -54,8 +54,9 @@ class SCPILayer(BaseProtocol): if not ch.query.strip(): continue try: - self._ser.write(f"{ch.query.strip()}\n".encode()) - resp = self._ser.readline().decode(errors="replace").strip() + with self._io_lock: + self._ser.write(f"{ch.query.strip()}\n".encode()) + resp = self._ser.readline().decode(errors="replace").strip() val = _parse_numeric(resp) if val is not None: result[ch.channel_id] = val * ch.scale @@ -77,7 +78,8 @@ class SCPILayer(BaseProtocol): return True try: cmd = ch.write_cmd.format(value=value) - self._ser.write(f"{cmd}\n".encode()) + with self._io_lock: + self._ser.write(f"{cmd}\n".encode()) return True except Exception: return False @@ -87,8 +89,9 @@ class SCPILayer(BaseProtocol): if not self._ser: return "(not connected)" try: - self._ser.write(b"*IDN?\n") - return self._ser.readline().decode(errors="replace").strip() + with self._io_lock: + self._ser.write(b"*IDN?\n") + return self._ser.readline().decode(errors="replace").strip() except Exception as e: return f"(error: {e})" diff --git a/devices/serial_device.py b/devices/serial_device.py index ca551c6..dc92b12 100644 --- a/devices/serial_device.py +++ b/devices/serial_device.py @@ -313,6 +313,16 @@ class SerialDevice(BaseDevice): color=_COLORS[color_idx % len(_COLORS)], )) color_idx += 1 + # Write-only action channels — motor must be enabled (ME) before VS/MA take effect + for cmd, label in (("ME", "Enable"), ("MD", "Disable")): + channels.append(ChannelConfig( + channel_id=f"{mid}_{cmd}", + name=f"{mid} {label}", + unit="", + min_value=0.0, max_value=1.0, + color=_COLORS[color_idx % len(_COLORS)], + )) + color_idx += 1 return channels or [ChannelConfig("M1_TP", "M1 TP", "counts", color=_COLORS[0])] return [] -- cgit v1.2.3 From b2dc94bb2e7c7e57cba202697ed4d58bbb1f01f5 Mon Sep 17 00:00:00 2001 From: Christian Kolset Date: Tue, 28 Jul 2026 17:01:38 -0600 Subject: Update CML protocol documentation and improve command handling; adjust motion_capture setting to false --- api_layers/protocols/cml.py | 118 ++++++++++++++++++++++++++--------------- api_layers/protocols/mark10.py | 9 +++- devices/serial_device.py | 10 ++-- plugins/enabled.json | 2 +- 4 files changed, 88 insertions(+), 51 deletions(-) (limited to 'devices/serial_device.py') diff --git a/api_layers/protocols/cml.py b/api_layers/protocols/cml.py index 6bc85f0..113afe7 100644 --- a/api_layers/protocols/cml.py +++ b/api_layers/protocols/cml.py @@ -1,36 +1,38 @@ """ api_layers/protocols/cml.py -CoolMuscle Language (CML) protocol layer. +CoolMuscle CM1-C ASCII (CML) protocol layer. -For CoolMuscle CM-series servo motors over RS-232 (single axis) -or RS-485 (multi-drop, up to 31 axes). +Wire format — see docs/CM1-C_ASCII_Command_Cheatsheet.md: + .[=]\\r + e.g. "S0.1=20\\r" (set speed register), "?97.1\\r" (query speed), + "^.1\\r" (execute), "(.1\\r" (enable), ").1\\r" (disable), "].1\\r" (stop) -Frame format -───────────── - RS-232 (address=0): - Command: []\\r - Response: []\\r (echo-back) +Motor ID is always appended explicitly as "." on every command — there is +no address-less / prefix-free mode. - RS-485 (address 1-31): - Command: #[]\\r - Response: *[]\\r +Terminator is CR only (default K70 setting). Replies are read up to that CR +with Serial.read_until(b"\\r") rather than readline(), since pyserial's +readline() looks for LF by default and would otherwise block for the full +serial timeout on every single query. Read commands (query current state): - TP — Tell absolute position (encoder counts, signed) - TV — Tell velocity (counts/second, signed) - TC — Tell current (% rated × 10, unsigned) - TS — Tell status word (hex flags) + TP — current position (?96, pulses, signed) + TV — current speed (?97, unit set by K37, signed) + TC — averaged current (?98, % rated, unsigned) + TS — motor status (?99, bit field — see cheatsheet) Write commands (control): - ME — Motor Enable - MD — Motor Disable - MA — Move Absolute (encoder counts) - MR — Move Relative (encoder counts) - VS — Velocity Setpoint + ME — Motor Enable ("(") + MD — Motor Disable (")") + ST — Immediate stop ("]") + VS — Velocity setpoint: sets a large P0 target (direction via sign + of S0) then executes with "^" — continuous rotation until + stopped (S0=0 or ST/MD). + MA — Move absolute: sets P0 to then executes with "^". Channel IDs follow pattern: _ - e.g. "M1_TP", "M1_TV", "M2_TC" + e.g. "M1_TP", "M1_VS", "M2_TC" """ import math @@ -41,15 +43,19 @@ from typing import Dict, List, Optional from api_layers.protocols.base_protocol import BaseProtocol -_READ_CMDS = ["TP", "TV", "TC", "TS"] -_RESP_RE = re.compile(r"[*@]?\d*([A-Z]{2})([\s\S]*)") -_NUM_RE = re.compile(r"[+-]?\d+") +_QUERY_CMDS = {"TP": "?96", "TV": "?97", "TC": "?98", "TS": "?99"} +_NUM_RE = re.compile(r"[+-]?\d+\.?\d*") + +# Position target for velocity-mode continuous rotation — direction comes +# from the sign of S0, not this value, so it just needs to be far enough +# away that the move never completes on its own. +_CONTINUOUS_POSITION = 1_000_000_000 @dataclass class CMLMotor: motor_id: str - address: int = 1 # 0 = RS-232 (no address prefix) + address: int = 1 # CM1-C motor ID, always sent as ".
" read_cmds: List[str] = field(default_factory=lambda: ["TP", "TV", "TC"]) @@ -66,17 +72,27 @@ class CMLLayer(BaseProtocol): super().__init__(port, baud, poll_interval, simulate) self.motors = motors or [CMLMotor("M1", address=1)] + # ── Low-level I/O ───────────────────────────────────────────────────── + + def _send(self, address: int, cmd: str, value: Optional[int] = None) -> None: + suffix = f"={value}" if value is not None else "" + frame = f"{cmd}.{address}{suffix}\r".encode() + self._ser.reset_input_buffer() + self._ser.write(frame) + self._ser.flush() + + def _read_reply(self) -> str: + return self._ser.read_until(b"\r").decode(errors="replace").strip() + # ── Protocol ────────────────────────────────────────────────────────── def _send_query(self, motor: CMLMotor, cmd: str) -> Optional[float]: - if motor.address == 0: - frame = f"{cmd}\r".encode() - else: - frame = f"#{motor.address}{cmd}\r".encode() + query = _QUERY_CMDS.get(cmd) + if query is None: + return None with self._io_lock: - self._ser.write(frame) - self._ser.flush() - resp = self._ser.readline().decode(errors="replace").strip() + self._send(motor.address, query) + resp = self._read_reply() return _parse_cml_response(resp) def _poll(self) -> Dict[str, float]: @@ -111,8 +127,7 @@ class CMLLayer(BaseProtocol): return result def write(self, channel_id: str, value) -> bool: - # channel_id: "_[]" - # e.g. "M1_ME", "M1_MA" (value carries position) + # channel_id: "_" e.g. "M1_ME", "M1_VS" (value carries speed) parts = channel_id.split("_", 1) if len(parts) != 2: return False @@ -123,23 +138,38 @@ class CMLLayer(BaseProtocol): if self.simulate: return True try: - data = "" if cmd in ("ME", "MD") else str(int(value)) - if motor.address == 0: - frame = f"{cmd}{data}\r".encode() - else: - frame = f"#{motor.address}{cmd}{data}\r".encode() with self._io_lock: - self._ser.write(frame) - self._ser.flush() - self._ser.readline() # discard echo-back so it doesn't desync the next poll read + if cmd == "ME": + self._send(motor.address, "(") + self._read_reply() + elif cmd == "MD": + self._send(motor.address, ")") + self._read_reply() + elif cmd == "ST": + self._send(motor.address, "]") + self._read_reply() + elif cmd == "VS": + self._send(motor.address, "P0", _CONTINUOUS_POSITION) + self._read_reply() + self._send(motor.address, "S0", int(value)) + self._read_reply() + self._send(motor.address, "^") + self._read_reply() + elif cmd == "MA": + self._send(motor.address, "P0", int(value)) + self._read_reply() + self._send(motor.address, "^") + self._read_reply() + else: + return False return True except Exception: return False def _parse_cml_response(resp: str) -> Optional[float]: - """Extract numeric value from CML response like '*1TP+001234'.""" - m = _NUM_RE.search(resp[3:] if resp and resp[0] in "*@#" else resp) + """Extract the first numeric value from a CM1-C reply.""" + m = _NUM_RE.search(resp) if m: return float(m.group()) return None diff --git a/api_layers/protocols/mark10.py b/api_layers/protocols/mark10.py index b7dacb4..a209232 100644 --- a/api_layers/protocols/mark10.py +++ b/api_layers/protocols/mark10.py @@ -10,6 +10,11 @@ Commands (sent with CR terminator): Response format: "+0.1234 kgF" (sign, value, space, unit suffix) +Replies are read up to CR with Serial.read_until(b"\\r") rather than +readline(), since pyserial's readline() looks for LF by default and the +gauge only terminates with CR — readline() would otherwise block for the +full serial timeout on every poll. + Channels exposed: force — current force reading (in instrument's selected unit) unit_code — numeric index into UNITS list (lb=0, kgF=1, N=2, ozF=3) @@ -44,8 +49,10 @@ class Mark10Layer(BaseProtocol): def _poll(self) -> Dict[str, float]: try: with self._io_lock: + self._ser.reset_input_buffer() self._ser.write(b"?\r") - resp = self._ser.readline().decode(errors="replace").strip() + self._ser.flush() + resp = self._ser.read_until(b"\r").decode(errors="replace").strip() return self._parse(resp) except Exception: return {} diff --git a/devices/serial_device.py b/devices/serial_device.py index dc92b12..067656a 100644 --- a/devices/serial_device.py +++ b/devices/serial_device.py @@ -314,7 +314,7 @@ class SerialDevice(BaseDevice): )) color_idx += 1 # Write-only action channels — motor must be enabled (ME) before VS/MA take effect - for cmd, label in (("ME", "Enable"), ("MD", "Disable")): + for cmd, label in (("ME", "Enable"), ("MD", "Disable"), ("ST", "Stop")): channels.append(ChannelConfig( channel_id=f"{mid}_{cmd}", name=f"{mid} {label}", @@ -822,7 +822,7 @@ class _CMLPanel(QWidget): lay.setContentsMargins(0, 4, 0, 4) lay.setSpacing(6) - grp = QGroupBox("Motors (RS-232: addr=0 / RS-485: addr 1-31)") + grp = QGroupBox("Motors (motor ID 1-31, always sent explicitly)") grp_lay = QVBoxLayout(grp) scroll = QScrollArea() @@ -885,9 +885,9 @@ class _MotorRow(QWidget): lay.addWidget(self._id_edit) self._addr_spin = QSpinBox() - self._addr_spin.setRange(0, 31) - self._addr_spin.setValue(m.get("address", 1)) - self._addr_spin.setToolTip("0 = RS-232 (no prefix), 1-31 = RS-485") + self._addr_spin.setRange(1, 31) + self._addr_spin.setValue(max(1, m.get("address", 1))) + self._addr_spin.setToolTip("CM1-C motor ID — always sent explicitly as \".\"") lay.addWidget(QLabel("Addr:")) lay.addWidget(self._addr_spin) diff --git a/plugins/enabled.json b/plugins/enabled.json index a33a40a..7d3abd6 100644 --- a/plugins/enabled.json +++ b/plugins/enabled.json @@ -1,3 +1,3 @@ { - "motion_capture": true + "motion_capture": false } \ No newline at end of file -- cgit v1.2.3 From 9360dea6e6327004b905eb6d7c782cc7c0d3ba13 Mon Sep 17 00:00:00 2001 From: Christian Kolset Date: Wed, 29 Jul 2026 12:59:10 -0600 Subject: Hide non-writable channels from Controls picker, gate writes on enabled+writable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds ChannelConfig.writable so the Controls editor can only bind to channels with a real write mapping (VS/MA/ME/MD/ST for CML, do*/DO for digital I/O, write_cmd-configured SCPI channels, holding-register Modbus channels) instead of read-only telemetry — this is exactly the class of mistake hit earlier (binding a motor-speed control to M1_TV instead of M1_VS). Also carries forward the enabled-channel gating for controls (hide disabled channels from the picker, block writes to them at _write() time) done alongside this investigation. Co-Authored-By: Claude Sonnet 5 --- devices/arduino_device.py | 1 + devices/base_device.py | 1 + devices/digital_io.py | 1 + devices/nidaqmx_device.py | 1 + devices/serial_device.py | 9 +++++++-- ui/control_editor.py | 6 +++++- ui/control_panel.py | 6 +++++- 7 files changed, 21 insertions(+), 4 deletions(-) (limited to 'devices/serial_device.py') diff --git a/devices/arduino_device.py b/devices/arduino_device.py index 7c1d21b..f2407e6 100644 --- a/devices/arduino_device.py +++ b/devices/arduino_device.py @@ -108,6 +108,7 @@ class ArduinoDevice(BaseDevice): channels.append(ChannelConfig( channel_id=f"do{i}", name=f"DO {i}", unit="", min_value=0.0, max_value=1.0, + writable=True, color=_DO_COLORS[i % len(_DO_COLORS)], )) diff --git a/devices/base_device.py b/devices/base_device.py index 32fe787..83b8536 100644 --- a/devices/base_device.py +++ b/devices/base_device.py @@ -29,6 +29,7 @@ class ChannelConfig: max_value: float = 100.0 enabled: bool = True color: str = "#00d4ff" + writable: bool = False # True if this channel accepts write_channel() calls extra: Dict[str, Any] = field(default_factory=dict) diff --git a/devices/digital_io.py b/devices/digital_io.py index 53395dc..111224d 100644 --- a/devices/digital_io.py +++ b/devices/digital_io.py @@ -60,6 +60,7 @@ class DigitalIODevice(BaseDevice): channel_id=f"do{i}", name=f"DO {i}", unit="", min_value=0.0, max_value=1.0, color=_OUT_COLORS[i % len(_OUT_COLORS)], + writable=True, )) info = DeviceInfo( diff --git a/devices/nidaqmx_device.py b/devices/nidaqmx_device.py index 88bb932..38cf93d 100644 --- a/devices/nidaqmx_device.py +++ b/devices/nidaqmx_device.py @@ -69,6 +69,7 @@ class NidaqmxDevice(BaseDevice): channel_id=f"do{i}", name=f"DO {i}", unit="", min_value=0.0, max_value=1.0, color=_DO_COLORS[i % len(_DO_COLORS)], + writable=True, )) info = DeviceInfo( diff --git a/devices/serial_device.py b/devices/serial_device.py index 067656a..8062624 100644 --- a/devices/serial_device.py +++ b/devices/serial_device.py @@ -264,6 +264,7 @@ class SerialDevice(BaseDevice): unit=sc.get("unit", ""), min_value=-1e9, max_value=1e9, color=_COLORS[i % len(_COLORS)], + writable=bool(sc.get("write_cmd")), ) for i, sc in enumerate(self._scpi_channels) ] @@ -275,6 +276,8 @@ class SerialDevice(BaseDevice): unit=mc.get("unit", ""), min_value=-1e9, max_value=1e9, color=_COLORS[i % len(_COLORS)], + # Holding registers (FC03) accept writes (FC06); input registers (FC04) don't. + writable=(mc.get("function_code", 0x03) == 0x03), ) for i, mc in enumerate(self._mb_channels) ] @@ -284,8 +287,8 @@ class SerialDevice(BaseDevice): ChannelConfig("force", "Force", "N", -5000.0, 5000.0, color=_COLORS[0]), ChannelConfig("unit_code", "Unit Code", "", 0.0, float(len(_MARK10_UNITS) - 1), color=_COLORS[1]), # Write-only action channels (no reading — for control buttons) - ChannelConfig("zero", "Zero Gauge", "", 0.0, 1.0, color=_COLORS[2]), - ChannelConfig("cycle_units", "Cycle Units", "", 0.0, 1.0, color=_COLORS[3]), + ChannelConfig("zero", "Zero Gauge", "", 0.0, 1.0, color=_COLORS[2], writable=True), + ChannelConfig("cycle_units", "Cycle Units", "", 0.0, 1.0, color=_COLORS[3], writable=True), ] elif fmt == "cml": _CMD_UNITS = {"TP": "counts", "TV": "counts/s", "TC": "%×10", "TS": "flags"} @@ -311,6 +314,7 @@ class SerialDevice(BaseDevice): unit=_WRITE_UNITS.get(cmd, ""), min_value=-1e6, max_value=1e6, color=_COLORS[color_idx % len(_COLORS)], + writable=True, )) color_idx += 1 # Write-only action channels — motor must be enabled (ME) before VS/MA take effect @@ -321,6 +325,7 @@ class SerialDevice(BaseDevice): unit="", min_value=0.0, max_value=1.0, color=_COLORS[color_idx % len(_COLORS)], + writable=True, )) color_idx += 1 return channels or [ChannelConfig("M1_TP", "M1 TP", "counts", color=_COLORS[0])] diff --git a/ui/control_editor.py b/ui/control_editor.py index 48de21d..5140bf3 100644 --- a/ui/control_editor.py +++ b/ui/control_editor.py @@ -360,8 +360,12 @@ class ControlEditorDialog(QDialog): dev = self.registry.get_instance(dev_id) if not dev: return - # Add actual channels + # Add actual channels (skip disabled — can't be driven while switched + # off — and skip read-only channels — a control writes, so a channel + # with no write mapping should never be offered as a target) for ch in dev.info.channels: + if not ch.enabled or not ch.writable: + continue self._ch_cb.addItem(f"{ch.channel_id} ({ch.name})", userData=ch.channel_id) # For Arduino backends also suggest digital pins for output diff --git a/ui/control_panel.py b/ui/control_panel.py index 2b936c4..22229ee 100644 --- a/ui/control_panel.py +++ b/ui/control_panel.py @@ -120,7 +120,11 @@ class ControlWidget(QFrame): if self.registry and self.device_id and self.channel_id: dev = self.registry.get_instance(self.device_id) if dev: - if dev.status not in (DeviceStatus.CONNECTED, DeviceStatus.SIMULATED): + ch = dev.get_channel(self.channel_id) + if ch is not None and not ch.enabled: + print(f"[Control] write_channel({self.channel_id}, {value}) skipped on " + f"{self.device_id} — channel is disabled") + elif dev.status not in (DeviceStatus.CONNECTED, DeviceStatus.SIMULATED): print(f"[Control] write_channel({self.channel_id}, {value}) skipped on " f"{self.device_id} — device status is {dev.status.value}, not connected") else: -- cgit v1.2.3 From d9ca58e48cf92438087ac24ee261c2c4911316b1 Mon Sep 17 00:00:00 2001 From: Christian Kolset Date: Wed, 29 Jul 2026 13:03:24 -0600 Subject: Add editable device display name, persist it across profile save/load DeviceInfo.name existed but was hardcoded per device type and never operator-editable. Adds a Display Name field to Add Device and makes the Info-tab Name field in the device config dialog editable, and threads the name through get_save_config()/ProfileManager.apply() so a custom name survives a .labdaq save/reload instead of reverting to the type default. Name is applied post-construction rather than as a constructor kwarg, since no device factory declares a "name" param. Co-Authored-By: Claude Sonnet 5 --- core/profile.py | 9 ++++++++- devices/analog_input.py | 1 + devices/arduino_device.py | 1 + devices/digital_io.py | 1 + devices/nidaqmx_device.py | 1 + devices/serial_device.py | 1 + plugins/motion_capture/device.py | 1 + ui/add_device_dialog.py | 8 ++++++++ ui/config_dialog.py | 9 ++++++++- ui/windows/devices_window.py | 2 +- 10 files changed, 31 insertions(+), 3 deletions(-) (limited to 'devices/serial_device.py') diff --git a/core/profile.py b/core/profile.py index d3c7e3a..7ede859 100644 --- a/core/profile.py +++ b/core/profile.py @@ -302,8 +302,15 @@ class ProfileManager: print(f"[Profile] Unknown device type: {dev_type}") continue try: - kwargs = {k: v for k, v in dev_cfg.items() if k != "device_type"} + # "name" is a display label, not a constructor arg — every device + # factory builds its own default name internally, so apply it + # after construction instead of passing it through. + custom_name = dev_cfg.get("name") + kwargs = {k: v for k, v in dev_cfg.items() + if k not in ("device_type", "name")} dev = factory(**kwargs) + if custom_name: + dev.info.name = custom_name registry.add_instance(dev) dev.connect() if engine is not None: diff --git a/devices/analog_input.py b/devices/analog_input.py index c9e5d2a..1a7fefa 100644 --- a/devices/analog_input.py +++ b/devices/analog_input.py @@ -175,6 +175,7 @@ class AnalogInputDevice(BaseDevice): return { "device_type": self.DEVICE_TYPE, "device_id": self.info.device_id, + "name": self.info.name, "num_channels": self._num_channels, "simulate": self.simulate, "backend": self.backend, diff --git a/devices/arduino_device.py b/devices/arduino_device.py index 7c1d21b..e7fb537 100644 --- a/devices/arduino_device.py +++ b/devices/arduino_device.py @@ -203,6 +203,7 @@ class ArduinoDevice(BaseDevice): return { "device_type": self.DEVICE_TYPE, "device_id": self.info.device_id, + "name": self.info.name, "analog_pins": self._analog_pins, "di_pins": self._di_pins, "do_pins": self._do_pins, diff --git a/devices/digital_io.py b/devices/digital_io.py index 53395dc..954a8ac 100644 --- a/devices/digital_io.py +++ b/devices/digital_io.py @@ -258,6 +258,7 @@ class DigitalIODevice(BaseDevice): return { "device_type": self.DEVICE_TYPE, "device_id": self.info.device_id, + "name": self.info.name, "num_inputs": self._num_inputs, "num_outputs": self._num_outputs, "simulate": self.simulate, diff --git a/devices/nidaqmx_device.py b/devices/nidaqmx_device.py index 88bb932..ed19aeb 100644 --- a/devices/nidaqmx_device.py +++ b/devices/nidaqmx_device.py @@ -219,6 +219,7 @@ class NidaqmxDevice(BaseDevice): return { "device_type": self.DEVICE_TYPE, "device_id": self.info.device_id, + "name": self.info.name, "num_analog": self._num_analog, "min_v": self._min_v, "max_v": self._max_v, diff --git a/devices/serial_device.py b/devices/serial_device.py index 067656a..57faee8 100644 --- a/devices/serial_device.py +++ b/devices/serial_device.py @@ -168,6 +168,7 @@ class SerialDevice(BaseDevice): cfg: Dict[str, Any] = { "device_type": self.DEVICE_TYPE, "device_id": self.info.device_id, + "name": self.info.name, "port": self._port, "baud_rate": self._baud, "parse_format": self._fmt, diff --git a/plugins/motion_capture/device.py b/plugins/motion_capture/device.py index 58f89ce..3369962 100644 --- a/plugins/motion_capture/device.py +++ b/plugins/motion_capture/device.py @@ -102,6 +102,7 @@ class CameraDevice(BaseDevice): return { "device_type": self.DEVICE_TYPE, "device_id": self.info.device_id, + "name": self.info.name, "camera_index": self._camera_index, "simulate": self._simulate, "resolution": list(self._resolution) if self._resolution else None, diff --git a/ui/add_device_dialog.py b/ui/add_device_dialog.py index 2956a96..68ec3ad 100644 --- a/ui/add_device_dialog.py +++ b/ui/add_device_dialog.py @@ -299,6 +299,10 @@ class AddDeviceDialog(QDialog): self._id_edit.setPlaceholderText("Leave blank for auto") cfg_form.addRow("Device ID:", self._id_edit) + self._name_edit = QLineEdit() + self._name_edit.setPlaceholderText("Leave blank to use the default type name") + cfg_form.addRow("Display Name:", self._name_edit) + self._fmt_cb = QComboBox() self._fmt_cb.addItems(list(_FORMAT_LABELS.keys())) self._fmt_lbl = QLabel("Protocol / Format:") @@ -449,6 +453,10 @@ class AddDeviceDialog(QDialog): panel.set_simulate(sim) dev = panel.build_device(dev_id) + display_name = self._name_edit.text().strip() + if display_name: + dev.info.name = display_name + self.created_device = dev self.accept() except Exception as e: diff --git a/ui/config_dialog.py b/ui/config_dialog.py index d9bc9df..5a95821 100644 --- a/ui/config_dialog.py +++ b/ui/config_dialog.py @@ -59,7 +59,14 @@ class DeviceConfigDialog(QDialog): e = QLineEdit(str(v)); e.setReadOnly(True); return e form.addRow("Device ID:", _ro(info.device_id)) - form.addRow("Name:", _ro(info.name)) + + def _on_name_edited(): + info.name = name_edit.text().strip() or info.name + self.setWindowTitle(f"Configure — {info.name} [{info.device_id}]") + + name_edit = QLineEdit(info.name) + name_edit.editingFinished.connect(_on_name_edited) + form.addRow("Name:", name_edit) form.addRow("Type:", _ro(info.device_type)) form.addRow("Description:", _ro(info.description)) form.addRow("Manufacturer:", _ro(info.manufacturer)) diff --git a/ui/windows/devices_window.py b/ui/windows/devices_window.py index ac9d13c..2c484e8 100644 --- a/ui/windows/devices_window.py +++ b/ui/windows/devices_window.py @@ -349,7 +349,7 @@ class DevicesWindow(QWidget): dev = self.registry.get_instance(device_id) if dev: DeviceConfigDialog(dev, self).exec() - self._ch_tab.refresh() + self.refresh() # rebuilds device rows (picks up a renamed display name) + Signals tab self.device_reconfigured.emit(device_id) def _on_remove(self, device_id: str): -- cgit v1.2.3 From bf9c7746ba60613b66ce8d1e9a68c5480f2b93d1 Mon Sep 17 00:00:00 2001 From: Christian Kolset Date: Wed, 29 Jul 2026 13:12:17 -0600 Subject: Sync Mark-10 gauge's live unit into ChannelConfig instead of a fixed default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mark10Layer._parse() already tracked whichever unit suffix the gauge last reported (lb/kgF/N/ozF — the gauge's physical unit button cycles these independently of this app). serial_device.py hardcoded the "force" channel's unit to "N" and never updated it, so switching units on the gauge itself was invisible here. Adds Mark10Layer.current_unit and has SerialDevice.read_channels() keep the "force" ChannelConfig's unit in sync with it on every poll. This fixes the unit shown in anything that reads ChannelConfig.unit live — new plots, channel pickers, CSV log headers — but does not relabel the Y-axis of an already-open plot pane, since plot axis labels are baked into PlotConfig.y_label once at plot-build time, not re-read from the channel live. Making an open pane's axis relabel itself would need new signal plumbing from the device through AcquisitionEngine to the strip chart — a bigger, separate change. Co-Authored-By: Claude Sonnet 5 --- api_layers/protocols/mark10.py | 5 +++++ devices/serial_device.py | 8 ++++++++ 2 files changed, 13 insertions(+) (limited to 'devices/serial_device.py') diff --git a/api_layers/protocols/mark10.py b/api_layers/protocols/mark10.py index a209232..48ed927 100644 --- a/api_layers/protocols/mark10.py +++ b/api_layers/protocols/mark10.py @@ -44,6 +44,11 @@ class Mark10Layer(BaseProtocol): super().__init__(port, baud, poll_interval, simulate) self._unit = "N" + @property + def current_unit(self) -> str: + """Last unit suffix seen in a gauge reply (e.g. "N", "kgF").""" + return self._unit + # ── Protocol ────────────────────────────────────────────────────────── def _poll(self) -> Dict[str, float]: diff --git a/devices/serial_device.py b/devices/serial_device.py index 067656a..eadaa42 100644 --- a/devices/serial_device.py +++ b/devices/serial_device.py @@ -142,6 +142,14 @@ class SerialDevice(BaseDevice): raw = self._layer.read() if not raw: return {} + if self._fmt == "mark10" and hasattr(self._layer, "current_unit"): + # Gauge can be switched between lb/kgF/N/ozF on the device itself — + # keep the channel's unit in sync so new plots/pickers/CSV log + # headers pick up the currently-selected unit instead of a fixed + # default. Does not relabel the axis of an already-open plot pane. + force_ch = self.get_channel("force") + if force_ch is not None: + force_ch.unit = self._layer.current_unit if self._fmt not in _GENERIC_FORMATS: # Protocol layers already key by channel_id — pass through untouched. # (Write-only channels, e.g. CML "M1_VS", never appear in raw — correctly dropped.) -- cgit v1.2.3 From cf33095f77e6ff902fb69932fa704eb6192b3418 Mon Sep 17 00:00:00 2001 From: Christian Kolset Date: Wed, 29 Jul 2026 13:28:24 -0600 Subject: Add Developer Mode setting, Debug window, and gate simulate behind it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New Settings > General > "Developer mode" checkbox (default on, so this repo's simulate-by-default workflow is unaffected out of the box) persisted through the existing core/app_settings.py load/save functions. Exposed to code that can't easily receive the settings dict via core.app_settings.is_developer_mode()/set_developer_mode(), a small in-memory cache MainWindow keeps in sync whenever settings are loaded or applied. Debug window (ui/windows/debug_window.py): minimal first pass per the plan — a live console. core/debug_log.py tees stdout/stderr into a ring buffer + Qt signal (installed once in main.py, before anything prints), so the window shows everything printed since app start, including from background poll threads, not just what's printed while it happens to be open. Its toolbar button is hidden unless developer mode is on. Simulate gating: every device's Simulation Mode checkbox/dropdown is now hidden when developer mode is off — ui/add_device_dialog.py (also covers the motion_capture camera panel, which shares this same checkbox rather than having its own), and the per-device config widgets in analog_input.py, arduino_device.py, digital_io.py, nidaqmx_device.py, serial_device.py. Hiding rather than force-clearing an already-simulating device's state — an existing simulated device keeps working if developer mode is turned off later; the option is just not offered again until it's back on. Co-Authored-By: Claude Sonnet 5 --- core/app_settings.py | 19 +++++++++++++ core/debug_log.py | 65 +++++++++++++++++++++++++++++++++++++++++++ devices/analog_input.py | 2 ++ devices/arduino_device.py | 2 ++ devices/digital_io.py | 2 ++ devices/nidaqmx_device.py | 2 ++ devices/serial_device.py | 6 +++- main.py | 2 ++ ui/add_device_dialog.py | 2 ++ ui/main_window.py | 31 ++++++++++++++++++++- ui/windows/debug_window.py | 65 +++++++++++++++++++++++++++++++++++++++++++ ui/windows/settings_window.py | 11 ++++++++ 12 files changed, 207 insertions(+), 2 deletions(-) create mode 100644 core/debug_log.py create mode 100644 ui/windows/debug_window.py (limited to 'devices/serial_device.py') diff --git a/core/app_settings.py b/core/app_settings.py index e8bc7ae..ea3ac49 100644 --- a/core/app_settings.py +++ b/core/app_settings.py @@ -51,3 +51,22 @@ def save_settings(cfg: dict) -> None: json.dump(cfg, f, indent=2) except Exception: pass + + +# ── Developer mode ──────────────────────────────────────────────────────── +# +# In-memory cache so widgets that build device/config UI (Add Device dialog, +# per-device config panels, plugin panels) can check this without needing +# the full settings dict threaded through their constructors. MainWindow +# keeps it in sync with the persisted setting whenever settings are +# loaded/applied — see set_developer_mode() calls in ui/main_window.py. +_dev_mode = True + + +def is_developer_mode() -> bool: + return _dev_mode + + +def set_developer_mode(value: bool) -> None: + global _dev_mode + _dev_mode = value diff --git a/core/debug_log.py b/core/debug_log.py new file mode 100644 index 0000000..86a8a59 --- /dev/null +++ b/core/debug_log.py @@ -0,0 +1,65 @@ +""" +core/debug_log.py + +Tees stdout/stderr into an in-memory ring buffer + Qt signal so the Debug +window can show everything the app has printed since startup — including +messages from background poll threads (e.g. "[CMLLayer] poll error: ...") — +not just whatever gets printed while the window happens to be open. + +install() should be called once, early, before anything prints. The real +streams are still written to, so running from a terminal is unaffected. +""" + +from __future__ import annotations + +import sys +from collections import deque +from typing import Optional + +from PyQt6.QtCore import QObject, pyqtSignal + + +class _Broadcaster(QObject): + line_written = pyqtSignal(str) + + +class _StreamTee: + def __init__(self, real_stream, lines: deque, broadcaster: _Broadcaster): + self._real = real_stream + self._lines = lines + self._broadcaster = broadcaster + + def write(self, text: str) -> None: + self._real.write(text) + if text: + self._lines.append(text) + self._broadcaster.line_written.emit(text) + + def flush(self) -> None: + self._real.flush() + + def isatty(self) -> bool: + return False + + +_lines: Optional[deque] = None +_broadcaster: Optional[_Broadcaster] = None + + +def install(max_lines: int = 2000) -> None: + """Redirect sys.stdout/sys.stderr through the tee. Safe to call once.""" + global _lines, _broadcaster + if _broadcaster is not None: + return + _lines = deque(maxlen=max_lines) + _broadcaster = _Broadcaster() + sys.stdout = _StreamTee(sys.stdout, _lines, _broadcaster) + sys.stderr = _StreamTee(sys.stderr, _lines, _broadcaster) + + +def get_broadcaster() -> Optional[_Broadcaster]: + return _broadcaster + + +def get_history() -> str: + return "".join(_lines) if _lines is not None else "" diff --git a/devices/analog_input.py b/devices/analog_input.py index c9e5d2a..6ac82d4 100644 --- a/devices/analog_input.py +++ b/devices/analog_input.py @@ -250,6 +250,8 @@ class AnalogInputConfigWidget(QWidget): self.sim_check = QCheckBox("Simulation Mode (no hardware)") self.sim_check.setChecked(self.device.simulate) + from core.app_settings import is_developer_mode + self.sim_check.setVisible(is_developer_mode()) be_form.addRow(self.sim_check) root.addWidget(be_grp) diff --git a/devices/arduino_device.py b/devices/arduino_device.py index 7c1d21b..954d387 100644 --- a/devices/arduino_device.py +++ b/devices/arduino_device.py @@ -287,6 +287,8 @@ class ArduinoConfigWidget(QWidget): self.sim_chk = QCheckBox("Simulation Mode (no hardware)") self.sim_chk.setChecked(self.device.simulate) + from core.app_settings import is_developer_mode + self.sim_chk.setVisible(is_developer_mode()) ser_form.addRow(self.sim_chk) scan_row = QHBoxLayout() diff --git a/devices/digital_io.py b/devices/digital_io.py index 53395dc..2bd0243 100644 --- a/devices/digital_io.py +++ b/devices/digital_io.py @@ -290,6 +290,8 @@ class DigitalIOConfigWidget(QWidget): be_form.addRow("Backend:", self.be_cb) self.sim_chk = QCheckBox("Simulate") self.sim_chk.setChecked(self.device.simulate) + from core.app_settings import is_developer_mode + self.sim_chk.setVisible(is_developer_mode()) be_form.addRow(self.sim_chk) self.ni_dev_edit = QLineEdit(self.device._ni_device) diff --git a/devices/nidaqmx_device.py b/devices/nidaqmx_device.py index 88bb932..3f64998 100644 --- a/devices/nidaqmx_device.py +++ b/devices/nidaqmx_device.py @@ -294,6 +294,8 @@ class NidaqmxConfigWidget(QWidget): self.sim_chk = QCheckBox("Simulation Mode (no hardware)") self.sim_chk.setChecked(self.device.simulate) + from core.app_settings import is_developer_mode + self.sim_chk.setVisible(is_developer_mode()) ni_form.addRow(self.sim_chk) scan_row = QHBoxLayout() diff --git a/devices/serial_device.py b/devices/serial_device.py index 067656a..bd953b8 100644 --- a/devices/serial_device.py +++ b/devices/serial_device.py @@ -448,7 +448,11 @@ class SerialConfigWidget(QWidget): self._sim_cb = QComboBox() self._sim_cb.addItems(["Simulate", "Real Hardware"]) self._sim_cb.setCurrentIndex(0 if self.device.simulate else 1) - conn_form.addRow("Mode:", self._sim_cb) + from core.app_settings import is_developer_mode + mode_lbl = QLabel("Mode:") + dev_mode = is_developer_mode() + mode_lbl.setVisible(dev_mode); self._sim_cb.setVisible(dev_mode) + conn_form.addRow(mode_lbl, self._sim_cb) root.addWidget(conn_grp) diff --git a/main.py b/main.py index b023b99..ede6277 100644 --- a/main.py +++ b/main.py @@ -13,11 +13,13 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from PyQt6.QtWidgets import QApplication from ui.main_window import MainWindow +from core.debug_log import install as install_debug_log def main(): app = QApplication(sys.argv) app.setApplicationName("LabDAQ") + install_debug_log() # tee stdout/stderr for the Debug window, before anything prints qss = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ui", "style_dark.qss") if os.path.exists(qss): diff --git a/ui/add_device_dialog.py b/ui/add_device_dialog.py index 2956a96..4b2b373 100644 --- a/ui/add_device_dialog.py +++ b/ui/add_device_dialog.py @@ -17,6 +17,7 @@ from devices.device_registry import DeviceRegistry from devices.arduino_device import ArduinoDevice from devices.nidaqmx_device import NidaqmxDevice from devices.serial_device import SerialDevice, _FORMAT_LABELS +from core.app_settings import is_developer_mode # ── Background scan threads ─────────────────────────────────────────────────── @@ -276,6 +277,7 @@ class AddDeviceDialog(QDialog): conn_form.addRow(self._ni_lbl, self._ni_edit) self._sim_chk = QCheckBox("Simulation mode") + self._sim_chk.setVisible(is_developer_mode()) # dev-mode-only escape hatch conn_form.addRow(self._sim_chk) root.addLayout(conn_form) diff --git a/ui/main_window.py b/ui/main_window.py index d0e0ac4..ca4274c 100644 --- a/ui/main_window.py +++ b/ui/main_window.py @@ -45,7 +45,7 @@ from ui.windows.settings_window import SettingsWindow from plugins.plugin_manager import PluginManager from plugins.base_plugin import PluginContext -from core.app_settings import load_settings, save_settings +from core.app_settings import load_settings, save_settings, set_developer_mode _DARK_QSS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "style_dark.qss") @@ -68,6 +68,7 @@ class MainWindow(QMainWindow): self._win_channels = None self._win_plot = None self._win_settings = None + self._win_debug = None _plugins_dir = os.path.join(os.path.dirname(os.path.dirname( os.path.abspath(__file__))), "plugins") @@ -171,6 +172,12 @@ class MainWindow(QMainWindow): set_btn.clicked.connect(lambda c: self._toggle_win("settings", c, set_btn)) tb.addWidget(set_btn); self._btn_settings = set_btn + debug_btn = QPushButton("🐞 Debug") + debug_btn.setObjectName("toolbarSectionBtn"); debug_btn.setCheckable(True) + debug_btn.clicked.connect(lambda c: self._toggle_win("debug", c, debug_btn)) + tb.addWidget(debug_btn); self._btn_debug = debug_btn + debug_btn.setVisible(False) # shown/hidden per developer-mode setting + # ── Central ─────────────────────────────────────────────────────── central = QWidget(); self.setCentralWidget(central) @@ -314,12 +321,14 @@ class MainWindow(QMainWindow): "channels": self._open_channels, "plot": self._open_plot, "settings": self._open_settings, + "debug": self._open_debug, } wins = { "devices": "_win_devices", "channels": "_win_channels", "plot": "_win_plot", "settings": "_win_settings", + "debug": "_win_debug", } if checked: creators[name]() @@ -370,6 +379,22 @@ class MainWindow(QMainWindow): self._win_settings.closed.connect(lambda: self._btn_settings.setChecked(False)) self._show_win(self._win_settings, "right") + def _open_debug(self): + from ui.windows.debug_window import DebugWindow + if self._win_debug is None: + self._win_debug = DebugWindow(self) + self._win_debug.closed.connect(lambda: self._btn_debug.setChecked(False)) + self._show_win(self._win_debug, "right") + + def _update_debug_btn_visibility(self): + from core.app_settings import is_developer_mode + on = is_developer_mode() + self._btn_debug.setVisible(on) + if not on: + self._btn_debug.setChecked(False) + if self._win_debug: + self._win_debug.hide() + def _show_win(self, win: QWidget, position: str = "right"): if not win.isVisible(): screen = QApplication.screenAt(self.geometry().center()) @@ -554,10 +579,14 @@ class MainWindow(QMainWindow): def _apply_settings_on_startup(self): self._apply_theme(self._settings.get("theme", "dark")) self.engine._interval = self._settings.get("poll_ms", 100) / 1000.0 + set_developer_mode(self._settings.get("developer_mode", True)) + self._update_debug_btn_visibility() def _on_settings(self, cfg: dict): self._settings.update(cfg) self.engine._interval = cfg.get("poll_ms", 100) / 1000.0 + set_developer_mode(self._settings.get("developer_mode", True)) + self._update_debug_btn_visibility() save_settings(self._settings) def _tick(self): diff --git a/ui/windows/debug_window.py b/ui/windows/debug_window.py new file mode 100644 index 0000000..0e891ed --- /dev/null +++ b/ui/windows/debug_window.py @@ -0,0 +1,65 @@ +""" +ui/windows/debug_window.py + +DEBUG window — developer-mode only. + +Minimal first pass: a live console showing everything the app has printed +via core.debug_log (stdout/stderr tee), so debugging doesn't require a +terminal. Not wired to any other diagnostics yet — extend as needed. +""" + +from PyQt6.QtWidgets import ( + QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, + QTextEdit, QFrame, +) +from PyQt6.QtCore import Qt, pyqtSignal +from PyQt6.QtGui import QFont, QCloseEvent + +from core.debug_log import get_broadcaster, get_history + + +class DebugWindow(QWidget): + closed = pyqtSignal() + + def __init__(self, parent=None): + super().__init__(parent, Qt.WindowType.Window | Qt.WindowType.Tool) + self.setWindowTitle("Debug") + self.setMinimumSize(560, 420) + self.resize(700, 500) + self._build() + + broadcaster = get_broadcaster() + if broadcaster is not None: + broadcaster.line_written.connect(self._append) + + def _build(self): + root = QVBoxLayout(self); root.setContentsMargins(0, 0, 0, 0); root.setSpacing(0) + + hdr = QWidget(); hdr.setObjectName("devWindowTitleBar"); hdr.setFixedHeight(44) + hl = QHBoxLayout(hdr); hl.setContentsMargins(14, 0, 14, 0) + title = QLabel("DEBUG"); title.setObjectName("devWindowTitle") + hl.addWidget(title, 1) + clear_btn = QPushButton("Clear"); clear_btn.setObjectName("configButton") + clear_btn.clicked.connect(lambda: self._console.clear()) + hl.addWidget(clear_btn) + root.addWidget(hdr) + + div = QFrame(); div.setFrameShape(QFrame.Shape.HLine) + div.setObjectName("devWindowDivider"); root.addWidget(div) + + self._console = QTextEdit(); self._console.setObjectName("codeEditor") + self._console.setReadOnly(True) + mono = QFont("IBM Plex Mono, Consolas, Monospace") + mono.setStyleHint(QFont.StyleHint.Monospace) + self._console.setFont(mono) + self._console.setPlainText(get_history()) + self._console.verticalScrollBar().setValue(self._console.verticalScrollBar().maximum()) + root.addWidget(self._console, 1) + + def _append(self, text: str): + self._console.insertPlainText(text) + sb = self._console.verticalScrollBar() + sb.setValue(sb.maximum()) + + def closeEvent(self, e: QCloseEvent): + self.closed.emit(); e.accept() diff --git a/ui/windows/settings_window.py b/ui/windows/settings_window.py index 1630efa..e24da7f 100644 --- a/ui/windows/settings_window.py +++ b/ui/windows/settings_window.py @@ -40,6 +40,7 @@ class SettingsWindow(QWidget): "show_grid": True, "font_size": 12, "antialias": True, + "developer_mode": True, } def __init__(self, registry: DeviceRegistry, @@ -108,6 +109,14 @@ class SettingsWindow(QWidget): self._aa_chk = QCheckBox(); self._aa_chk.setChecked(self.cfg["antialias"]) lay.addRow("Anti-alias plots:", self._aa_chk) + self._dev_chk = QCheckBox() + self._dev_chk.setChecked(self.cfg["developer_mode"]) + self._dev_chk.setToolTip( + "Controls whether the Debug window and each device's Simulation\n" + "Mode option are available. Off = real-hardware-only, no debug tools." + ) + lay.addRow("Developer mode:", self._dev_chk) + rst = QPushButton("Reset to Defaults"); rst.setObjectName("configButton") rst.clicked.connect(self._reset_to_defaults) lay.addRow("", rst) @@ -120,6 +129,7 @@ class SettingsWindow(QWidget): self._theme_cb.setCurrentText(self.cfg["theme"].title()) self._font_sp.setValue(self.cfg["font_size"]) self._aa_chk.setChecked(self.cfg["antialias"]) + self._dev_chk.setChecked(self.cfg["developer_mode"]) self._poll_sp.setValue(self.cfg["poll_ms"]) self._buf_sp.setValue(self.cfg["buffer_size"]) self._log_edit.setText(self.cfg["log_dir"]) @@ -288,6 +298,7 @@ class SettingsWindow(QWidget): "theme": theme, "font_size": self._font_sp.value(), "antialias": self._aa_chk.isChecked(), + "developer_mode": self._dev_chk.isChecked(), "poll_ms": self._poll_sp.value(), "buffer_size": self._buf_sp.value(), "log_dir": self._log_edit.text(), -- cgit v1.2.3