CLI for SidePulse
Python
Support read-only SidePulse mounts with automatic LED transport fallback
Peter Kuhar05bc5edbb2a4
diff --git a/MANIFEST.in b/MANIFEST.inindex 35ff3fe..76ee144 100644--- a/MANIFEST.in+++ b/MANIFEST.in@@ -4,6 +4,8 @@ include README.mdinclude pyproject.tomlrecursive-include src *.c *.LED *.py *.wasmrecursive-include tests *.py+include tests/fixtures/read2me-vectors.txt+include src/sidepulse/_vendor/README.mdprune .githubprune datadiff --git a/README.md b/README.mdindex d4b2391..af0ab99 100644--- a/README.md+++ b/README.md@@ -143,6 +143,27 @@ sidepulse write "off" --device /media/$USER/SidePulseDotThe writer decodes simple escapes such as `\n`, then enforces the controller's512-byte and 20-line limits before writing the LED control file.+Mounted drives restricted to **read-only storage**, including by an MDM policy,+automatically use an alternate LED transport on **firmware 1.1 or newer**:+SidePulse Pro uses READ2ME through SD reads of `setup.html` (macOS), and+SidePulse Dot uses direct SPC2 USB control (macOS and Linux). This applies to+the CLI, menu bar, battery display, and background service without extra flags.+Dot's USB library is included with the app and installed as a Python dependency.++The app tries a normal file write first and falls back only when opening+`LEDS.LED` is denied as read-only or by permissions. A failure after writing+begins is never replayed through another transport. The firmware version is+checked in `STATUS.TXT`; older or unrecognized firmware produces an error.+Upgrade older firmware using a computer that permits storage writes.++Alternate transports require a valid device acknowledgement before reporting+success. Dot is matched to the selected mount's USB connection, including when+multiple devices are attached. USB access can still be blocked by management+policy, and Pro's SD reader must support uncached reads; these failures are+reported without changing mount permissions. The fallback controls live LEDs;+it does not install firmware or change startup programs. Pro file contents may+appear stale until remount; Dot USB commands do not modify `LEDS.LED`.+For an **unmounted macOS device**, the standalone standard-library utility canwrite the existing `LEDS.LED` directly through `/dev/diskN` or `/dev/rdiskN`:@@ -687,8 +708,8 @@ clamshell mode and SidePulse's no-external-display fallback, is documented in| When Agents Work | Keep the Mac awake while agents are Working / Tool Running / Progressing, plus the existing five-minute Ask / Done / Error grace period. || Always | Keep the closed-lid sleep override active while the status-bar app is running. |-The status-bar app still keeps the SidePulse Pro/SidePulse Dot volume active by touching-a `keepalive` file on each connected device at least once per minute. The+The status-bar app still keeps the SidePulse Pro/SidePulse Dot volume active by reading+`STATUS.TXT` with the existing uncached, read-only macOS transport on each connected device at least once per minute. Theclosed-lid policy uses the SidePulse sleep helper when it is installed. The PKGinstaller sets this up automatically; source/dev installs can run the one-timesetup command:diff --git a/packaging/build_macos_pkg.sh b/packaging/build_macos_pkg.shindex d43ee23..4698995 100755--- a/packaging/build_macos_pkg.sh+++ b/packaging/build_macos_pkg.sh@@ -42,6 +42,7 @@ OUTPUT_PKG="$DIST_DIR/SidePulse-${VERSION}-${ARCH}.pkg"--specpath "$BUILD_DIR" \--collect-submodules Cocoa \--collect-data sidepulse.resources \+ --collect-all libusb_package \"$ROOT_DIR/packaging/sidepulse_entry.py"/usr/libexec/PlistBuddy -c "Add :CFBundleShortVersionString string $VERSION" "$APP_PATH/Contents/Info.plist" 2>/dev/null || \diff --git a/pyproject.toml b/pyproject.tomlindex 6af2a1b..8ac1322 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -29,6 +29,7 @@ classifiers = ["Topic :: Utilities",]dependencies = [+ "libusb-package>=1.0.26,<2","qrcode>=8,<9","pyobjc-framework-Cocoa>=10; sys_platform == 'darwin'","pyobjc-framework-Quartz>=10; sys_platform == 'darwin'",diff --git a/src/sidepulse/_vendor/README.md b/src/sidepulse/_vendor/README.mdnew file mode 100644index 0000000..0d2828a--- /dev/null+++ b/src/sidepulse/_vendor/README.md@@ -0,0 +1,15 @@+# READ2ME++`read2me.py` is the dependency-free Python protocol client from+`sdstatus_bitbang/utils/read2me/python/sidepulse_read2me/protocol.py`, copied+2026-09-29 (source checkout HEAD bb5910ad713b2fd353f73f8358bc957a662fdd5e).+The shared interoperability vectors and protocol tests are included in this+repository. Keep the aligned reads, cache invalidation, freshness probe and+completion checks together when updating this client.++`sidepulse/usb_control.py` is adapted from that checkout's+`utils/usb-control/sidepulse_usb_control.py`: packaged libusb discovery,+mount-to-USB selection, and ambiguous-write reconciliation are added here.++The application exposes these transports only for LED writes on firmware+1.1 or newer. Firmware updates are outside the automatic fallback API.diff --git a/src/sidepulse/_vendor/__init__.py b/src/sidepulse/_vendor/__init__.pynew file mode 100644index 0000000..a937ccf--- /dev/null+++ b/src/sidepulse/_vendor/__init__.py@@ -0,0 +1 @@+"""Bundled SidePulse protocol clients; see README.md for provenance."""diff --git a/src/sidepulse/_vendor/read2me.py b/src/sidepulse/_vendor/read2me.pynew file mode 100644index 0000000..6472999--- /dev/null+++ b/src/sidepulse/_vendor/read2me.py@@ -0,0 +1,303 @@+#!/usr/bin/env python3+"""Send SidePulse files using only read requests to setup.html (macOS)."""+from __future__ import annotations++import binascii+import ctypes+import os+from pathlib import Path+import secrets+import struct+import sys+import time++FIRMWARE_REBOOT_QUIET_SECONDS = 5++START = (16, 16, 1, 2, 3, 4)+STOP = (17, 17, 4, 3, 2, 1)+STATES = ("IDLE", "RECEIVING", "VALIDATING", "DONE", "ERROR")+ERRORS = ("NONE", "FRAME", "CRC", "HEADER", "OFFSET", "CONFLICT", "BUSY", "APPLY", "OVERFLOW")+++def crc16(data: bytes) -> int:+ return binascii.crc_hqx(data, 0xffff)+++def frame(transfer_id: int, name: str, total: int, offset: int, data: bytes) -> list[int]:+ if not 1 <= transfer_id <= 0xffffffff or not 1 <= total <= 0xffffffff:+ raise ValueError("transfer ID and total must be nonzero u32 values")+ filename = name.upper().encode("ascii")+ if filename not in (b"LEDS.LED", b"INIT.LED", b"FIRMWARE.BIN", b"SIDEPULSE_OTA.BIN"):+ raise ValueError("unsupported destination")+ if filename in (b"LEDS.LED", b"INIT.LED") and total > 512:+ raise ValueError("LED programs are limited to 512 bytes")+ if not 1 <= len(data) <= 512 or not 0 <= offset < total or offset + len(data) > total:+ raise ValueError("invalid chunk range")+ packet = struct.pack(">BIB", 1, transfer_id, len(filename)) + filename+ packet += struct.pack(">IIH", total, offset, len(data)) + data+ packet += struct.pack(">H", crc16(packet))+ return [*START, *(n for b in packet for n in (b >> 4, b & 15)), *STOP]+++def decode_status(data: bytes) -> dict:+ """Decode one 512-byte setup.html sector, including its status CRC."""+ prefix = b"<!--READ2ME1:"+ start = 256 + len(prefix)+ if len(data) != 512 or data[256:start] != prefix or data[start + 128:start + 132] != b"-->\n":+ raise ValueError("invalid setup.html status envelope")+ encoded = data[start:start + 128]+ if any(c not in b"0123456789abcdef" for c in encoded):+ raise ValueError("invalid setup.html status hex")+ data = bytes.fromhex(encoded.decode('ascii'))+ if len(data) < 64 or data[:8] != b"READ2ME1" or data[8] != 1:+ raise ValueError("not a READ2ME v1 response; stale cache or firmware without READ2ME")+ if crc16(data[:62]) != struct.unpack_from(">H", data, 62)[0]:+ raise ValueError("torn status response")+ if data[9] >= len(STATES) or data[10] >= len(ERRORS) or data[11] > 2:+ raise ValueError("unknown status state, error, or target")+ fields = struct.unpack_from(">8I", data, 12)+ result = dict(zip(("transfer_id", "total", "received", "accepted_chunks", "errors", "symbols", "overflows", "capacity"), fields))+ result.update(state=STATES[data[9]], error=ERRORS[data[10]], target=data[11],+ payload_crc16=struct.unpack_from(">H", data, 44)[0],+ uptime_ms=struct.unpack_from(">I", data, 46)[0],+ read_requests=struct.unpack_from(">I", data, 50)[0],+ last_read_lba=struct.unpack_from(">I", data, 54)[0])+ return result+++class _MacFile:+ """Read-only, aligned positional I/O; also used for fresh ordinary file reads."""+ def __init__(self, path: Path, expected_size=None):+ if sys.platform != "darwin":+ raise OSError("READ2ME hardware transport currently supports macOS only")+ import fcntl+ self.libc = ctypes.CDLL(None, use_errno=True)+ self.libc.posix_memalign.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_size_t, ctypes.c_size_t]+ self.libc.pread.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_longlong]+ self.libc.pread.restype = ctypes.c_ssize_t+ self.libc.free.argtypes = [ctypes.c_void_p]+ self.buffer = ctypes.c_void_p()+ self.fd = os.open(path, os.O_RDONLY)+ try:+ if expected_size is not None and os.fstat(self.fd).st_size != expected_size:+ raise ValueError(f"control file must be exactly {expected_size} bytes")+ fcntl.fcntl(self.fd, 48, 1) # Darwin F_NOCACHE+ fcntl.fcntl(self.fd, 45, 0) # Darwin F_RDAHEAD+ # F_NOCACHE alone is insufficient: an unaligned Python bytes buffer+ # makes macOS read surrounding sectors, corrupting address symbols.+ page_size = os.sysconf("SC_PAGESIZE")+ result = self.libc.posix_memalign(ctypes.byref(self.buffer), page_size, page_size)+ if result:+ raise OSError(result, os.strerror(result))+ except BaseException:+ os.close(self.fd)+ raise++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ self.close()++ def close(self):+ if self.fd < 0:+ return+ self.libc.free(self.buffer)+ self.buffer = ctypes.c_void_p()+ os.close(self.fd)+ self.fd = -1++ def invalidate_cache(self):+ """Evict existing cached pages before reading an ordinary status file."""+ if self.fd < 0:+ raise ValueError("channel is closed")+ size = os.fstat(self.fd).st_size+ if size == 0:+ return+ self.libc.mmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int,+ ctypes.c_int, ctypes.c_int, ctypes.c_longlong]+ self.libc.mmap.restype = ctypes.c_void_p+ self.libc.msync.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int]+ self.libc.msync.restype = ctypes.c_int+ self.libc.munmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t]+ self.libc.munmap.restype = ctypes.c_int+ # PROT_READ | MAP_SHARED; never access the mapping itself.+ address = self.libc.mmap(None, size, 1, 1, self.fd, 0)+ if address == ctypes.c_void_p(-1).value:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ try:+ if self.libc.msync(address, size, 2) != 0: # MS_INVALIDATE+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ finally:+ if self.libc.munmap(address, size) != 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))++ def read_at(self, offset: int) -> bytes:+ if self.fd < 0:+ raise ValueError("channel is closed")+ count = self.libc.pread(self.fd, self.buffer, 512, offset)+ if count < 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ return ctypes.string_at(self.buffer, count)+++class Channel(_MacFile):+ """Synchronous READ2ME v1 sender. Use as a context manager; serialize callers."""+ def __init__(self, path: Path):+ super().__init__(path, 19 * 512)+ self._cache_mapping = None+ try:+ self.libc.mmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int,+ ctypes.c_int, ctypes.c_int, ctypes.c_longlong]+ self.libc.mmap.restype = ctypes.c_void_p+ self.libc.msync.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int]+ self.libc.msync.restype = ctypes.c_int+ self.libc.munmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t]+ self.libc.munmap.restype = ctypes.c_int+ # PROT_READ | MAP_SHARED. Never touch the mapping: doing so would+ # fault in pages and issue unwanted read-address symbols.+ address = self.libc.mmap(None, 19 * 512, 1, 1, self.fd, 0)+ if address == ctypes.c_void_p(-1).value:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ self._cache_mapping = address+ except BaseException:+ self.close()+ raise++ def close(self):+ address = getattr(self, '_cache_mapping', None)+ self._cache_mapping = None+ try:+ if address is not None and self.libc.munmap(address, 19 * 512) != 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))+ finally:+ super().close()++ def _invalidate_cache(self):+ if self.fd < 0:+ raise ValueError("channel is closed")+ # F_NOCACHE does not evict pages previously populated by cat/Finder.+ # MS_INVALIDATE drops the control file's cached pages without reading+ # through the mapping. Do this before every read, even on reused handles.+ if self.libc.msync(self._cache_mapping, 19 * 512, 2) != 0:+ error = ctypes.get_errno()+ raise OSError(error, os.strerror(error))++ def read(self, symbol: int) -> bytes:+ if not 0 <= symbol <= 18:+ raise ValueError("invalid symbol")+ self._invalidate_cache()+ data = self.read_at(symbol * 512)+ if len(data) != 512:+ raise OSError("short control-file read")+ return data++ def status(self) -> dict:+ for _ in range(10):+ try:+ return decode_status(self.read(18))+ except ValueError:+ time.sleep(0.01)+ return decode_status(self.read(18))++ def send_frame(self, symbols: list[int]):+ for symbol in symbols:+ self.read(symbol)++ def probe(self) -> dict:+ """Check that control-address reads cause observable receiver progress."""+ before = self.status()+ # A partial START resets framing but cannot commit any command.+ self.send_frame([*START, 16])+ deadline = time.monotonic() + 1+ while True:+ after = self.status()+ delta = (after["symbols"] - before["symbols"]) & 0xffffffff+ if delta > len(START) + 1:+ raise RuntimeError("Unexpected extra control symbols; another reader or read aggregation is interfering")+ if delta == len(START) + 1 and after["read_requests"] != before["read_requests"]:+ return after+ if time.monotonic() >= deadline:+ raise RuntimeError(+ "Control reads produced no fresh symbol acknowledgement. "+ "Filesystem/reader caching or read aggregation may prevent this channel; "+ "F_NOCACHE alone is not sufficient on every Mac. No upload was started."+ )+ time.sleep(0.01)++ def upload(self, data: bytes, name: str, transfer_id: int | None = None,+ chunk_size: int = 512, retries: int = 3, progress=None,+ ack_timeout: float = 2, completion_timeout: float = 30) -> dict:+ name = name.upper()+ # Validate all inputs before the probe changes receiver framing.+ frame(transfer_id if transfer_id is not None else 1, name, len(data), 0, data[:512])+ if ack_timeout < 0 or completion_timeout < 0:+ raise ValueError("timeouts cannot be negative")+ if retries < 0:+ raise ValueError("retries cannot be negative")+ initial = self.status()+ if initial["state"] == "VALIDATING":+ raise RuntimeError("device is busy validating another transfer")+ if transfer_id is not None and transfer_id == initial["transfer_id"]:+ raise ValueError("use a fresh transfer ID for a new upload")+ if not 0 < len(data) <= initial["capacity"]:+ raise ValueError("payload exceeds receiver capacity or is empty")+ if name.upper() in ("LEDS.LED", "INIT.LED") and len(data) > 512:+ raise ValueError("LED programs are limited to 512 bytes")+ if not 1 <= chunk_size <= 512:+ raise ValueError("chunk size must be 1..512")+ self.probe()+ if transfer_id is None:+ transfer_id = secrets.randbelow(0xffffffff) + 1+ while transfer_id == initial["transfer_id"]:+ transfer_id = secrets.randbelow(0xffffffff) + 1+ target = 0 if name == "LEDS.LED" else 1 if name == "INIT.LED" else 2+ def matches(status):+ return (status["transfer_id"] == transfer_id and status["total"] == len(data)+ and status["target"] == target)++ final_firmware_frame = False+ try:+ for offset in range(0, len(data), chunk_size):+ chunk = data[offset:offset + chunk_size]+ symbols = frame(transfer_id, name, len(data), offset, chunk)+ if target == 2 and offset + len(chunk) == len(data):+ final_firmware_frame = True+ for attempt in range(retries + 1):+ self.send_frame(symbols)+ deadline = time.monotonic() + ack_timeout+ while True:+ status = self.status()+ if matches(status) and status["received"] >= offset + len(chunk):+ break+ if time.monotonic() >= deadline:+ break+ time.sleep(0.01)+ if matches(status) and status["received"] >= offset + len(chunk):+ break+ if attempt == retries:+ raise RuntimeError(f"chunk at {offset} was not acknowledged: {status}")+ if progress and not (target == 2 and offset + len(chunk) == len(data)):+ progress(offset + len(chunk), len(data))+ deadline = time.monotonic() + completion_timeout+ while status["state"] == "VALIDATING" and time.monotonic() < deadline:+ time.sleep(0.02)+ status = self.status()+ if not matches(status) or status["received"] != len(data) or status["state"] != "DONE" or status["error"] != "NONE":+ raise RuntimeError(f"upload did not finish successfully: {status}")+ if status["payload_crc16"] != crc16(data):+ raise RuntimeError("received payload checksum differs")+ finally:+ # Also stay quiet on an ambiguous final acknowledgement / I/O error:+ # the board may already be restarting. Never probe during this wait.+ if final_firmware_frame:+ time.sleep(FIRMWARE_REBOOT_QUIET_SECONDS)+ if target == 2 and progress:+ progress(len(data), len(data))+ return statusdiff --git a/src/sidepulse/device_writer.py b/src/sidepulse/device_writer.pyindex c2e748a..13d7de8 100644--- a/src/sidepulse/device_writer.py+++ b/src/sidepulse/device_writer.py@@ -1,7 +1,11 @@from __future__ import annotations+import errno+import hashlibimport osimport sys+import threading+from contextlib import contextmanagerfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Iterable@@ -17,6 +21,7 @@ DEVICE_NAME_HINTS = ("sidepulsedot","pulsedot",)+_WRITE_LOCK = threading.Lock()class DeviceWriteError(RuntimeError):@@ -59,11 +64,28 @@ def write_normalized_led_program(if dry_run:return target- target.parent.mkdir(parents=True, exist_ok=True)- write_text_synced(target, program)+ with device_write_lock(target.parent):+ target.parent.mkdir(parents=True, exist_ok=True)+ write_text_synced(target, program)return target+@contextmanager+def device_write_lock(root: Path):+ """Serialize this app's file/USB/read-channel writers across threads and processes."""+ import fcntl++ key = hashlib.sha256(os.fsencode(root.resolve())).hexdigest()+ directory = Path.home() / ".cache" / "sidepulse" / "device-locks"+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)+ with _WRITE_LOCK, (directory / key).open("a") as lock:+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX)+ try:+ yield+ finally:+ fcntl.flock(lock.fileno(), fcntl.LOCK_UN)++def write_text_synced(target: Path, text: str) -> None:"""Write text and force it to the device before returning.@@ -74,7 +96,17 @@ def write_text_synced(target: Path, text: str) -> None:"""is_new = not path_exists(target)- with target.open("w", encoding="utf-8") as handle:+ try:+ handle = target.open("w", encoding="utf-8")+ except OSError as exc:+ if exc.errno not in (errno.EROFS, errno.EACCES, errno.EPERM):+ raise+ from .readonly_control import write_readonly_program++ write_readonly_program(target, text)+ return+ # Only a denied open may change transports. Never replay a partial write.+ with handle:handle.write(text)handle.flush()sync_fd(handle.fileno())diff --git a/src/sidepulse/keep_awake.py b/src/sidepulse/keep_awake.pyindex 74cd3c6..3715eaa 100644--- a/src/sidepulse/keep_awake.py+++ b/src/sidepulse/keep_awake.py@@ -14,7 +14,7 @@ from .models import AgentModeAWAKE_GRACE_SECONDS = 300.0SD_STATUS_READ_SECONDS = 60.0KEEPALIVE_FILE_NAME = "keepalive"-STATUS_FILE_NAME = KEEPALIVE_FILE_NAME+STATUS_FILE_NAME = "STATUS.TXT"CAFFEINATE_COMMAND = ("/usr/bin/caffeinate", "-ims")@@ -36,7 +36,7 @@ class KeepAwakeController:self.status_read_seconds = status_read_secondsself.command = tuple(command)self.process_factory = process_factory or subprocess.Popen- self.status_reader = status_reader or touch_keepalive_file+ self.status_reader = status_reader or read_status_fileself.status_read_async = status_read_asyncself.watch_current_process = watch_current_processself.process = None@@ -194,22 +194,21 @@ def status_file_for_target(target: Path) -> Path:def keepalive_file_for_target(target: Path) -> Path:known_file_names = KNOWN_LED_FILE_NAMES | {KEEPALIVE_FILE_NAME.upper(), "STATUS.TXT"}if target.name.upper() in known_file_names:- return target.parent / KEEPALIVE_FILE_NAME- return target / KEEPALIVE_FILE_NAME+ return target.parent / STATUS_FILE_NAME+ return target / STATUS_FILE_NAMEdef read_status_file(path: Path) -> None:- touch_keepalive_file(path)+ from .device_writer import device_write_lock+ from .readonly_control import read_status_bytes++ with device_write_lock(path.parent):+ read_status_bytes(path)def touch_keepalive_file(path: Path) -> None:- subprocess.run(- ["/usr/bin/touch", str(path)],- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- timeout=2,- check=True,- )+ """Compatibility alias: keepalive now reads STATUS.TXT without writing."""+ read_status_file(status_file_for_target(path))def format_duration(seconds: int) -> str:diff --git a/src/sidepulse/readonly_control.py b/src/sidepulse/readonly_control.pynew file mode 100644index 0000000..b8aae8d--- /dev/null+++ b/src/sidepulse/readonly_control.py@@ -0,0 +1,150 @@+"""Automatic LED-only transport fallback for denied filesystem write-open."""+from __future__ import annotations++import os+from pathlib import Path+import plistlib+import re+import subprocess+import sys++from .device_writer import DeviceWriteError++# Accessed with device_write_lock held. A service tick is not authorization to+# resubmit a USB command whose acknowledgement was lost. An explicit new CLI+# invocation or a different program can start a new command.+_uncertain_programs: dict[Path, bytes] = {}+++def read_status_bytes(path: Path) -> bytes:+ """Read status with the read-only, uncached macOS transport."""+ if sys.platform == "darwin":+ from ._vendor.read2me import _MacFile++ with _MacFile(path) as stream:+ stream.invalidate_cache()+ data = b""+ for offset in range(0, 4096, 512):+ block = stream.read_at(offset)+ data += block+ if len(block) < 512:+ break+ else:+ with path.open("rb") as stream:+ data = stream.read(4096)+ return data+++def read_device_info(root: Path) -> tuple[str, str]:+ data = read_status_bytes(root / "STATUS.TXT")+ fields = {}+ for line in data.decode("ascii", errors="replace").splitlines():+ pair = line.strip("\0 \r").split(None, 1)+ if len(pair) == 2:+ fields[pair[0]] = pair[1]+ # These are the production status formats, including unassigned devices.+ dot = "app_version" in fields+ pro = "release_version" in fields and "firmware_version" in fields+ if dot == pro:+ raise DeviceWriteError("Cannot identify SidePulse model and firmware from STATUS.TXT.")+ if dot:+ model, version = "Dot", fields["app_version"]+ else:+ model, version = "Pro", fields["release_version"]+ match = re.fullmatch(r"v?(\d+)\.(\d+)(?:\.(\d+))?(-[^+\s]+)?(?:\+[^\s]+)?", version)+ if match:+ number = tuple(int(part or 0) for part in match.group(1, 2, 3))+ if not match or number < (1, 1, 0) or (number == (1, 1, 0) and match.group(4)):+ raise DeviceWriteError(+ f"Read-only control requires SidePulse firmware 1.1 or newer; {model} reports {version}. "+ "Update the firmware using a computer that permits storage writes."+ )+ return model, version+++def write_readonly_program(target: Path, text: str) -> None:+ """Called only after write-open was denied, with the writer lock held."""+ if target.name.upper() != "LEDS.LED":+ raise DeviceWriteError("Automatic read-only fallback supports LEDS.LED only.")+ try:+ model, _ = read_device_info(target.parent)+ if model == "Pro":+ from ._vendor.read2me import Channel++ with Channel(target.parent / "setup.html") as channel:+ channel.upload(text.encode("utf-8"), "LEDS.LED")+ else:+ from .usb_control import Device, UncertainUSBWriteError++ key = target.parent.resolve()+ payload = text.encode("utf-8")+ if _uncertain_programs.get(key) == payload:+ raise DeviceWriteError(+ "Previous USB LED command has an uncertain result; automatic replay stopped. "+ "Select a different program or retry explicitly with sidepulse write."+ )+ _uncertain_programs.pop(key, None)+ bus, address = usb_address_for_volume(target.parent)+ with Device(bus=bus, address=address) as device:+ try:+ device.write(payload)+ except UncertainUSBWriteError:+ _uncertain_programs[key] = payload+ raise+ except DeviceWriteError:+ raise+ except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc:+ raise DeviceWriteError(f"Read-only LED control failed for {target.parent}: {exc}") from exc+++def _plist_command(command: list[str]):+ return plistlib.loads(subprocess.run(+ command, check=True, capture_output=True, timeout=5,+ ).stdout)+++def usb_address_for_volume(root: Path) -> tuple[int, int]:+ """Resolve the selected mounted volume, never the first matching USB VID/PID."""+ if sys.platform == "darwin":+ info = _plist_command(["/usr/sbin/diskutil", "info", "-plist", str(root)])+ mount = info.get("MountPoint")+ if not mount or Path(mount).resolve() != root.resolve():+ raise DeviceWriteError("The selected Dot path is not a mounted volume.")+ disk = info.get("DeviceIdentifier")+ if not disk:+ raise DeviceWriteError("Cannot identify the mounted Dot disk.")+ tree = _plist_command([+ "/usr/sbin/ioreg", "-a", "-l", "-p", "IOService", "-r", "-c", "IOUSBHostDevice",+ ])+ matches = set()++ def visit(node, usb=None):+ if node.get("IOObjectClass") == "IOUSBHostDevice":+ usb = node+ if node.get("BSD Name") == disk and usb is not None:+ if (usb.get("idVendor"), usb.get("idProduct")) == (0x1A86, 0xFE10):+ location, address = usb.get("locationID"), usb.get("USB Address")+ if isinstance(location, int) and isinstance(address, int):+ # libusb's Darwin bus number is the high byte of locationID.+ matches.add((location >> 24, address))+ for child in node.get("IORegistryEntryChildren", []):+ visit(child, usb)++ for node in tree:+ visit(node)+ if len(matches) == 1:+ return matches.pop()+ elif sys.platform.startswith("linux"):+ if not os.path.ismount(root):+ raise DeviceWriteError("The selected Dot path is not a mounted volume.")+ dev = root.stat().st_dev+ node = (Path("/sys/dev/block") / f"{os.major(dev)}:{os.minor(dev)}").resolve()+ for parent in (node, *node.parents):+ if (parent / "idVendor").exists() and (parent / "idProduct").exists():+ vid = int((parent / "idVendor").read_text().strip(), 16)+ pid = int((parent / "idProduct").read_text().strip(), 16)+ if (vid, pid) == (0x1A86, 0xFE10):+ return (int((parent / "busnum").read_text()),+ int((parent / "devnum").read_text()))+ break+ raise DeviceWriteError("Cannot uniquely match the mounted Dot to its USB connection.")diff --git a/src/sidepulse/status_bar.py b/src/sidepulse/status_bar.pyindex 5894399..f804066 100644--- a/src/sidepulse/status_bar.py+++ b/src/sidepulse/status_bar.py@@ -3509,7 +3509,7 @@ class StatusBarController(NSObject):status_path = self.keep_awake.poke_status_file(target)if status_path is not None:read_any = True- log_status_bar(f"sd_keepalive touch={status_path}")+ log_status_bar(f"sd_keepalive read={status_path}")if not read_any and self.keep_awake.last_status_error != self.last_status_read_error:self.last_status_read_error = self.keep_awake.last_status_errorif self.last_status_read_error:diff --git a/src/sidepulse/usb_control.py b/src/sidepulse/usb_control.pynew file mode 100644index 0000000..cfa6a32--- /dev/null+++ b/src/sidepulse/usb_control.py@@ -0,0 +1,153 @@+#!/usr/bin/env python3+"""Dot SPC2 LED control. Never claims, detaches, or resets USB interfaces.++Adapted from sdstatus_bitbang/utils/usb-control/sidepulse_usb_control.py.+"""+import ctypes as C+import ctypes.util+import secrets+import struct+import time++INDEX = 0x5350+STATUS_BYTES = 16+MAX_BYTES = 512+++class UncertainUSBWriteError(RuntimeError):+ """The command may have applied; background writers must not replay it."""+++def decode_status(data):+ if len(data) != STATUS_BYTES or data[:4] != b'SPC2':+ raise ValueError('not a SidePulse USB-control v2 response')+ ident, state, reserved, length, received, applied, polls = struct.unpack_from('<HBBHHHH', data, 4)+ if state > 5 or reserved != 0 or length > MAX_BYTES or received > length:+ raise ValueError('invalid USB-control status')+ return dict(id=ident, state=('IDLE', 'RECEIVING', 'BUSY', 'APPLIED', 'INVALID', 'ABORTED')[state],+ length=length, received=received, applied=applied, polls=polls)+++class Device:+ def __init__(self, *, bus: int, address: int, library=None):+ from libusb_package import find_library++ path = library or find_library('libusb-1.0') or ctypes.util.find_library('usb-1.0')+ if not path:+ raise OSError('libusb is unavailable; reinstall SidePulse with its libusb-package dependency')+ u = self.usb = C.CDLL(path)+ u.libusb_init.argtypes = [C.POINTER(C.c_void_p)]+ u.libusb_exit.argtypes = [C.c_void_p]+ u.libusb_get_device_list.argtypes = [C.c_void_p, C.POINTER(C.POINTER(C.c_void_p))]+ u.libusb_get_device_list.restype = C.c_ssize_t+ u.libusb_free_device_list.argtypes = [C.POINTER(C.c_void_p), C.c_int]+ u.libusb_get_device_descriptor.argtypes = [C.c_void_p, C.c_void_p]+ u.libusb_get_bus_number.argtypes = [C.c_void_p]+ u.libusb_get_bus_number.restype = C.c_uint8+ u.libusb_get_device_address.argtypes = [C.c_void_p]+ u.libusb_get_device_address.restype = C.c_uint8+ u.libusb_open.argtypes = [C.c_void_p, C.POINTER(C.c_void_p)]+ u.libusb_close.argtypes = [C.c_void_p]+ u.libusb_control_transfer.argtypes = [C.c_void_p, C.c_uint8, C.c_uint8,+ C.c_uint16, C.c_uint16, C.c_void_p,+ C.c_uint16, C.c_uint]+ u.libusb_error_name.argtypes = [C.c_int]+ u.libusb_error_name.restype = C.c_char_p+ self.context = C.c_void_p()+ self.handle = C.c_void_p()+ self._check(u.libusb_init(C.byref(self.context)))+ devices = C.POINTER(C.c_void_p)()+ try:+ count = self._check(u.libusb_get_device_list(self.context, C.byref(devices)))+ matches = []+ for i in range(count):+ descriptor = (C.c_ubyte * 18)()+ self._check(u.libusb_get_device_descriptor(devices[i], descriptor))+ # libusb's descriptor contains host-endian integer fields.+ vid = C.c_uint16.from_buffer(descriptor, 8).value+ pid = C.c_uint16.from_buffer(descriptor, 10).value+ if ((vid, pid) == (0x1a86, 0xfe10)+ and u.libusb_get_bus_number(devices[i]) == bus+ and u.libusb_get_device_address(devices[i]) == address):+ matches.append(devices[i])+ if len(matches) != 1:+ raise OSError(f'expected the selected SidePulse Dot at USB {bus}:{address}; found {len(matches)}')+ self._check(u.libusb_open(matches[0], C.byref(self.handle)))+ except BaseException:+ if devices:+ u.libusb_free_device_list(devices, 1)+ devices = None+ self.close()+ raise+ finally:+ if devices:+ u.libusb_free_device_list(devices, 1)++ def _check(self, result):+ if result < 0:+ raise OSError(f'USB: {self.usb.libusb_error_name(result).decode()} ({result})')+ return result++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ self.close()++ def close(self):+ if self.handle:+ self.usb.libusb_close(self.handle)+ self.handle = C.c_void_p()+ if self.context:+ self.usb.libusb_exit(self.context)+ self.context = C.c_void_p()++ def _transfer(self, request_type, request, value, data):+ if not self.handle:+ raise ValueError('USB device is closed')+ buffer = (C.c_ubyte * len(data)).from_buffer_copy(data)+ count = self._check(self.usb.libusb_control_transfer(+ self.handle, request_type, request, value, INDEX, buffer, len(data), 1000))+ if count != len(data):+ raise OSError(f'short USB transfer: {count}/{len(data)}')+ return bytes(buffer)++ def status(self):+ return decode_status(self._transfer(0xc0, 0x51, 0, bytes(STATUS_BYTES)))++ def write(self, text):+ data = text.encode('ascii') if isinstance(text, str) else bytes(text)+ if not 1 <= len(data) <= MAX_BYTES:+ raise ValueError('USB control accepts 1..512 bytes of LED text')+ before = self.status()+ if before['state'] == 'BUSY':+ raise RuntimeError('another LED command is pending')+ ident = secrets.randbelow(65535) + 1+ while ident == before['id']:+ ident = secrets.randbelow(65535) + 1+ # An OUT error can occur after application. Reconcile the same command,+ # but never resubmit it: IDs are acknowledgement tags, not deduplication.+ out_error = None+ try:+ self._transfer(0x40, 0x50, ident, data)+ except OSError as exc:+ out_error = exc+ deadline = time.monotonic() + 2+ while True:+ try:+ status = self.status()+ except (OSError, ValueError) as exc:+ raise UncertainUSBWriteError(+ 'LED command result is uncertain; USB acknowledgement was lost'+ ) from exc+ if status['id'] == ident and status['state'] not in ('BUSY', 'RECEIVING'):+ if (status['state'] != 'APPLIED' or status['length'] != len(data)+ or status['received'] != len(data)+ or status['applied'] != (before['applied'] + 1) % 65536):+ if status['state'] in ('INVALID', 'ABORTED'):+ raise RuntimeError(f'LED command was not applied: {status}')+ raise UncertainUSBWriteError(f'LED command result is uncertain: {status}')+ return status+ if time.monotonic() >= deadline:+ raise UncertainUSBWriteError(f'LED command result is uncertain; no matching acknowledgement: {status}') from out_error+ time.sleep(0.005)diff --git a/tests/fixtures/read2me-vectors.txt b/tests/fixtures/read2me-vectors.txtnew file mode 100644index 0000000..062af6d--- /dev/null+++ b/tests/fixtures/read2me-vectors.txt@@ -0,0 +1,5 @@+# ID=0x01020304, LEDS.LED, total=3, offset=0, payload=ASCII off+packet=0101020304084c4544532e4c4544000000030000000000036f6666999e+symbols=101001020304000100010002000300040008040c040504040503020e040c040504040000000000000003000000000000000000000003060f060606060909090e111104030201+status=52454144324d4531010300000102030400000003000000030000000100000000000000460000000000028400d62a0001e240000026940000001a000000000848+html_status=202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020203c212d2d52454144324d45313a35323435343134343332346434353331303130333030303030313032303330343030303030303033303030303030303330303030303030313030303030303030303030303030343630303030303030303030303238343030643632613030303165323430303030303236393430303030303031613030303030303030303834382d2d3e0a20202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020200adiff --git a/tests/test_read2me.py b/tests/test_read2me.pynew file mode 100644index 0000000..c9ea9c4--- /dev/null+++ b/tests/test_read2me.py@@ -0,0 +1,121 @@+import errno+from pathlib import Path+import struct+import tempfile+import unittest+from unittest.mock import patch, Mock+from types import SimpleNamespace+from sidepulse._vendor.read2me import Channel, crc16, frame, decode_status+from sidepulse._vendor.read2me import START++VECTORS = dict(line.split('=',1) for line in (Path(__file__).parent/'fixtures'/'read2me-vectors.txt').read_text().splitlines() if not line.startswith('#'))++def envelope(raw):+ return b' ' * 256 + b'<!--READ2ME1:' + raw.hex().encode() + b'-->\n' + b' ' * 110 + b'\n'++class FakeChannel(Channel):+ def __init__(self, *, drop_ack=False, bad_crc=False, wrong_target=False, reject=False):+ self.s = decode_status(bytes.fromhex(VECTORS['html_status']))+ self.s.update(transfer_id=0,total=0,received=0,accepted_chunks=0,state='IDLE',symbols=0)+ self.payload = bytearray()+ self.sent = []+ self.drop_ack=drop_ack; self.bad_crc=bad_crc; self.wrong_target=wrong_target;self.reject=reject+ self.stale=None+ def status(self):+ if self.stale is not None:+ stale,self.stale=self.stale,None+ return stale+ return self.s.copy()+ def send_frame(self, symbols):+ self.s['symbols']+=len(symbols);self.s['read_requests']+=len(symbols)+1+ if symbols == [*START,16]: return+ self.sent.append(symbols)+ raw=bytes((a<<4)|b for a,b in zip(symbols[6:-6:2],symbols[7:-6:2]))+ assert crc16(raw[:-2])==int.from_bytes(raw[-2:],'big')+ old=self.s.copy()+ ident=int.from_bytes(raw[1:5],'big');n=raw[5];name=raw[6:6+n]+ total,offset,size=struct.unpack_from('>IIH',raw,6+n)+ data=raw[16+n:-2]+ if offset==len(self.payload):+ self.payload.extend(data);self.s['accepted_chunks']+=1+ else: assert bytes(self.payload[offset:offset+size])==data+ self.s.update(transfer_id=ident,total=total,received=len(self.payload),target=0 if name==b'LEDS.LED' else 1 if name==b'INIT.LED' else 2,+ state='DONE' if len(self.payload)==total else 'RECEIVING',error='NONE',payload_crc16=crc16(self.payload))+ if self.bad_crc:self.s['payload_crc16']^=1+ if self.wrong_target:self.s['target']=2+ if self.reject:self.s.update(state='ERROR',error='APPLY')+ if self.drop_ack:self.stale=old;self.drop_ack=False++class ProtocolTests(unittest.TestCase):+ def test_vectors(self):+ self.assertEqual(crc16(b'123456789'),0x29b1)+ self.assertEqual(bytes(frame(0x01020304,'leds.led',3,0,b'off')).hex(),VECTORS['symbols'])+ s=decode_status(bytes.fromhex(VECTORS['html_status']))+ self.assertEqual((s['transfer_id'],s['payload_crc16'],s['uptime_ms']),(0x01020304,crc16(b'off'),123456))+ def test_invalid_frame(self):+ for args in [(0,'LEDS.LED',3,0,b'off'),(1,'BAD.LED',3,0,b'off'),(1,'INIT.LED',513,0,b'off'),(1,'LEDS.LED',3,2,b'off')]:+ with self.assertRaises(ValueError): frame(*args)+ def test_status_corruption_and_unknown_enum(self):+ for offset in [0,8,9,10,11,32,63]:+ s=bytearray.fromhex(VECTORS['status']);s[offset]=255+ if offset in (9,10,11):s[62:64]=crc16(s[:62]).to_bytes(2,'big')+ with self.assertRaises(ValueError):decode_status(envelope(s))+ for offset in [256, 269, 300, 397]:+ s=bytearray.fromhex(VECTORS['html_status']);s[offset]=255+ with self.assertRaises(ValueError):decode_status(s)+ for s in [b'', bytes.fromhex(VECTORS['status']), bytes.fromhex(VECTORS['html_status'])[:-1]]:+ with self.assertRaises(ValueError):decode_status(s)+ def test_chunking_and_lost_ack_retry(self):+ c=FakeChannel(drop_ack=True)+ s=c.upload(b'abcdef','LEDS.LED',transfer_id=42,chunk_size=3,ack_timeout=0)+ self.assertEqual(s['accepted_chunks'],2)+ self.assertEqual(c.sent[0],c.sent[1])+ self.assertEqual(s['received'],6)+ def test_failed_completion(self):+ for kwargs in ({'bad_crc':True},{'wrong_target':True},{'reject':True}):+ with self.assertRaises(RuntimeError):FakeChannel(**kwargs).upload(b'off','LEDS.LED',ack_timeout=0,retries=0)+ def test_firmware_quiet_before_return_and_final_progress(self):+ c=FakeChannel();events=[]+ with patch('sidepulse._vendor.read2me.time.sleep',side_effect=lambda seconds: events.append(('quiet',seconds))):+ status=c.upload(b'firmware','FIRMWARE.BIN',transfer_id=42,+ progress=lambda n,total: events.append(('progress',n)))+ self.assertEqual(status['state'],'DONE')+ self.assertEqual(events,[('quiet',5),('progress',8)])+ def test_firmware_quiet_even_on_bad_crc_or_uncertain_final_read(self):+ with patch('sidepulse._vendor.read2me.time.sleep') as sleep:+ with self.assertRaises(RuntimeError):+ FakeChannel(bad_crc=True).upload(b'firmware','FIRMWARE.BIN',transfer_id=42)+ sleep.assert_called_once_with(5)+ c=FakeChannel();send=c.send_frame+ def disconnect(symbols):+ send(symbols)+ if c.s['state']=='DONE':raise OSError('disconnected after final frame')+ with patch.object(c,'send_frame',side_effect=disconnect),patch('sidepulse._vendor.read2me.time.sleep') as sleep:+ with self.assertRaises(OSError):c.upload(b'firmware','FIRMWARE.BIN',transfer_id=42)+ sleep.assert_called_once_with(5)+ def test_led_completion_has_no_reboot_wait(self):+ with patch('sidepulse._vendor.read2me.time.sleep') as sleep:+ FakeChannel().upload(b'off','LEDS.LED',transfer_id=42)+ sleep.assert_not_called()+ def test_cache_invalidation_failure_never_reads_a_symbol(self):+ c=Channel.__new__(Channel)+ c.fd=12;c._cache_mapping=4096+ c.libc=SimpleNamespace(msync=Mock(return_value=-1))+ c.read_at=Mock()+ with patch('sidepulse._vendor.read2me.ctypes.get_errno',return_value=errno.EIO):+ with self.assertRaises(OSError):c.read(18)+ c.read_at.assert_not_called()+ c.fd=-1+ with self.assertRaises(ValueError):c.read(18)+ c.libc.msync.assert_called_once()+ def test_invalid_inputs_before_probe(self):+ c=FakeChannel()+ with self.assertRaises(ValueError):c.upload(b'off','LEDS.LED',transfer_id=0)+ self.assertEqual(c.s['symbols'],0)+ def test_probe_rejects_extra_and_stale_symbols(self):+ c=FakeChannel()+ before=c.status();after=before.copy();after['symbols']+=8+ with patch.object(c,'status',side_effect=[before,after]):+ with self.assertRaises(RuntimeError):c.probe()+ with patch.object(c,'status',return_value=before),patch('sidepulse._vendor.read2me.time.monotonic',side_effect=[0,2]):+ with self.assertRaises(RuntimeError):c.probe()diff --git a/tests/test_readonly_control.py b/tests/test_readonly_control.pynew file mode 100644index 0000000..bb73eba--- /dev/null+++ b/tests/test_readonly_control.py@@ -0,0 +1,328 @@+"""Read-only transport routing and SPC2 safety, without hardware I/O."""+import errno+import os+import subprocess+from pathlib import Path+import threading+from unittest.mock import Mock, patch++import pytest++from sidepulse import device_writer as writer+from sidepulse import readonly_control as readonly+from sidepulse import usb_control as usb+from sidepulse import keep_awake+++def volume(tmp_path):+ (tmp_path / "LEDS.LED").write_text("off")+ (tmp_path / "STATUS.TXT").write_text("release_version 1.1.0\nfirmware_version 1.1.0\nserial SPP-000002\n")+ return tmp_path++[email protected]("error", [errno.EROFS, errno.EACCES, errno.EPERM])+def test_denied_open_uses_fallback(volume, error):+ with patch.object(Path, "open", side_effect=OSError(error, "denied")), patch.object(+ readonly, "write_readonly_program"+ ) as fallback:+ writer.write_text_synced(volume / "LEDS.LED", "off")+ fallback.assert_called_once_with(volume / "LEDS.LED", "off")++[email protected]("error", [errno.EIO, errno.ENOENT, errno.ENOSPC])+def test_other_open_errors_do_not_fallback(volume, error):+ with patch.object(Path, "open", side_effect=OSError(error, "failed")), patch.object(+ readonly, "write_readonly_program"+ ) as fallback, pytest.raises(OSError):+ writer.write_text_synced(volume / "LEDS.LED", "off")+ fallback.assert_not_called()++[email protected]("operation", ["write", "flush", "__exit__"])+def test_never_replays_after_open(volume, operation):+ with patch.object(Path, "open") as opened, patch.object(readonly, "write_readonly_program") as fallback:+ handle = opened.return_value+ handle.__enter__.return_value = handle+ getattr(handle, operation).side_effect = OSError(errno.EROFS, "failed after open")+ handle.fileno.return_value = -1+ with pytest.raises(OSError):+ writer.write_text_synced(volume / "LEDS.LED", "off")+ fallback.assert_not_called()+++def test_writable_and_dry_run_do_not_probe(volume):+ with patch.object(readonly, "read_device_info") as probe:+ target = writer.write_led_program("#ff0000", device_path=volume)+ assert target.read_text() == "#ff0000"+ writer.write_led_program("off", device_path=volume, dry_run=True)+ probe.assert_not_called()++[email protected]("model,field,extra", [+ ("Dot", "app_version", ""), ("Pro", "release_version", "firmware_version 1.1.0\n"),+])[email protected]("version,supported", [+ ("1.0.5", False), ("1.0.5-read2me.13", False), ("1.1.0-rc.1", False),+ ("1.1", True), ("1.1.0", True), ("1.10.0", True), ("2.0.0", True),+ ("v1.1.1+build", True), ("unknown", False), ("", False),+])+def test_firmware_gate(volume, model, field, extra, version, supported):+ (volume / "STATUS.TXT").write_text(f"{field} {version}\n{extra}")+ with patch.object(readonly.sys, "platform", "linux"):+ if supported:+ assert readonly.read_device_info(volume) == (model, version)+ else:+ with pytest.raises(writer.DeviceWriteError):+ readonly.read_device_info(volume)+++def test_unknown_and_old_firmware_never_open_a_transport(volume):+ with patch.object(readonly.sys, "platform", "linux"), patch(+ "sidepulse._vendor.read2me.Channel"+ ) as channel, patch.object(usb, "Device") as device:+ for status in ("", "app_version 1.0.5\n", "release_version 1.0.5\nfirmware_version 1.0.5\n"):+ (volume / "STATUS.TXT").write_text(status)+ with pytest.raises(writer.DeviceWriteError):+ readonly.write_readonly_program(volume / "LEDS.LED", "off")+ channel.assert_not_called()+ device.assert_not_called()+++def test_pro_upload_and_errors(volume):+ with patch.object(readonly, "read_device_info", return_value=("Pro", "1.1.0")), patch(+ "sidepulse._vendor.read2me.Channel"+ ) as factory:+ channel = factory.return_value.__enter__.return_value+ readonly.write_readonly_program(volume / "LEDS.LED", "off")+ factory.assert_called_once_with(volume / "setup.html")+ channel.upload.assert_called_once_with(b"off", "LEDS.LED")+ channel.upload.side_effect = RuntimeError("received payload checksum differs")+ with pytest.raises(writer.DeviceWriteError, match="checksum"):+ readonly.write_readonly_program(volume / "LEDS.LED", "off")+++def test_dot_uses_mounted_device_address(volume):+ with patch.object(readonly, "read_device_info", return_value=("Dot", "1.1.0")), patch.object(+ readonly, "usb_address_for_volume", return_value=(2, 9)+ ) as address, patch.object(usb, "Device") as factory:+ readonly.write_readonly_program(volume / "LEDS.LED", "off")+ address.assert_called_once_with(volume)+ factory.assert_called_once_with(bus=2, address=9)+ factory.return_value.__enter__.return_value.write.assert_called_once_with(b"off")+++def test_custom_filename_refused(volume):+ with patch.object(readonly, "read_device_info") as probe, pytest.raises(writer.DeviceWriteError):+ readonly.write_readonly_program(volume / "custom.led", "off")+ probe.assert_not_called()+++def usb_tree(disk, bus, address, vid=0x1A86):+ return {"IOObjectClass": "IOUSBHostDevice", "idVendor": vid, "idProduct": 0xFE10,+ "locationID": bus << 24, "USB Address": address,+ "IORegistryEntryChildren": [{"IORegistryEntryChildren": [{"BSD Name": disk}]}]}+++def test_mac_mount_matching_with_multiple_devices(volume):+ tree = [usb_tree("disk2", 1, 2), usb_tree("disk3", 2, 2), usb_tree("disk4", 3, 2, vid=123)]+ info = {"MountPoint": str(volume), "DeviceIdentifier": "disk3"}+ with patch.object(readonly.sys, "platform", "darwin"), patch.object(+ readonly, "_plist_command", side_effect=[info, tree]+ ) as commands:+ assert readonly.usb_address_for_volume(volume) == (2, 2)+ assert "-l" in commands.call_args.args[0]++[email protected]("tree", [[], [usb_tree("disk3", 2, 2, vid=123)],+ [usb_tree("disk3", 1, 2), usb_tree("disk3", 2, 2)]])+def test_mac_missing_wrong_or_ambiguous_device_is_refused(volume, tree):+ info = {"MountPoint": str(volume), "DeviceIdentifier": "disk3"}+ with patch.object(readonly.sys, "platform", "darwin"), patch.object(+ readonly, "_plist_command", side_effect=[info, tree]+ ), pytest.raises(writer.DeviceWriteError):+ readonly.usb_address_for_volume(volume)+++def test_linux_mount_maps_through_sysfs(volume):+ sysroot = volume / "sys"+ usbroot = sysroot / "usb-device"+ block = usbroot / "storage" / "block" / "sdc" / "sdc1"+ block.mkdir(parents=True)+ (usbroot / "idVendor").write_text("1a86")+ (usbroot / "idProduct").write_text("fe10")+ (usbroot / "busnum").write_text("3")+ (usbroot / "devnum").write_text("7")+ device = volume.stat().st_dev+ (sysroot / f"{os.major(device)}:{os.minor(device)}").symlink_to(block)+ with patch.object(readonly.sys, "platform", "linux"), patch.object(+ readonly.os.path, "ismount", return_value=True+ ), patch.object(readonly, "Path", side_effect=lambda value: sysroot if value == "/sys/dev/block" else Path(value)):+ assert readonly.usb_address_for_volume(volume) == (3, 7)+ (usbroot / "idVendor").write_text("ffff")+ with pytest.raises(writer.DeviceWriteError):+ readonly.usb_address_for_volume(volume)+++def test_pro_unsupported_platform_is_reported(volume):+ with patch.object(readonly.sys, "platform", "linux"), pytest.raises(+ writer.DeviceWriteError, match="macOS only"+ ):+ readonly.write_readonly_program(volume / "LEDS.LED", "off")+++def status(ident=0, state="IDLE", length=0, received=0, applied=0):+ return dict(id=ident, state=state, length=length, received=received, applied=applied, polls=1)+++def fake_usb(*states, out_error=None):+ device = usb.Device.__new__(usb.Device)+ device.status = Mock(side_effect=states)+ device._transfer = Mock(side_effect=out_error)+ return device+++def test_spc2_vector_and_malformed_status():+ data = bytes.fromhex("53 50 43 32 34 12 03 00 03 00 03 00 01 00 02 00")+ assert usb.decode_status(data) == dict(id=0x1234, state="APPLIED", length=3, received=3, applied=1, polls=2)+ for value in (b"", data[:-1], b"SPC1" + data[4:]):+ with pytest.raises(ValueError):+ usb.decode_status(value)+ for offset, value in ((6, 6), (7, 1), (9, 3), (10, 4)):+ bad = bytearray(data)+ bad[offset] = value+ with pytest.raises(ValueError):+ usb.decode_status(bad)+++def test_usb_one_transfer_and_counter_wrap():+ device = fake_usb(status(applied=65535), status(42, "BUSY", 512, 512, 65535),+ status(42, "APPLIED", 512, 512, 0))+ with patch.object(usb.secrets, "randbelow", return_value=41):+ result = device.write(b"x" * 512)+ assert result["state"] == "APPLIED"+ device._transfer.assert_called_once_with(0x40, 0x50, 42, b"x" * 512)++[email protected]("state", [status(42, "INVALID", 3, 3), status(42, "ABORTED", 3, 2),+ status(42, "APPLIED", 3, 2, 1), status(42, "APPLIED", 4, 4, 1), status(42, "APPLIED", 3, 3, 2)])+def test_usb_requires_complete_matching_acknowledgement(state):+ device = fake_usb(status(), state)+ with patch.object(usb.secrets, "randbelow", return_value=41), pytest.raises(RuntimeError):+ device.write(b"off")+ assert device._transfer.call_count == 1+++def test_usb_busy_does_not_submit():+ device = fake_usb(status(state="BUSY"))+ with pytest.raises(RuntimeError, match="pending"):+ device.write("off")+ device._transfer.assert_not_called()+++def test_usb_reconciles_ambiguous_out_without_resubmission():+ device = fake_usb(status(), status(42, "APPLIED", 3, 3, 1), out_error=OSError("timeout"))+ with patch.object(usb.secrets, "randbelow", return_value=41):+ assert device.write("off")["state"] == "APPLIED"+ assert device._transfer.call_count == 1+++def test_usb_missing_acknowledgement_is_uncertain_not_retried():+ device = fake_usb(status(), status(99, "APPLIED", 3, 3, 1))+ with patch.object(usb.secrets, "randbelow", return_value=41), patch.object(+ usb.time, "monotonic", side_effect=[0, 3]+ ), pytest.raises(usb.UncertainUSBWriteError, match="uncertain"):+ device.write("off")+ assert device._transfer.call_count == 1+++def test_usb_disconnect_after_write_is_uncertain():+ device = fake_usb(status(), OSError("disconnected"))+ with pytest.raises(RuntimeError, match="uncertain"):+ device.write("off")+ assert device._transfer.call_count == 1+++def test_background_tick_does_not_replay_uncertain_usb_command(volume):+ with patch.object(readonly, "read_device_info", return_value=("Dot", "1.1.0")), patch.object(+ readonly, "usb_address_for_volume", return_value=(2, 9)+ ), patch.object(usb, "Device") as factory:+ device = factory.return_value.__enter__.return_value+ device.write.side_effect = usb.UncertainUSBWriteError("lost acknowledgement")+ with pytest.raises(writer.DeviceWriteError, match="lost acknowledgement"):+ readonly.write_readonly_program(volume / "LEDS.LED", "off")+ with pytest.raises(writer.DeviceWriteError, match="automatic replay stopped"):+ readonly.write_readonly_program(volume / "LEDS.LED", "off")+ assert device.write.call_count == 1+ device.write.side_effect = None+ readonly.write_readonly_program(volume / "LEDS.LED", "#ff0000")+ assert device.write.call_count == 2+++def test_writer_serializes_threads(volume):+ entered = threading.Event()+ release = threading.Event()+ calls = []++ def write(target, program):+ calls.append(program)+ if program == "off":+ entered.set()+ assert release.wait(3)++ with patch.object(writer, "write_text_synced", side_effect=write):+ a = threading.Thread(target=writer.write_led_program, args=("off",), kwargs={"device_path": volume})+ b = threading.Thread(target=writer.write_led_program, args=("#ff0000",), kwargs={"device_path": volume})+ a.start()+ assert entered.wait(3)+ b.start()+ try:+ assert calls == ["off"]+ finally:+ release.set()+ a.join(3)+ b.join(3)+ assert calls == ["off", "#ff0000"]+++def test_readonly_keepalive_reads_status(volume):+ with patch.object(keep_awake.subprocess, "run") as run, patch.object(+ readonly, "read_status_bytes"+ ) as read:+ controller = keep_awake.KeepAwakeController(status_read_async=False)+ assert controller.poke_status_file(volume / "LEDS.LED", now=0) == volume / "STATUS.TXT"+ read.assert_called_once_with(volume / "STATUS.TXT")+ run.assert_not_called()+++def test_keepalive_reads_status_without_firmware_validation(volume):+ (volume / "STATUS.TXT").write_text("legacy status\n")+ with patch.object(readonly.sys, "platform", "linux"):+ keep_awake.read_status_file(volume / "STATUS.TXT")+ assert not (volume / "keepalive").exists()+++def test_keepalive_uses_uncached_mac_reader(volume):+ from sidepulse._vendor import read2me++ with patch.object(readonly.sys, "platform", "darwin"), patch.object(+ read2me, "_MacFile"+ ) as reader:+ reader.return_value.__enter__.return_value.read_at.return_value = b"status"+ keep_awake.read_status_file(volume / "STATUS.TXT")+ reader.assert_called_once_with(volume / "STATUS.TXT")+ reader.return_value.__enter__.return_value.invalidate_cache.assert_called_once_with()+ reader.return_value.__enter__.return_value.read_at.assert_called_once_with(0)+++def test_keepalive_cache_invalidation_failure_prevents_read(volume):+ from sidepulse._vendor import read2me++ with patch.object(readonly.sys, "platform", "darwin"), patch.object(+ read2me, "_MacFile"+ ) as reader:+ stream = reader.return_value.__enter__.return_value+ stream.invalidate_cache.side_effect = OSError("invalidation failed")+ with pytest.raises(OSError, match="invalidation failed"):+ keep_awake.read_status_file(volume / "STATUS.TXT")+ stream.read_at.assert_not_called()diff --git a/tests/test_sidepulse.py b/tests/test_sidepulse.pyindex 26c047a..9d407a1 100644--- a/tests/test_sidepulse.py+++ b/tests/test_sidepulse.py@@ -4994,11 +4994,11 @@ class AgentMonitorTests(unittest.TestCase):self.assertEqual(len(processes), 1)self.assertTrue(processes[0].terminated)- def test_keep_awake_touches_keepalive_file_once_per_interval(self) -> None:+ def test_keep_awake_reads_status_file_once_per_interval(self) -> None:with tempfile.TemporaryDirectory() as tmp:device = Path(tmp) / "SidePulsePro"device.mkdir()- status_path = device / "keepalive"+ status_path = device / "STATUS.TXT"reads: list[Path] = []controller = KeepAwakeController(