From f338c84c9c8bf86a5a4f109c5f76337aeef3cdeb Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 14:25:23 -0700 Subject: [PATCH 01/34] fix(capture): assemble every chunk of a remote capture (NEH-241) remote_capture_get_data ran a single transaction and threw the response parameters away, so any still that CHDK split across more than one chunk came back truncated with no error to show for it. CHDK's PTP_CHDK_RemoteCaptureGetData handler in core/ptp.c reports the chunk size in param1, a "more chunks follow" flag in param2, and the file position to write at in param3, where -1 means append. PTP parameters are unsigned, so that -1 reaches us as 0xFFFFFFFF and has to be folded back before it is used as an offset. remote_capture_get_chunk now does one transaction and returns the chunk with those three facts decoded; remote_capture_get_data loops it and assembles the image, seeking where the camera asks and appending where it does not. The name, argument and return type are unchanged, so _shoot_streaming needs no change. A chunk ceiling keeps a camera that never clears the flag from spinning forever. --- src/pychdk/chdk.py | 85 +++++++++++++++++++++++++++++++++++++++++++--- tests/test_chdk.py | 82 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 162 insertions(+), 5 deletions(-) diff --git a/src/pychdk/chdk.py b/src/pychdk/chdk.py index dfd4377..e0f7c28 100644 --- a/src/pychdk/chdk.py +++ b/src/pychdk/chdk.py @@ -62,10 +62,32 @@ class ScriptFlag(IntEnum): REMOTE_CAP_RAW = 0x02 REMOTE_CAP_DNG_HDR = 0x04 +# A full-resolution still needs a few hundred chunks at most; this only +# exists so a camera that never clears the "more" flag cannot hang us. +MAX_CAPTURE_CHUNKS = 10000 + ScriptMessage = namedtuple("ScriptMessage", ["msg_type", "data_type", "script_id", "value"]) +def _as_signed32(value): + """Reinterpret a PTP uint32 parameter as a signed 32-bit integer. + + PTP parameters are unsigned, so CHDK's -1 sentinels arrive as + 0xFFFFFFFF and have to be folded back before they are used. + + Args: + value: Parameter value as received (unsigned). + + Returns: + Integer in the range -2**31 .. 2**31 - 1. + """ + value &= 0xFFFFFFFF + if value >= 0x80000000: + return value - 0x100000000 + return value + + def _decode_script_value(data_type, data): """Decode a script value from raw bytes given its type.""" if data_type == ScriptDataType.NIL: @@ -242,21 +264,74 @@ def remote_capture_is_ready(self): return False, 0 return True, params[0] - def remote_capture_get_data(self, format_flag): - """Download remote capture image data. + def remote_capture_get_chunk(self, format_flag): + """Fetch one chunk of a remote capture. + + CHDK's PTP_CHDK_RemoteCaptureGetData handler (core/ptp.c) + answers one chunk per transaction and describes it in the + response parameters: + + * param1 — the chunk's size in bytes; + * param2 — 1 while further chunks follow, 0 on the last one; + * param3 — the file position to seek to before writing this + chunk, or -1 to append. Parameters are unsigned, so -1 + arrives as 0xFFFFFFFF and is folded back here. + + A camera that sends fewer parameters is read as a single + appended chunk the size of the data phase. Args: format_flag: Which format to download (JPEG=1, RAW=2, DNG_HDR=4). Returns: - Image data as bytes. + Tuple of (chunk_bytes, more, position), where more is a bool + and position is a sign-corrected int (-1 means append). """ - _, data = self._session.transaction( + params, data = self._session.transaction( OperationCode.CHDK, params=[ChdkCommand.REMOTE_CAPTURE_GET_DATA, format_flag], receive_data=True, ) - return data + params = params or [] + size = params[0] if len(params) > 0 else len(data) + more = bool(params[1]) if len(params) > 1 else False + position = _as_signed32(params[2]) if len(params) > 2 else -1 + # Trust the data phase when the camera claims more than it sent. + if 0 <= size < len(data): + data = data[:size] + return data, more, position + + def remote_capture_get_data(self, format_flag): + """Download remote capture image data. + + Loops over remote_capture_get_chunk until the camera clears its + "more" flag, placing each chunk at the position CHDK asks for. + A still larger than one chunk used to come back truncated. + + Args: + format_flag: Which format to download (JPEG=1, RAW=2, DNG_HDR=4). + + Returns: + Image data as bytes. + + Raises: + RuntimeError: If the camera never clears its "more" flag. + """ + image = bytearray() + for _ in range(MAX_CAPTURE_CHUNKS): + chunk, more, position = self.remote_capture_get_chunk(format_flag) + if position >= 0: + end = position + len(chunk) + if len(image) < end: + image.extend(bytes(end - len(image))) + image[position:end] = chunk + else: + image.extend(chunk) + if not more: + return bytes(image) + raise RuntimeError( + f"Remote capture did not end after {MAX_CAPTURE_CHUNKS} chunks" + ) def wait_for_script(self, timeout=30.0): """Wait until no script is running on the camera.""" diff --git a/tests/test_chdk.py b/tests/test_chdk.py index b7b932e..2b0dca4 100644 --- a/tests/test_chdk.py +++ b/tests/test_chdk.py @@ -93,3 +93,85 @@ def test_nil(self): def test_string(self): assert _decode_script_value(ScriptDataType.STRING, b"hello") == "hello" + + +class TestRemoteCaptureGetData: + """Chunk assembly for PTP_CHDK_RemoteCaptureGetData.""" + + def _make_chdk(self): + mock_session = MagicMock() + return ChdkPTP(mock_session), mock_session + + def test_two_chunks_are_joined_in_order(self): + chdk, session = self._make_chdk() + # [size, more, position]; position -1 means "append". + session.transaction.side_effect = [ + ([4, 1, 0xFFFFFFFF], b"AAAA"), + ([4, 0, 0xFFFFFFFF], b"BBBB"), + ] + assert chdk.remote_capture_get_data(1) == b"AAAABBBB" + assert session.transaction.call_count == 2 + + def test_explicit_position_places_a_late_chunk_first(self): + chdk, session = self._make_chdk() + # Chunk B arrives first but belongs at offset 8. + session.transaction.side_effect = [ + ([4, 1, 8], b"BBBB"), + ([8, 0, 0], b"AAAAAAAA"), + ] + assert chdk.remote_capture_get_data(1) == b"AAAAAAAABBBB" + + def test_position_ffffffff_appends_instead_of_seeking(self): + chdk, session = self._make_chdk() + session.transaction.side_effect = [ + ([2, 1, 0xFFFFFFFF], b"hi"), + ([5, 0, 0xFFFFFFFF], b"there"), + ] + assert chdk.remote_capture_get_data(1) == b"hithere" + + def test_single_chunk_capture_is_returned_unchanged(self): + chdk, session = self._make_chdk() + session.transaction.side_effect = [ + ([5, 0, 0xFFFFFFFF], b"\xff\xd8\xff\xe0\x00"), + ] + assert chdk.remote_capture_get_data(1) == b"\xff\xd8\xff\xe0\x00" + + def test_camera_that_never_clears_more_raises(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ([1, 1, 0xFFFFFFFF], b"x") + with pytest.raises(RuntimeError, match="10000"): + chdk.remote_capture_get_data(1) + + +class TestRemoteCaptureGetChunk: + def _make_chdk(self): + mock_session = MagicMock() + return ChdkPTP(mock_session), mock_session + + def test_reports_size_more_and_position(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ([3, 1, 16], b"abc") + chunk, more, position = chdk.remote_capture_get_chunk(1) + assert chunk == b"abc" + assert more is True + assert position == 16 + + def test_short_params_mean_one_appended_chunk(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ([], b"abc") + chunk, more, position = chdk.remote_capture_get_chunk(1) + assert chunk == b"abc" + assert more is False + assert position == -1 + + def test_size_smaller_than_the_data_phase_truncates(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ([2, 0, 0xFFFFFFFF], b"abcd\x00\x00") + chunk, _, _ = chdk.remote_capture_get_chunk(1) + assert chunk == b"ab" + + def test_size_larger_than_the_data_phase_keeps_what_arrived(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ([64, 0, 0xFFFFFFFF], b"abcd") + chunk, _, _ = chdk.remote_capture_get_chunk(1) + assert chunk == b"abcd" From 901efc059bfd98d773d42ad9ee333fdac984e9d9 Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 14:27:35 -0700 Subject: [PATCH 02/34] fix(device): install the signal handlers only on the main thread (NEH-242) device.py called signal.signal at import time, and Python raises ValueError: signal only works in main thread of the main interpreter anywhere but the main thread. That made `import pychdk` fail outright for any host whose first import happens on a worker thread, which is exactly what a synchronous FastAPI route does. The two calls move into install_signal_handlers(), which declines off the main thread and also catches the ValueError for embeddings that refuse even on it. The import still calls it and ignores the result, so the common case is unchanged; a host that imported from a worker can call it from its main thread later, which is why it is exported. The originals are captured only when the current handlers are not already ours, so installing twice cannot save _signal_handler as its own predecessor and recurse. atexit stays unconditional; it is thread-safe. --- src/pychdk/__init__.py | 9 +++-- src/pychdk/device.py | 42 ++++++++++++++++++++--- tests/test_device.py | 75 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 120 insertions(+), 6 deletions(-) diff --git a/src/pychdk/__init__.py b/src/pychdk/__init__.py index fb483f3..d68a747 100644 --- a/src/pychdk/__init__.py +++ b/src/pychdk/__init__.py @@ -1,13 +1,18 @@ """Pure Python CHDK PTP camera control.""" __version__ = "0.1.0" -from pychdk.device import ChdkDevice, list_devices, DeviceInfo +from pychdk.device import ( + ChdkDevice, + list_devices, + DeviceInfo, + install_signal_handlers, +) from pychdk.ptp import PTPError from pychdk.chdk import ChdkPTP from pychdk.multicam import MultiCam from pychdk import util __all__ = [ - "ChdkDevice", "list_devices", "DeviceInfo", + "ChdkDevice", "list_devices", "DeviceInfo", "install_signal_handlers", "PTPError", "ChdkPTP", "MultiCam", "util", ] diff --git a/src/pychdk/device.py b/src/pychdk/device.py index 1858154..25cd693 100644 --- a/src/pychdk/device.py +++ b/src/pychdk/device.py @@ -5,6 +5,7 @@ """ import atexit import signal +import threading import time import weakref from collections import namedtuple @@ -90,11 +91,44 @@ def _signal_handler(signum, frame): signal.raise_signal(signum) +def install_signal_handlers(): + """Install the SIGINT/SIGTERM handlers that close open cameras. + + Python only allows handlers to be installed from the main thread of + the main interpreter, so this declines anywhere else instead of + raising: a host that first imports pychdk inside a worker thread — + a synchronous FastAPI route, say — would otherwise fail on the + import. Such a host can call this later from its main thread to get + the handlers after all. Installing twice is harmless; the originals + are captured once. + + Returns: + True if our handlers are in place, False if it declined. + """ + global _original_sigint, _original_sigterm + if threading.current_thread() is not threading.main_thread(): + return False + current_sigint = signal.getsignal(signal.SIGINT) + current_sigterm = signal.getsignal(signal.SIGTERM) + if current_sigint is _signal_handler and current_sigterm is _signal_handler: + return True + # Never save our own handler as the original: that would recurse. + if current_sigint is not _signal_handler: + _original_sigint = current_sigint + if current_sigterm is not _signal_handler: + _original_sigterm = current_sigterm + try: + signal.signal(signal.SIGINT, _signal_handler) + signal.signal(signal.SIGTERM, _signal_handler) + except ValueError: + # Some embeddings refuse even on the main thread. + return False + return True + + +# atexit is thread-safe, so it is registered unconditionally. atexit.register(_cleanup_all) -_original_sigint = signal.getsignal(signal.SIGINT) -_original_sigterm = signal.getsignal(signal.SIGTERM) -signal.signal(signal.SIGINT, _signal_handler) -signal.signal(signal.SIGTERM, _signal_handler) +install_signal_handlers() class ChdkDevice: diff --git a/tests/test_device.py b/tests/test_device.py index 7131373..ed9f6b2 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -1,6 +1,12 @@ """Tests for high-level ChdkDevice API.""" +import importlib +import signal +import sys +import threading from unittest.mock import MagicMock, patch import pytest +import pychdk +from pychdk import device from pychdk.device import ChdkDevice, list_devices, DeviceInfo @@ -73,3 +79,72 @@ def test_close(self): dev, mock_chdk = self._make_device() dev.close() assert not dev.is_connected + + +class TestSignalHandlers: + """Signal handlers may only be installed from the main thread.""" + + def test_importing_from_a_worker_thread_does_not_raise(self): + saved_module = sys.modules.pop("pychdk.device", None) + failures = [] + + def reimport(): + try: + importlib.import_module("pychdk.device") + except BaseException as exc: + failures.append(exc) + + try: + thread = threading.Thread(target=reimport) + thread.start() + thread.join() + finally: + if saved_module is not None: + sys.modules["pychdk.device"] = saved_module + pychdk.device = saved_module + assert failures == [] + + def test_declines_on_a_worker_thread(self): + before = ( + signal.getsignal(signal.SIGINT), + signal.getsignal(signal.SIGTERM), + ) + results = [] + + def install(): + results.append(device.install_signal_handlers()) + + thread = threading.Thread(target=install) + thread.start() + thread.join() + assert results == [False] + assert signal.getsignal(signal.SIGINT) is before[0] + assert signal.getsignal(signal.SIGTERM) is before[1] + + def test_installing_twice_keeps_the_first_saved_originals(self): + saved_handlers = ( + signal.getsignal(signal.SIGINT), + signal.getsignal(signal.SIGTERM), + ) + saved_originals = (device._original_sigint, device._original_sigterm) + + def sentinel_sigint(signum, frame): + pass + + def sentinel_sigterm(signum, frame): + pass + + try: + signal.signal(signal.SIGINT, sentinel_sigint) + signal.signal(signal.SIGTERM, sentinel_sigterm) + assert device.install_signal_handlers() is True + assert device.install_signal_handlers() is True + assert signal.getsignal(signal.SIGINT) is device._signal_handler + assert signal.getsignal(signal.SIGTERM) is device._signal_handler + assert device._original_sigint is sentinel_sigint + assert device._original_sigterm is sentinel_sigterm + finally: + signal.signal(signal.SIGINT, saved_handlers[0]) + signal.signal(signal.SIGTERM, saved_handlers[1]) + device._original_sigint = saved_originals[0] + device._original_sigterm = saved_originals[1] From d600af67224fca0ee14a0519f23ee1f16148c273 Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 14:30:18 -0700 Subject: [PATCH 03/34] feat(own-txt): carry a camera id beside the page parity (NEH-243) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OWN.TXT records a body's page parity — which pages it shoots — not a side of the table; which parity ends up on the left is the operator's reading direction and no business of the file's. The wording everywhere said left and right, so fix that first. The toolkit's CHDK backend also needs a stable identity per body, and pyusb cannot always read a serial from a Canon compact: list_devices hands back serial_num=None often enough that we cannot key on it. So the file gains a second line, id=, minted when a card is flashed. parse_own_txt and format_own_txt own the format. Parsing is deliberately forgiving — CRLF, a BOM, stray whitespace, blank and unknown lines, lowercase keywords — and never raises, because a card that has been through a Windows editor should still read as the camera it is. The flasher keeps an id already on the card rather than minting a new one, so re-flashing does not silently turn a body into a different camera, and it says which it did. --- README.md | 4 +-- src/pychdk/__init__.py | 2 ++ src/pychdk/util.py | 62 ++++++++++++++++++++++++++++++++++++ tests/test_util.py | 71 ++++++++++++++++++++++++++++++++++++++++++ tools/flash_chdk.py | 29 ++++++++++++++--- 5 files changed, 162 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 4eca8bd..ae385e7 100644 --- a/README.md +++ b/README.md @@ -87,9 +87,9 @@ pyusb / libusb — raw USB access ## Camera side assignment -For book scanning with two cameras, each camera is identified as "odd" or "even" (left/right pages). This is stored in a file called `OWN.TXT` on the camera's SD card containing either `ODD` or `EVEN`. The Captua workflow reads this via `download_file('OWN.TXT')` to determine page sequencing and EXIF orientation. +For book scanning with two cameras, each body is assigned a page parity — which pages it shoots — stored in a file called `OWN.TXT` on the camera's SD card. The first line is `ODD` or `EVEN`; which of the two sits on the left is the operator's reading direction, and the file says nothing about it. A second line, `id=3f9a1c2b7d4e`, gives the body a stable identity, because pyusb cannot always read a serial number from a Canon compact. The Captua workflow reads the file via `download_file('A/OWN.TXT')` to determine page sequencing and EXIF orientation, and to tell one body from the other across replugs. Note the `A/` prefix: `download_file` and `upload_file` both take a card path. -The `tools/flash_chdk.py` script writes this file during SD card preparation. +The `tools/flash_chdk.py` script writes both lines during SD card preparation, keeping any id the card already carries. `parse_own_txt` and `format_own_txt` in `util.py` read and write the format. ## Tools diff --git a/src/pychdk/__init__.py b/src/pychdk/__init__.py index d68a747..f33153f 100644 --- a/src/pychdk/__init__.py +++ b/src/pychdk/__init__.py @@ -11,8 +11,10 @@ from pychdk.chdk import ChdkPTP from pychdk.multicam import MultiCam from pychdk import util +from pychdk.util import parse_own_txt, format_own_txt __all__ = [ "ChdkDevice", "list_devices", "DeviceInfo", "install_signal_handlers", "PTPError", "ChdkPTP", "MultiCam", "util", + "parse_own_txt", "format_own_txt", ] diff --git a/src/pychdk/util.py b/src/pychdk/util.py index 766dfe6..94ec70b 100644 --- a/src/pychdk/util.py +++ b/src/pychdk/util.py @@ -62,3 +62,65 @@ def to_camerapath(path): if path.startswith("A/") or path.startswith("A\\"): return path return "A/" + path + + +def parse_own_txt(data): + """Read a camera's page parity and id from OWN.TXT. + + OWN.TXT records which pages a body shoots — ODD or EVEN — not which + side of the table it stands on; which parity appears on the left is + the operator's reading direction, and the file says nothing about + it. A second line, 'id=', carries a stable identity for the + body, because pyusb cannot always read a serial number from a Canon + compact. + + Tolerates CRLF, a byte order mark, surrounding whitespace, blank + lines, lowercase keywords, a missing id line and unknown lines. It + never raises: rubbish simply parses as nothing. + + Args: + data: File contents as bytes or str. + + Returns: + Tuple of (side, camera_id), where side is 'ODD', 'EVEN' or None + and camera_id is the id line's value or None. + """ + if isinstance(data, (bytes, bytearray)): + text = bytes(data).decode("utf-8-sig", errors="replace") + elif isinstance(data, str): + text = data + else: + return None, None + + side = None + camera_id = None + for line in text.splitlines(): + line = line.replace("\ufeff", "").strip() + if not line: + continue + if side is None and line.upper() in ("ODD", "EVEN"): + side = line.upper() + elif camera_id is None and line.upper().startswith("ID="): + value = line.split("=", 1)[1].strip() + if value: + camera_id = value + return side, camera_id + + +def format_own_txt(side, camera_id=None): + """Render the canonical OWN.TXT for a page parity and camera id. + + The parity is which pages the body shoots, ODD or EVEN, not a side + of the table. The id line is written only when an id is given. + + Args: + side: 'ODD' or 'EVEN', in any case. + camera_id: Stable hex identity for the body, or None. + + Returns: + File contents as a str, with a single trailing newline. + """ + lines = [str(side).strip().upper()] + if camera_id: + lines.append("id=" + str(camera_id).strip()) + return "\n".join(lines) + "\n" diff --git a/tests/test_util.py b/tests/test_util.py index 40a58b8..e26e149 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -5,6 +5,8 @@ iso_to_sv96, aperture_to_av96, to_camerapath, + parse_own_txt, + format_own_txt, ) @@ -48,3 +50,72 @@ def test_already_prefixed(self): def test_own_txt(self): assert to_camerapath("OWN.TXT") == "A/OWN.TXT" + + +class TestParseOwnTxt: + def test_parity_only(self): + assert parse_own_txt(b"EVEN\n") == ("EVEN", None) + + def test_parity_and_id(self): + assert parse_own_txt(b"EVEN\nid=3f9a1c2b7d4e\n") == ( + "EVEN", "3f9a1c2b7d4e", + ) + + def test_accepts_str(self): + assert parse_own_txt("ODD\nid=abc123\n") == ("ODD", "abc123") + + def test_crlf(self): + assert parse_own_txt(b"ODD\r\nid=abc123\r\n") == ("ODD", "abc123") + + def test_byte_order_mark(self): + assert parse_own_txt(b"\xef\xbb\xbfEVEN\nid=abc123\n") == ( + "EVEN", "abc123", + ) + + def test_trailing_whitespace(self): + assert parse_own_txt(b" EVEN \n id=abc123 \n") == ( + "EVEN", "abc123", + ) + + def test_blank_lines(self): + assert parse_own_txt(b"\n\nODD\n\n\nid=abc123\n\n") == ( + "ODD", "abc123", + ) + + def test_lowercase(self): + assert parse_own_txt(b"odd\nId=ABC123\n") == ("ODD", "ABC123") + + def test_missing_id_line(self): + assert parse_own_txt(b"ODD") == ("ODD", None) + + def test_unknown_lines_are_ignored(self): + data = b"# written by flash_chdk\nEVEN\nnotes=whatever\nid=abc123\n" + assert parse_own_txt(data) == ("EVEN", "abc123") + + def test_rubbish_gives_nothing(self): + assert parse_own_txt(b"\xff\xfe not a parity file at all") == ( + None, None, + ) + + def test_empty(self): + assert parse_own_txt(b"") == (None, None) + + def test_does_not_raise_on_a_wrong_type(self): + assert parse_own_txt(None) == (None, None) + + +class TestFormatOwnTxt: + def test_parity_and_id(self): + assert format_own_txt("EVEN", "3f9a1c2b7d4e") == ( + "EVEN\nid=3f9a1c2b7d4e\n" + ) + + def test_id_line_omitted_without_an_id(self): + assert format_own_txt("ODD") == "ODD\n" + + def test_parity_is_uppercased(self): + assert format_own_txt("even", "abc123") == "EVEN\nid=abc123\n" + + def test_round_trip(self): + text = format_own_txt("odd", "3f9a1c2b7d4e") + assert parse_own_txt(text) == ("ODD", "3f9a1c2b7d4e") diff --git a/tools/flash_chdk.py b/tools/flash_chdk.py index c6af5a9..86697aa 100755 --- a/tools/flash_chdk.py +++ b/tools/flash_chdk.py @@ -7,12 +7,17 @@ """ import plistlib +import secrets import subprocess import sys import urllib.request import zipfile from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src")) + +from pychdk.util import format_own_txt, parse_own_txt + CHDK_URL = "https://www.mighty-hoernsche.de/bins/a2500-100a-1.6.1-6315-full.zip" CHDK_FILENAME = "a2500-100a-1.6.1-6315-full.zip" CACHE_DIR = Path.home() / ".cache" / "pychdk" @@ -184,8 +189,13 @@ def get_mount_point(disk: str) -> str: def write_camera_side(mount_point: str): - """Ask user for camera side and write OWN.TXT.""" - choice = input("Which side is this camera? [o]dd / [e]ven / [s]kip: ").strip().lower() + """Ask which pages this camera shoots and write OWN.TXT. + + The file carries the page parity and a stable id for the body. An + id already on the card is kept, so re-flashing a card does not + change which camera the toolkit thinks it is. + """ + choice = input("Which pages does this camera shoot? [o]dd / [e]ven / [s]kip: ").strip().lower() if choice in ("o", "odd"): side = "ODD" elif choice in ("e", "even"): @@ -198,8 +208,19 @@ def write_camera_side(mount_point: str): return own_txt = Path(mount_point) / "OWN.TXT" - own_txt.write_text(side + "\n") - print(f"Wrote OWN.TXT ({side})") + camera_id = None + try: + camera_id = parse_own_txt(own_txt.read_bytes())[1] + except OSError: + camera_id = None + if camera_id: + origin = "kept the id already on the card" + else: + camera_id = secrets.token_hex(6) + origin = "minted a new id" + + own_txt.write_text(format_own_txt(side, camera_id)) + print(f"Wrote OWN.TXT ({side}, id={camera_id}) — {origin}") def eject_card(disk: str): From 532fd46989c956e070c68c3cd974fe97f4baf02a Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 14:30:38 -0700 Subject: [PATCH 04/34] chore(release): 0.1.1 Cuts the release carrying the chunked remote capture fix (NEH-241), the main-thread signal handler guard (NEH-242) and the camera id in OWN.TXT (NEH-243). --- pyproject.toml | 2 +- src/pychdk/__init__.py | 2 +- tests/test_version.py | 17 +++++++++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 tests/test_version.py diff --git a/pyproject.toml b/pyproject.toml index e53bfb2..6130ffd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "pychdk" -version = "0.1.0" +version = "0.1.1" description = "Pure Python CHDK PTP camera control" requires-python = ">=3.11" dependencies = [ diff --git a/src/pychdk/__init__.py b/src/pychdk/__init__.py index f33153f..b2f265f 100644 --- a/src/pychdk/__init__.py +++ b/src/pychdk/__init__.py @@ -1,5 +1,5 @@ """Pure Python CHDK PTP camera control.""" -__version__ = "0.1.0" +__version__ = "0.1.1" from pychdk.device import ( ChdkDevice, diff --git a/tests/test_version.py b/tests/test_version.py new file mode 100644 index 0000000..aa9f545 --- /dev/null +++ b/tests/test_version.py @@ -0,0 +1,17 @@ +"""The package version and pyproject.toml must not drift apart.""" +import tomllib +from pathlib import Path + +import pychdk + + +def _pyproject_version(): + """Read project.version from the pyproject.toml beside this checkout.""" + pyproject = Path(__file__).resolve().parent.parent / "pyproject.toml" + with pyproject.open("rb") as f: + return tomllib.load(f)["project"]["version"] + + +class TestVersion: + def test_package_version_matches_pyproject(self): + assert pychdk.__version__ == _pyproject_version() From 3d67301841227260aee041568e108c43f9a74ea4 Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 14:36:45 -0700 Subject: [PATCH 05/34] refactor(package): resolve the exports lazily so the flasher stays stdlib-only (NEH-243) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reaching pychdk.util used to import the whole package: __init__ pulled in device, device pulls in usb_transport, and usb_transport imports pyusb. So teaching tools/flash_chdk.py to write OWN.TXT through format_own_txt quietly gave the flasher a pyusb dependency it has no use for — util itself imports nothing but math. That matters because the flasher is a card-preparation tool. It runs on whatever Mac is nearest the card reader, before anything else is set up, and the README promises it needs only the standard library. Making that promise true again is worth more than the eager imports. A module-level __getattr__ (PEP 562) now imports the submodule that owns a name on first access and caches the result, so each export costs only its own module. __version__ and __all__ stay literals at the top, every name in __all__ resolves exactly as before, and an unknown name raises the AttributeError Python would have raised anyway. --- src/pychdk/__init__.py | 62 ++++++++++++++++++++++++++++++++++-------- tests/test_imports.py | 45 ++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 12 deletions(-) create mode 100644 tests/test_imports.py diff --git a/src/pychdk/__init__.py b/src/pychdk/__init__.py index b2f265f..2e758c2 100644 --- a/src/pychdk/__init__.py +++ b/src/pychdk/__init__.py @@ -1,20 +1,58 @@ """Pure Python CHDK PTP camera control.""" -__version__ = "0.1.1" +import importlib -from pychdk.device import ( - ChdkDevice, - list_devices, - DeviceInfo, - install_signal_handlers, -) -from pychdk.ptp import PTPError -from pychdk.chdk import ChdkPTP -from pychdk.multicam import MultiCam -from pychdk import util -from pychdk.util import parse_own_txt, format_own_txt +__version__ = "0.1.1" __all__ = [ "ChdkDevice", "list_devices", "DeviceInfo", "install_signal_handlers", "PTPError", "ChdkPTP", "MultiCam", "util", "parse_own_txt", "format_own_txt", ] + +# Submodules reachable as attributes of the package. +_SUBMODULES = ("util",) + +# Every other export, mapped to the submodule that owns it. +_EXPORTS = { + "ChdkDevice": "pychdk.device", + "list_devices": "pychdk.device", + "DeviceInfo": "pychdk.device", + "install_signal_handlers": "pychdk.device", + "PTPError": "pychdk.ptp", + "ChdkPTP": "pychdk.chdk", + "MultiCam": "pychdk.multicam", + "parse_own_txt": "pychdk.util", + "format_own_txt": "pychdk.util", +} + + +def __getattr__(name): + """Resolve an export on first access (PEP 562). + + Importing the submodules eagerly meant that reaching pychdk.util — + which needs nothing but math — imported pychdk.device and so pyusb. + Each name now costs only the submodule that owns it, and is cached + in the module globals afterwards. + + Args: + name: Attribute being looked up on the package. + + Returns: + The submodule or the exported object. + + Raises: + AttributeError: If the package exports no such name. + """ + if name in _SUBMODULES: + value = importlib.import_module(f"pychdk.{name}") + elif name in _EXPORTS: + value = getattr(importlib.import_module(_EXPORTS[name]), name) + else: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + globals()[name] = value + return value + + +def __dir__(): + """List the exports alongside whatever has already been resolved.""" + return sorted(set(globals()) | set(__all__)) diff --git a/tests/test_imports.py b/tests/test_imports.py new file mode 100644 index 0000000..c194f07 --- /dev/null +++ b/tests/test_imports.py @@ -0,0 +1,45 @@ +"""What importing the package is allowed to drag in with it.""" +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +import pychdk + +SRC = Path(__file__).resolve().parent.parent / "src" + + +def _run_import(code): + """Run a snippet against this checkout in a fresh interpreter.""" + env = dict(os.environ, PYTHONPATH=str(SRC)) + return subprocess.run( + [sys.executable, "-c", code], + capture_output=True, text=True, env=env, + ) + + +class TestFlasherStaysStdlibOnly: + """tools/flash_chdk.py must run on a fresh macOS, pyusb or not.""" + + def test_importing_pychdk_util_does_not_pull_in_pyusb(self): + result = _run_import( + "import pychdk.util, sys; print('usb' in sys.modules)" + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "False" + + +class TestExports: + def test_every_name_in_all_is_reachable(self): + for name in pychdk.__all__: + assert getattr(pychdk, name) is not None + + def test_util_is_the_submodule(self): + import pychdk.util + assert pychdk.util is sys.modules["pychdk.util"] + + def test_unknown_name_raises_attribute_error(self): + with pytest.raises(AttributeError, match="has no attribute 'nope'"): + pychdk.nope From fd10ad342ed6f3565d5e680a72a085284cb13ea7 Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 14:47:24 -0700 Subject: [PATCH 06/34] fix(capture): follow CHDK's seek semantics when assembling a capture (NEH-241) The third response parameter is documented in core/ptp.h as "seek required to pos (-1 = no seek)", and I read -1 as "append". Those are the same thing only until a chunk seeks backwards. Once one does, the current write position is no longer the end of the file, and the next unseeked chunk belongs at the cursor, not tacked onto the end: a camera that sent eight bytes, seeked to 0 to rewrite two, then continued without a seek produced xyCDEFGHzw where the file is xyzwEFGH. So keep the cursor a file would keep. A seek moves it, every chunk is written at it with any forward gap zero-filled, and it advances by the chunk's length. Appending was never the rule; it was the special case of a cursor that happened to sit at the end. --- src/pychdk/chdk.py | 32 ++++++++++++++++++++------------ tests/test_chdk.py | 23 ++++++++++++++++++++++- 2 files changed, 42 insertions(+), 13 deletions(-) diff --git a/src/pychdk/chdk.py b/src/pychdk/chdk.py index e0f7c28..fdf149f 100644 --- a/src/pychdk/chdk.py +++ b/src/pychdk/chdk.py @@ -273,9 +273,12 @@ def remote_capture_get_chunk(self, format_flag): * param1 — the chunk's size in bytes; * param2 — 1 while further chunks follow, 0 on the last one; - * param3 — the file position to seek to before writing this - chunk, or -1 to append. Parameters are unsigned, so -1 - arrives as 0xFFFFFFFF and is folded back here. + * param3 — "seek required to pos (-1 = no seek)", in the + header's words. No seek means the chunk continues from the + current write position, which is not the same as the end of + the file once a chunk has seeked backwards. Parameters are + unsigned, so -1 arrives as 0xFFFFFFFF and is folded back + here. A camera that sends fewer parameters is read as a single appended chunk the size of the data phase. @@ -285,7 +288,7 @@ def remote_capture_get_chunk(self, format_flag): Returns: Tuple of (chunk_bytes, more, position), where more is a bool - and position is a sign-corrected int (-1 means append). + and position is a sign-corrected int (-1 means no seek). """ params, data = self._session.transaction( OperationCode.CHDK, @@ -305,8 +308,12 @@ def remote_capture_get_data(self, format_flag): """Download remote capture image data. Loops over remote_capture_get_chunk until the camera clears its - "more" flag, placing each chunk at the position CHDK asks for. - A still larger than one chunk used to come back truncated. + "more" flag, following the same write cursor a file would. A + chunk that asks for a seek moves the cursor; every chunk is + written at the cursor and advances it by its own length. That + is what "-1 = no seek" means: the chunk continues from wherever + the last one ended, which is only the end of the file while no + chunk has seeked backwards. Args: format_flag: Which format to download (JPEG=1, RAW=2, DNG_HDR=4). @@ -318,15 +325,16 @@ def remote_capture_get_data(self, format_flag): RuntimeError: If the camera never clears its "more" flag. """ image = bytearray() + cursor = 0 for _ in range(MAX_CAPTURE_CHUNKS): chunk, more, position = self.remote_capture_get_chunk(format_flag) if position >= 0: - end = position + len(chunk) - if len(image) < end: - image.extend(bytes(end - len(image))) - image[position:end] = chunk - else: - image.extend(chunk) + cursor = position + end = cursor + len(chunk) + if len(image) < end: + image.extend(bytes(end - len(image))) + image[cursor:end] = chunk + cursor = end if not more: return bytes(image) raise RuntimeError( diff --git a/tests/test_chdk.py b/tests/test_chdk.py index 2b0dca4..1d40ac3 100644 --- a/tests/test_chdk.py +++ b/tests/test_chdk.py @@ -121,7 +121,7 @@ def test_explicit_position_places_a_late_chunk_first(self): ] assert chdk.remote_capture_get_data(1) == b"AAAAAAAABBBB" - def test_position_ffffffff_appends_instead_of_seeking(self): + def test_position_ffffffff_is_no_seek_not_a_huge_offset(self): chdk, session = self._make_chdk() session.transaction.side_effect = [ ([2, 1, 0xFFFFFFFF], b"hi"), @@ -136,6 +136,27 @@ def test_single_chunk_capture_is_returned_unchanged(self): ] assert chdk.remote_capture_get_data(1) == b"\xff\xd8\xff\xe0\x00" + def test_an_unseeked_chunk_continues_from_the_write_cursor(self): + chdk, session = self._make_chdk() + # CHDK seeks back to 0 to rewrite the first two bytes; the chunk + # after it carries no seek, so it continues from byte 2 — not + # from the end of what has been written so far. + session.transaction.side_effect = [ + ([8, 1, 0], b"ABCDEFGH"), + ([2, 1, 0], b"xy"), + ([2, 0, 0xFFFFFFFF], b"zw"), + ] + assert chdk.remote_capture_get_data(1) == b"xyzwEFGH" + + def test_a_forward_seek_leaves_a_zero_filled_gap(self): + chdk, session = self._make_chdk() + session.transaction.side_effect = [ + ([2, 1, 0], b"AB"), + ([2, 1, 6], b"CD"), + ([2, 0, 0xFFFFFFFF], b"EF"), + ] + assert chdk.remote_capture_get_data(1) == b"AB\x00\x00\x00\x00CDEF" + def test_camera_that_never_clears_more_raises(self): chdk, session = self._make_chdk() session.transaction.return_value = ([1, 1, 0xFFFFFFFF], b"x") From c1a1cd54d91e5520dd8becaf644266a1070d64af Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 14:49:05 -0700 Subject: [PATCH 07/34] fix(flasher): read the card's id before the card is erased (NEH-243) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit write_camera_side looked for an existing id in OWN.TXT, but main() calls format_card first, and eraseDisk has already taken the file away by then. The preservation branch could only ever fire for a card that had somehow not been formatted, so in the real workflow every re-flash minted a fresh identity — precisely what the docstring and the README promise it will not do. The promise was the only thing keeping it. main() now reads the id off the card before formatting and hands it to write_camera_side, which keeps its own read as a fallback for a card that was not formatted in this run. A card that will not mount, is unformatted, or has no readable OWN.TXT yields no id and no complaint: a blank card is the ordinary case, not an error worth stopping for. --- tests/test_flash_chdk.py | 82 ++++++++++++++++++++++++++++++++++++++++ tools/flash_chdk.py | 47 +++++++++++++++++++---- 2 files changed, 122 insertions(+), 7 deletions(-) create mode 100644 tests/test_flash_chdk.py diff --git a/tests/test_flash_chdk.py b/tests/test_flash_chdk.py new file mode 100644 index 0000000..0898e8c --- /dev/null +++ b/tests/test_flash_chdk.py @@ -0,0 +1,82 @@ +"""The flasher must not change a body's identity when a card is re-flashed.""" +import importlib.util +from pathlib import Path + +import pytest + +from pychdk.util import parse_own_txt + +TOOL = Path(__file__).resolve().parent.parent / "tools" / "flash_chdk.py" + + +def _load_tool(): + """Load tools/flash_chdk.py, which is a script and not a package.""" + spec = importlib.util.spec_from_file_location("flash_chdk", TOOL) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class TestCameraIdSurvivesAReflash: + def test_main_reads_the_id_before_it_erases_the_card(self, monkeypatch): + tool = _load_tool() + calls = [] + received = {} + + def record(name, result=None): + def fake(*args, **kwargs): + calls.append(name) + return result + return fake + + def fake_write(mount_point, existing_id=None): + calls.append("write_camera_side") + received["existing_id"] = existing_id + + monkeypatch.setattr(tool, "download_chdk", record("download_chdk")) + monkeypatch.setattr(tool, "find_removable_disks", record("find", [])) + monkeypatch.setattr(tool, "pick_disk", record("pick_disk", "/dev/disk9")) + monkeypatch.setattr( + tool, "read_existing_camera_id", + record("read_existing_camera_id", "abc123def456"), + ) + monkeypatch.setattr(tool, "format_card", record("format_card", "/Volumes/X")) + monkeypatch.setattr(tool, "extract_chdk", record("extract_chdk")) + monkeypatch.setattr(tool, "patch_boot_sector", record("patch_boot_sector")) + monkeypatch.setattr(tool, "get_mount_point", record("get_mount_point", "/Volumes/X")) + monkeypatch.setattr(tool, "write_camera_side", fake_write) + monkeypatch.setattr(tool, "eject_card", record("eject_card")) + + tool.main() + + assert calls.index("read_existing_camera_id") < calls.index("format_card") + assert received["existing_id"] == "abc123def456" + + def test_write_camera_side_keeps_the_id_it_is_handed( + self, tmp_path, monkeypatch, capsys, + ): + tool = _load_tool() + monkeypatch.setattr("builtins.input", lambda prompt="": "e") + tool.write_camera_side(str(tmp_path), existing_id="abc123def456") + assert (tmp_path / "OWN.TXT").read_text() == "EVEN\nid=abc123def456\n" + assert "kept" in capsys.readouterr().out + + def test_write_camera_side_mints_an_id_when_there_is_none( + self, tmp_path, monkeypatch, capsys, + ): + tool = _load_tool() + monkeypatch.setattr("builtins.input", lambda prompt="": "o") + tool.write_camera_side(str(tmp_path)) + side, camera_id = parse_own_txt((tmp_path / "OWN.TXT").read_bytes()) + assert side == "ODD" + assert camera_id is not None + assert "minted" in capsys.readouterr().out + + def test_reading_an_id_from_an_unusable_card_is_quiet(self, monkeypatch): + tool = _load_tool() + + def refuse(disk): + raise SystemExit(1) + + monkeypatch.setattr(tool, "get_mount_point", refuse) + assert tool.read_existing_camera_id("/dev/disk9") is None diff --git a/tools/flash_chdk.py b/tools/flash_chdk.py index 86697aa..224ac0d 100755 --- a/tools/flash_chdk.py +++ b/tools/flash_chdk.py @@ -188,12 +188,42 @@ def get_mount_point(disk: str) -> str: return info.get("MountPoint", f"/Volumes/{VOLUME_LABEL}") -def write_camera_side(mount_point: str): +def read_existing_camera_id(disk: str) -> str | None: + """Read the camera id from a card before the card is erased. + + main() formats the card long before OWN.TXT could be read off it, + so the id has to be salvaged first or it is gone. A card that will + not mount, is unformatted, or carries no readable OWN.TXT simply + has no id: this never raises and never prompts. get_mount_point + exits the process when diskutil fails, which is why SystemExit is + caught here. + + Args: + disk: /dev/diskN path. + + Returns: + The id already on the card, or None. + """ + try: + mount_point = get_mount_point(disk) + data = (Path(mount_point) / "OWN.TXT").read_bytes() + except (SystemExit, OSError, ValueError): + return None + return parse_own_txt(data)[1] + + +def write_camera_side(mount_point: str, existing_id: str | None = None): """Ask which pages this camera shoots and write OWN.TXT. The file carries the page parity and a stable id for the body. An id already on the card is kept, so re-flashing a card does not change which camera the toolkit thinks it is. + + Args: + mount_point: Where the card is mounted. + existing_id: Id read off the card before it was erased, if any. + Falls back to reading OWN.TXT here, for a card that was not + formatted in this run. """ choice = input("Which pages does this camera shoot? [o]dd / [e]ven / [s]kip: ").strip().lower() if choice in ("o", "odd"): @@ -208,11 +238,12 @@ def write_camera_side(mount_point: str): return own_txt = Path(mount_point) / "OWN.TXT" - camera_id = None - try: - camera_id = parse_own_txt(own_txt.read_bytes())[1] - except OSError: - camera_id = None + camera_id = existing_id + if not camera_id: + try: + camera_id = parse_own_txt(own_txt.read_bytes())[1] + except OSError: + camera_id = None if camera_id: origin = "kept the id already on the card" else: @@ -233,12 +264,14 @@ def main(): zip_path = download_chdk() disks = find_removable_disks() disk = pick_disk(disks) + # Salvage the body's identity before eraseDisk takes it away. + existing_id = read_existing_camera_id(disk) mount_point = format_card(disk) extract_chdk(zip_path, mount_point) patch_boot_sector(disk) mount_point = get_mount_point(disk) - write_camera_side(mount_point) + write_camera_side(mount_point, existing_id=existing_id) eject_card(disk) print("Done! Lock the SD card and insert into camera.") From d6dd5516e7a54f6ddb24d2bcf5ff100716beab5b Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 14:50:21 -0700 Subject: [PATCH 08/34] fix(own-txt): accept only a well-formed id, and never let a bad line hide a good one (NEH-243) parse_own_txt took the first nonempty value after an 'id=' and stopped looking. A card whose id line had picked up a bad byte therefore parsed as the replacement character, and the flasher dutifully preserved that as the body's identity while the real id sat on the line below, unread. Being forgiving about the file's shape is right; being forgiving about what an identity looks like is not. An id is now twelve to thirty-two hex characters, and every 'id=' line is examined until one qualifies, so a corrupt line costs nothing. A further valid id is ignored: a file claiming two identities cannot say which body it belongs to, and picking the later one would silently rename a camera. Ids come back lowercased so that no caller has to remember to fold case before comparing. --- src/pychdk/util.py | 19 ++++++++++++++++--- tests/test_util.py | 44 ++++++++++++++++++++++++++++++++------------ 2 files changed, 48 insertions(+), 15 deletions(-) diff --git a/src/pychdk/util.py b/src/pychdk/util.py index 94ec70b..e9e4857 100644 --- a/src/pychdk/util.py +++ b/src/pychdk/util.py @@ -4,6 +4,7 @@ These functions convert between human-readable values and APEX96. """ import math +import re def shutter_to_tv96(shutter_speed): @@ -64,6 +65,11 @@ def to_camerapath(path): return "A/" + path +# A camera id is hex, long enough not to collide and short enough to +# read aloud over a workbench. The flasher mints twelve characters. +_CAMERA_ID_RE = re.compile(r"^[0-9a-f]{12,32}$") + + def parse_own_txt(data): """Read a camera's page parity and id from OWN.TXT. @@ -78,12 +84,19 @@ def parse_own_txt(data): lines, lowercase keywords, a missing id line and unknown lines. It never raises: rubbish simply parses as nothing. + An id counts only when it is twelve to thirty-two hexadecimal + characters. Every 'id=' line is examined and the first valid one + wins, so a corrupt line cannot shield a good one below it; any + further valid id is ignored rather than merged, because a file with + two identities has no way to say which body it belongs to. The id + comes back lowercased, so callers can compare it directly. + Args: data: File contents as bytes or str. Returns: Tuple of (side, camera_id), where side is 'ODD', 'EVEN' or None - and camera_id is the id line's value or None. + and camera_id is the first well-formed id, lowercased, or None. """ if isinstance(data, (bytes, bytearray)): text = bytes(data).decode("utf-8-sig", errors="replace") @@ -101,8 +114,8 @@ def parse_own_txt(data): if side is None and line.upper() in ("ODD", "EVEN"): side = line.upper() elif camera_id is None and line.upper().startswith("ID="): - value = line.split("=", 1)[1].strip() - if value: + value = line.split("=", 1)[1].strip().lower() + if _CAMERA_ID_RE.match(value): camera_id = value return side, camera_id diff --git a/tests/test_util.py b/tests/test_util.py index e26e149..b680c58 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -62,35 +62,55 @@ def test_parity_and_id(self): ) def test_accepts_str(self): - assert parse_own_txt("ODD\nid=abc123\n") == ("ODD", "abc123") + assert parse_own_txt("ODD\nid=abc123def456\n") == ("ODD", "abc123def456") def test_crlf(self): - assert parse_own_txt(b"ODD\r\nid=abc123\r\n") == ("ODD", "abc123") + assert parse_own_txt(b"ODD\r\nid=abc123def456\r\n") == ("ODD", "abc123def456") def test_byte_order_mark(self): - assert parse_own_txt(b"\xef\xbb\xbfEVEN\nid=abc123\n") == ( - "EVEN", "abc123", + assert parse_own_txt(b"\xef\xbb\xbfEVEN\nid=abc123def456\n") == ( + "EVEN", "abc123def456", ) def test_trailing_whitespace(self): - assert parse_own_txt(b" EVEN \n id=abc123 \n") == ( - "EVEN", "abc123", + assert parse_own_txt(b" EVEN \n id=abc123def456 \n") == ( + "EVEN", "abc123def456", ) def test_blank_lines(self): - assert parse_own_txt(b"\n\nODD\n\n\nid=abc123\n\n") == ( - "ODD", "abc123", + assert parse_own_txt(b"\n\nODD\n\n\nid=abc123def456\n\n") == ( + "ODD", "abc123def456", ) def test_lowercase(self): - assert parse_own_txt(b"odd\nId=ABC123\n") == ("ODD", "ABC123") + assert parse_own_txt(b"odd\nId=ABC123DEF456\n") == ("ODD", "abc123def456") def test_missing_id_line(self): assert parse_own_txt(b"ODD") == ("ODD", None) def test_unknown_lines_are_ignored(self): - data = b"# written by flash_chdk\nEVEN\nnotes=whatever\nid=abc123\n" - assert parse_own_txt(data) == ("EVEN", "abc123") + data = b"# written by flash_chdk\nEVEN\nnotes=whatever\nid=abc123def456\n" + assert parse_own_txt(data) == ("EVEN", "abc123def456") + + def test_a_malformed_id_line_does_not_hide_a_good_one(self): + assert parse_own_txt(b"ODD\nid=\xff\nid=3f9a1c2b7d4e\n") == ( + "ODD", "3f9a1c2b7d4e", + ) + + def test_an_uppercase_id_comes_back_lowercase(self): + assert parse_own_txt(b"ODD\nid=3F9A1C2B7D4E\n") == ( + "ODD", "3f9a1c2b7d4e", + ) + + def test_a_too_short_id_is_rejected(self): + assert parse_own_txt(b"ODD\nid=3f9a1c2b\n") == ("ODD", None) + + def test_a_non_hex_id_is_rejected(self): + assert parse_own_txt(b"ODD\nid=not-an-id-at-all\n") == ("ODD", None) + + def test_the_first_valid_id_wins(self): + data = b"ODD\nid=3f9a1c2b7d4e\nid=aaaaaaaaaaaa\n" + assert parse_own_txt(data) == ("ODD", "3f9a1c2b7d4e") def test_rubbish_gives_nothing(self): assert parse_own_txt(b"\xff\xfe not a parity file at all") == ( @@ -114,7 +134,7 @@ def test_id_line_omitted_without_an_id(self): assert format_own_txt("ODD") == "ODD\n" def test_parity_is_uppercased(self): - assert format_own_txt("even", "abc123") == "EVEN\nid=abc123\n" + assert format_own_txt("even", "abc123def456") == "EVEN\nid=abc123def456\n" def test_round_trip(self): text = format_own_txt("odd", "3f9a1c2b7d4e") From d983e333a25fd97d77dc24b131b98a4131f08a54 Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 14:51:21 -0700 Subject: [PATCH 09/34] feat(capture): refuse a streamed DNG instead of returning a partial file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit shoot(dng=True, stream=True) asked the camera for RAW|DNG_HDR and then downloaded a single format off the readiness bitmask. But the DNG flag delivers only the DNG header: the raw data is a second transfer, and the file has to be spliced together on this side. What came back was therefore never a DNG, and nothing said so — it had a plausible size and a plausible header, which is the worst way for a file to be wrong. An operator would have found out at the far end of a scanning session. Refusing is better than half-doing it. The error names what is missing so the next person knows what implementing it involves, and points at the two routes that work today: DNG to the card, or JPEG over USB. Assembling the two transfers is real work and deserves its own change, not a silent guess inside this one. --- src/pychdk/device.py | 18 +++++++++++++++--- tests/test_device.py | 5 +++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/pychdk/device.py b/src/pychdk/device.py index 25cd693..b95e318 100644 --- a/src/pychdk/device.py +++ b/src/pychdk/device.py @@ -226,11 +226,23 @@ def shoot(self, shutter_speed=None, market_iso=None, dng=False, return self._shoot_standard(parts, download_after, remove_after) def _shoot_streaming(self, setup_parts, dng): - """Capture using remote capture (PTP commands 13/14).""" - fmt = REMOTE_CAP_JPEG + """Capture using remote capture (PTP commands 13/14). + + Raises: + NotImplementedError: If dng is True. CHDK's DNG_HDR flag + sends the DNG header only; the raw data is a separate + transfer, and the client has to splice the two into a + file. This method downloads one format, so it cannot. + """ if dng: - fmt = REMOTE_CAP_RAW | REMOTE_CAP_DNG_HDR + raise NotImplementedError( + "Streamed DNG is not supported: CHDK sends the DNG header " + "and the raw data as two separate transfers that the client " + "must assemble into a file. Capture DNG with stream=False, " + "or stream JPEG." + ) + fmt = REMOTE_CAP_JPEG script = "init_usb_capture({})".format(fmt) for part in setup_parts: script = part + "; " + script diff --git a/tests/test_device.py b/tests/test_device.py index ed9f6b2..dab434e 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -75,6 +75,11 @@ def test_download_file(self): result = dev.download_file("A/OWN.TXT") assert result == b"EVEN\n" + def test_streamed_dng_is_refused(self): + dev, mock_chdk = self._make_device() + with pytest.raises(NotImplementedError, match="DNG"): + dev.shoot(dng=True, stream=True) + def test_close(self): dev, mock_chdk = self._make_device() dev.close() From dc948835f505e7f7a0631732b9c89d12091e7c14 Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 14:55:44 -0700 Subject: [PATCH 10/34] fix(capture): tell an uninitialized remote capture from a ready one (NEH-241) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit core/ptp.h gives RemoteCaptureIsReady three answers in param1, not two: 0 is not ready, 0x10000000 says remote capture was never initialized, and anything else is a bitmask of the data types that are ready. We treated every nonzero status as ready and handed the value straight back as a format, so a camera that had never seen init_usb_capture read as ready with a format of 0x10000000, and the next call asked for a data type that does not exist. What the operator saw was a protocol error from the wrong end of the exchange, or a thirty-second wait for a shot that was never coming — never the one fact that would have helped, which is that the capture was not set up. It now raises and says so. The download request also takes a single bit: the header calls param2 "bit indicating data type to get", while a ready mask can have several set. We ask for the format we requested if the camera has it and the lowest ready bit otherwise. With streamed DNG refused, only JPEG is ever asked for today, so this costs one line and stops the mask being mistaken for a data type if that changes. --- src/pychdk/chdk.py | 28 +++++++++++++++++++++++++--- src/pychdk/device.py | 6 ++++-- tests/test_chdk.py | 23 +++++++++++++++++++++++ tests/test_device.py | 23 +++++++++++++++++++++++ 4 files changed, 75 insertions(+), 5 deletions(-) diff --git a/src/pychdk/chdk.py b/src/pychdk/chdk.py index fdf149f..efbdfb5 100644 --- a/src/pychdk/chdk.py +++ b/src/pychdk/chdk.py @@ -62,6 +62,10 @@ class ScriptFlag(IntEnum): REMOTE_CAP_RAW = 0x02 REMOTE_CAP_DNG_HDR = 0x04 +# Not a data type: the status PTP_CHDK_RemoteCaptureIsReady reports when +# init_usb_capture has not run (PTP_CHDK_CAPTURE_NOTSET in core/ptp.h). +REMOTE_CAP_NOTSET = 0x10000000 + # A full-resolution still needs a few hundred chunks at most; this only # exists so a camera that never clears the "more" flag cannot hang us. MAX_CAPTURE_CHUNKS = 10000 @@ -252,17 +256,35 @@ def get_display_data(self, flags=0): def remote_capture_is_ready(self): """Check if a remote capture is ready for download. + CHDK's PTP_CHDK_RemoteCaptureIsReady (core/ptp.h) returns a + status in param1: 0 is not ready yet, 0x10000000 says remote + capture was never initialized, and any other value is a bitmask + of the PTP_CHDK_CAPTURE_* data types that are ready. The + uninitialized status is not a bitmask and must not be passed + back as one. + Returns: - Tuple of (is_ready, image_format). + Tuple of (is_ready, formats), where formats is a bitmask of + the data types ready to download. + + Raises: + RuntimeError: If the camera says remote capture was never + initialized. """ params, _ = self._session.transaction( OperationCode.CHDK, params=[ChdkCommand.REMOTE_CAPTURE_IS_READY], receive_data=False, ) - if not params or params[0] == 0: + status = params[0] if params else 0 + if status == REMOTE_CAP_NOTSET: + raise RuntimeError( + "Remote capture is not initialized on the camera: " + "init_usb_capture must run before the shot" + ) + if status == 0: return False, 0 - return True, params[0] + return True, status def remote_capture_get_chunk(self, format_flag): """Fetch one chunk of a remote capture. diff --git a/src/pychdk/device.py b/src/pychdk/device.py index b95e318..ed7174b 100644 --- a/src/pychdk/device.py +++ b/src/pychdk/device.py @@ -252,9 +252,11 @@ def _shoot_streaming(self, setup_parts, dng): deadline = time.monotonic() + 30 while time.monotonic() < deadline: - ready, img_fmt = self._chdk.remote_capture_is_ready() + ready, formats = self._chdk.remote_capture_is_ready() if ready: - return self._chdk.remote_capture_get_data(img_fmt) + # The request parameter is one bit, not the whole mask. + data_type = fmt if formats & fmt else formats & -formats + return self._chdk.remote_capture_get_data(data_type) time.sleep(0.1) raise TimeoutError("Remote capture did not complete") diff --git a/tests/test_chdk.py b/tests/test_chdk.py index 1d40ac3..bf3b769 100644 --- a/tests/test_chdk.py +++ b/tests/test_chdk.py @@ -95,6 +95,29 @@ def test_string(self): assert _decode_script_value(ScriptDataType.STRING, b"hello") == "hello" +class TestRemoteCaptureIsReady: + def _make_chdk(self): + mock_session = MagicMock() + return ChdkPTP(mock_session), mock_session + + def test_uninitialized_capture_raises(self): + chdk, session = self._make_chdk() + # 0x10000000 is PTP_CHDK_CAPTURE_NOTSET, not a data type bitmask. + session.transaction.return_value = ([0x10000000], b"") + with pytest.raises(RuntimeError, match="init_usb_capture"): + chdk.remote_capture_is_ready() + + def test_status_zero_is_not_ready(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ([0], b"") + assert chdk.remote_capture_is_ready() == (False, 0) + + def test_a_nonzero_status_is_the_ready_bitmask(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ([0x03], b"") + assert chdk.remote_capture_is_ready() == (True, 0x03) + + class TestRemoteCaptureGetData: """Chunk assembly for PTP_CHDK_RemoteCaptureGetData.""" diff --git a/tests/test_device.py b/tests/test_device.py index dab434e..4b75bd9 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -80,6 +80,29 @@ def test_streamed_dng_is_refused(self): with pytest.raises(NotImplementedError, match="DNG"): dev.shoot(dng=True, stream=True) + def test_streaming_asks_for_a_single_data_type(self): + dev, mock_chdk = self._make_device() + # JPEG and RAW both ready; the request parameter takes one bit. + mock_chdk.remote_capture_is_ready.return_value = (True, 0x03) + mock_chdk.remote_capture_get_data.return_value = b"jpeg" + assert dev.shoot(stream=True) == b"jpeg" + mock_chdk.remote_capture_get_data.assert_called_once_with(1) + + def test_streaming_falls_back_to_the_lowest_ready_bit(self): + dev, mock_chdk = self._make_device() + # No JPEG on offer: RAW (0x2) and DNG header (0x4). + mock_chdk.remote_capture_is_ready.return_value = (True, 0x06) + mock_chdk.remote_capture_get_data.return_value = b"raw" + assert dev.shoot(stream=True) == b"raw" + mock_chdk.remote_capture_get_data.assert_called_once_with(2) + + def test_streaming_jpeg_is_unchanged(self): + dev, mock_chdk = self._make_device() + mock_chdk.remote_capture_is_ready.return_value = (True, 0x01) + mock_chdk.remote_capture_get_data.return_value = b"jpeg" + assert dev.shoot(stream=True) == b"jpeg" + mock_chdk.remote_capture_get_data.assert_called_once_with(1) + def test_close(self): dev, mock_chdk = self._make_device() dev.close() From 111e91e72647f2e4cb32a78231d31bf7be817eaa Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 15:00:02 -0700 Subject: [PATCH 11/34] fix(script): keep the text of a script error and name its kind MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An ERR message's param2 is a ptp_chdk_script_error_type, not a ptp_chdk_script_data_type, and the two enums overlap: we read COMPILE as NIL and RUN as BOOLEAN, so every Lua error decoded to None or True and the actual text sat unread in the data phase. What a caller saw was "Script error: None". A syntax error and a missing camera function were indistinguishable, and neither said anything about itself. An ERR now takes its text from the data phase as UTF-8, undecodable bytes replaced and the trailing NUL stripped, since the header promises at least one zero byte even for an empty message. Every other message type decodes exactly as before. execute_lua_wait names the kind alongside the text, so a compile error reads as "Script error (compile): attempt to call a nil value". The namedtuple keeps its field names — renaming data_type would break callers — and now says in its docstring which subtype it is carrying. This matters more than its size suggests: we get one bench session with the cameras, and an error that arrives as None costs a slot in it. --- src/pychdk/chdk.py | 55 ++++++++++++++++++++++++++++++++++-- tests/test_chdk.py | 69 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 120 insertions(+), 4 deletions(-) diff --git a/src/pychdk/chdk.py b/src/pychdk/chdk.py index efbdfb5..27d3014 100644 --- a/src/pychdk/chdk.py +++ b/src/pychdk/chdk.py @@ -51,6 +51,18 @@ class MessageType(IntEnum): USER = 3 +class ScriptErrorType(IntEnum): + """ptp_chdk_script_error_type, the subtype of an ERR message. + + SCRIPT_RUNNING is an ExecuteScript startup status only, never a + message subtype, per core/ptp.h. + """ + NONE = 0 + COMPILE = 1 + RUN = 2 + SCRIPT_RUNNING = 0x1000 + + class ScriptFlag(IntEnum): NONE = 0 NOKILL = 0x100 @@ -72,6 +84,30 @@ class ScriptFlag(IntEnum): ScriptMessage = namedtuple("ScriptMessage", ["msg_type", "data_type", "script_id", "value"]) +ScriptMessage.__doc__ = """One message from the camera's script queue. + +The data_type field carries whichever subtype the message type calls +for, as core/ptp.h defines it: a ScriptDataType for RET and USER +messages, and a ScriptErrorType for ERR. The field keeps its name for +the sake of callers that already read it. +""" + + +def _script_error_name(error_type): + """Name a script error type for a message a human has to read. + + Args: + error_type: Value of an ERR message's subtype, or an + ExecuteScript startup status. + + Returns: + Lowercase name, or the raw value in hex if CHDK sends one we + do not know. + """ + try: + return ScriptErrorType(error_type).name.lower() + except ValueError: + return f"unknown 0x{int(error_type):x}" def _as_signed32(value): @@ -175,8 +211,16 @@ def read_script_message(self): [msg_type, data_type, script_id, data_size] Data phase contains the raw value bytes. + Param2 is the message subtype, and what it means depends on the + message type: for RET and USER it is a ScriptDataType, but for + ERR it is a ScriptErrorType, and the data phase is the error + text rather than an encoded value. Reading an ERR's subtype as + a data type silently threw that text away — the two enums + overlap, so COMPILE decoded as NIL and RUN as BOOLEAN. + Returns: - ScriptMessage namedtuple. + ScriptMessage namedtuple. Its data_type field holds an + error type when msg_type is ERR, a data type otherwise. """ params, data = self._session.transaction( OperationCode.CHDK, @@ -188,7 +232,11 @@ def read_script_message(self): msg_type = params[0] data_type = params[1] if len(params) > 1 else ScriptDataType.NIL script_id = params[2] if len(params) > 2 else 0 - value = _decode_script_value(data_type, data) + if msg_type == MessageType.ERR: + # The header guarantees at least one zero byte, even empty. + value = data.decode("utf-8", errors="replace").rstrip("\x00") + else: + value = _decode_script_value(data_type, data) return ScriptMessage(msg_type, data_type, script_id, value) def write_script_message(self, message, script_id=0): @@ -407,7 +455,8 @@ def execute_lua_wait(self, script, timeout=10.0): if msg.msg_type == MessageType.RET: return msg.value if msg.msg_type == MessageType.ERR: - raise RuntimeError(f"Script error: {msg.value}") + kind = _script_error_name(msg.data_type) + raise RuntimeError(f"Script error ({kind}): {msg.value}") if not running and not has_msgs: return None time.sleep(0.05) diff --git a/tests/test_chdk.py b/tests/test_chdk.py index bf3b769..7c35ae5 100644 --- a/tests/test_chdk.py +++ b/tests/test_chdk.py @@ -1,13 +1,15 @@ """Tests for CHDK PTP extension protocol.""" import struct -from unittest.mock import MagicMock +from unittest.mock import MagicMock, patch import pytest from pychdk.chdk import ( ChdkPTP, ChdkCommand, ScriptLanguage, ScriptDataType, + ScriptErrorType, MessageType, + ScriptMessage, _decode_script_value, ) from pychdk.ptp import ResponseCode, PTPContainer, ContainerType @@ -75,6 +77,71 @@ def test_read_script_message_none(self): assert msg.value is None +class TestScriptErrors: + """An ERR message's subtype is an error type, not a data type.""" + + def _make_chdk(self): + mock_session = MagicMock() + return ChdkPTP(mock_session), mock_session + + def test_a_compile_error_keeps_its_text_and_kind(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ( + [MessageType.ERR, ScriptErrorType.COMPILE, 7, 28], + b"attempt to call a nil value\x00", + ) + msg = chdk.read_script_message() + assert msg.data_type == ScriptErrorType.COMPILE + assert msg.value == "attempt to call a nil value" + + def test_a_run_error_keeps_its_text_and_kind(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ( + [MessageType.ERR, ScriptErrorType.RUN, 7, 15], + b"bad argument\x00", + ) + msg = chdk.read_script_message() + assert msg.data_type == ScriptErrorType.RUN + assert msg.value == "bad argument" + + def test_an_error_with_no_text_is_empty_but_still_named(self): + chdk, session = self._make_chdk() + # The header promises at least one zero byte even with no message. + session.transaction.return_value = ( + [MessageType.ERR, ScriptErrorType.RUN, 7, 1], + b"\x00", + ) + msg = chdk.read_script_message() + assert msg.data_type == ScriptErrorType.RUN + assert msg.value == "" + + def test_a_return_value_with_a_colliding_subtype_still_decodes(self): + chdk, session = self._make_chdk() + # Subtype 2 is BOOLEAN for a RET and ERRTYPE_RUN for an ERR. + session.transaction.return_value = ( + [MessageType.RET, ScriptDataType.BOOLEAN, 7, 4], + struct.pack(" Date: Wed, 9 Sep 2026 15:01:14 -0700 Subject: [PATCH 12/34] fix(script): refuse a script that never started MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ExecuteScript returns the script id in param1 and a startup status in param2, and we read only the first. A script the camera refused — because it would not compile, or because one was already running and NOKILL was set — came back looking exactly like a script that had started, id and all. execute_lua_wait then polled for a message from it until the timeout ran out and reported that the script had not completed, which is true and useless: it never began. Reading param2 turns a thirty-second wait and a wrong diagnosis into an immediate one that names the kind. The NOKILL case says what 0x1000 means in words rather than leaving a bare code, because that is the one an operator will actually hit: shoot twice in quick succession and the second is refused while the first is still going. --- src/pychdk/chdk.py | 16 ++++++++++++++++ tests/test_chdk.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/src/pychdk/chdk.py b/src/pychdk/chdk.py index 27d3014..4997c35 100644 --- a/src/pychdk/chdk.py +++ b/src/pychdk/chdk.py @@ -179,8 +179,16 @@ def execute_script(self, script, language=ScriptLanguage.LUA, language: ScriptLanguage.LUA or ScriptLanguage.UBASIC. flags: ScriptFlag bitmask (NOKILL, FLUSH). + CHDK returns the script id in param1 and a startup status from + ptp_chdk_script_error_type in param2 (core/ptp.h). A nonzero + status means the script never started, so the id is not one: + waiting on it would only burn the caller's whole timeout. + Returns: Script ID assigned by the camera. + + Raises: + RuntimeError: If the camera refused to start the script. """ script_bytes = script.encode("utf-8") + b"\x00" params, _ = self._session.transaction( @@ -188,6 +196,14 @@ def execute_script(self, script, language=ScriptLanguage.LUA, params=[ChdkCommand.EXECUTE_SCRIPT, language | flags], send_data=script_bytes, ) + status = params[1] if len(params) > 1 else 0 + if status: + if status == ScriptErrorType.SCRIPT_RUNNING: + reason = ("a script is already running and NOKILL was set, " + "so this one was refused") + else: + reason = f"{_script_error_name(status)} error" + raise RuntimeError(f"Script did not start: {reason}") return params[0] if params else 0 def get_script_status(self): diff --git a/tests/test_chdk.py b/tests/test_chdk.py index 7c35ae5..15b2fc1 100644 --- a/tests/test_chdk.py +++ b/tests/test_chdk.py @@ -142,6 +142,50 @@ def test_execute_lua_wait_reports_the_kind_and_the_text(self): chdk.execute_lua_wait("bogus(") +class TestScriptStartupStatus: + """ExecuteScript reports in param2 whether the script actually ran.""" + + def _make_chdk(self): + mock_session = MagicMock() + return ChdkPTP(mock_session), mock_session + + def test_a_compile_error_refuses_the_script(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ([0, ScriptErrorType.COMPILE], b"") + with pytest.raises(RuntimeError, match="compile"): + chdk.execute_script("bogus(") + + def test_a_run_error_refuses_the_script(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ([0, ScriptErrorType.RUN], b"") + with pytest.raises(RuntimeError, match="run"): + chdk.execute_script("error()") + + def test_nokill_refusal_says_what_it_means(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ( + [0, ScriptErrorType.SCRIPT_RUNNING], b"", + ) + with pytest.raises(RuntimeError, match="already running"): + chdk.execute_script("shoot()") + + def test_a_zero_status_returns_the_script_id(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ([7, ScriptErrorType.NONE], b"") + assert chdk.execute_script("return 1") == 7 + + def test_a_refused_script_fails_without_waiting(self): + chdk, session = self._make_chdk() + session.transaction.side_effect = [ + ([0], b""), # drain: nothing pending + ([0, ScriptErrorType.COMPILE], b""), # execute: refused + ] + with pytest.raises(RuntimeError, match="compile"): + chdk.execute_lua_wait("bogus(", timeout=30) + # The drain and the execute, and no polling loop after them. + assert session.transaction.call_count == 2 + + class TestDecodeScriptValue: def test_integer(self): data = struct.pack(" Date: Wed, 9 Sep 2026 15:07:12 -0700 Subject: [PATCH 13/34] ci: run the test suite on push and pull request The library is now tagged and pinned by the appliance, so the mocked protocol suite should run on every change rather than only where someone remembers to. It runs on 3.11, the floor pyproject sets and the version the backend pins in pixi.toml, and on 3.12 to catch anything that breaks on a newer interpreter before the appliance moves. --- .github/workflows/ci.yml | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b9f36c2 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,30 @@ +# The suite is all mocks: it runs the PTP and CHDK protocol logic without a +# camera, which is the only way this library can be tested between bench +# sessions. `tests/` is named explicitly because `examples/` holds hardware +# scripts that pytest would otherwise collect and fail to import. +name: CI + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.11", "3.12"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - name: Install + run: | + python -m pip install --upgrade pip + pip install -e ".[dev]" + - name: Test + run: pytest tests/ -q From 90f778e88ca33281806c47d0b6a134a85ef5b6a2 Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 15:13:06 -0700 Subject: [PATCH 14/34] fix(capture): initialize and shoot in one script so the shot cannot kill its own setup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Streaming sent init_usb_capture and shoot() as two unwaited scripts, and CHDK kills a running script when a new one arrives unless NOKILL is set. So the shot could terminate its own setup. The camera then did what a camera does with no USB capture configured — took an ordinary shot to the card — while we sat in the readiness poll for thirty seconds waiting for bytes that were never coming. It would have looked like a flaky camera, and on a bench with two bodies and one afternoon that is the worst thing for it to look like. One script now carries the setup, the init and the shutter, so nothing can arrive in between, and we wait for it instead of firing and hoping. The script reports the init's result, and only an explicit false is treated as a refusal: an older CHDK returns nothing from init_usb_capture, and a nil that read as failure would break cameras that work fine. Setup parts are joined in the order given, matching _shoot_standard; they were being reversed here for no reason. --- src/pychdk/device.py | 31 +++++++++++++++++++++++++------ tests/test_device.py | 26 ++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 6 deletions(-) diff --git a/src/pychdk/device.py b/src/pychdk/device.py index ed7174b..b2260fe 100644 --- a/src/pychdk/device.py +++ b/src/pychdk/device.py @@ -228,7 +228,18 @@ def shoot(self, shutter_speed=None, market_iso=None, dng=False, def _shoot_streaming(self, setup_parts, dng): """Capture using remote capture (PTP commands 13/14). + Setup and shutter go out as one script, because a second script + kills the first unless NOKILL is set ("if script is running + return error instead of killing", core/ptp.h) — so a separate + shoot() could terminate the init_usb_capture that was still + running and leave the camera taking an ordinary card shot while + we waited for bytes that were never coming. The script returns + after the shutter, so the readiness poll below usually finds + the data waiting on its first pass. + Raises: + RuntimeError: If the camera refuses to initialize remote + capture. NotImplementedError: If dng is True. CHDK's DNG_HDR flag sends the DNG header only; the raw data is a separate transfer, and the client has to splice the two into a @@ -243,12 +254,20 @@ def _shoot_streaming(self, setup_parts, dng): ) fmt = REMOTE_CAP_JPEG - script = "init_usb_capture({})".format(fmt) - for part in setup_parts: - script = part + "; " + script - self.lua_execute(script, do_return=False) - - self.lua_execute("shoot()", do_return=False) + setup = "".join(part + "; " for part in setup_parts) + script = ( + f"{setup}local ok = init_usb_capture({fmt}); " + "if ok == false then return false end; " + "shoot(); " + "return true" + ) + # Only an explicit false is a refusal: an older CHDK returns + # nothing at all, and nil must not be read as failure. + if self.lua_execute(script, timeout=30) is False: + raise RuntimeError( + "The camera refused to initialize remote capture: " + "init_usb_capture returned false" + ) deadline = time.monotonic() + 30 while time.monotonic() < deadline: diff --git a/tests/test_device.py b/tests/test_device.py index 4b75bd9..8ba88d6 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -80,6 +80,32 @@ def test_streamed_dng_is_refused(self): with pytest.raises(NotImplementedError, match="DNG"): dev.shoot(dng=True, stream=True) + def test_streaming_initializes_and_shoots_in_one_script(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_lua_wait.return_value = True + mock_chdk.remote_capture_is_ready.return_value = (True, 0x01) + mock_chdk.remote_capture_get_data.return_value = b"jpeg" + assert dev.shoot(stream=True) == b"jpeg" + # One script: a second one would kill the first, setup included. + assert mock_chdk.execute_lua_wait.call_count == 1 + script = mock_chdk.execute_lua_wait.call_args[0][0] + assert "init_usb_capture" in script + assert "shoot()" in script + + def test_streaming_raises_when_the_camera_refuses_to_initialize(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_lua_wait.return_value = False + with pytest.raises(RuntimeError, match="initialize remote capture"): + dev.shoot(stream=True) + + def test_streaming_tolerates_a_camera_that_returns_nothing(self): + dev, mock_chdk = self._make_device() + # An older CHDK returns nil, which is not a refusal. + mock_chdk.execute_lua_wait.return_value = None + mock_chdk.remote_capture_is_ready.return_value = (True, 0x01) + mock_chdk.remote_capture_get_data.return_value = b"jpeg" + assert dev.shoot(stream=True) == b"jpeg" + def test_streaming_asks_for_a_single_data_type(self): dev, mock_chdk = self._make_device() # JPEG and RAW both ready; the request parameter takes one bit. From e3317508cb7864bd1d49c5a66102a17e24b9328e Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 15:14:03 -0700 Subject: [PATCH 15/34] fix(capture): refuse a ready mask without the requested format MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Falling back to the lowest ready bit meant a camera offering RAW and a DNG header, but no JPEG, returned raw framebuffer bytes to a caller that had asked for a JPEG — the right number of bytes, the wrong picture, and nothing anywhere saying so. A file like that survives the whole pipeline and is only found later, if at all. A ready mask that lacks the format we asked for is a fault. It now raises, naming both the format requested and the mask that came back, so the next question is answerable from the message alone. The fallback's only defender was the test asserting it, which is replaced. --- src/pychdk/device.py | 10 ++++++++-- tests/test_device.py | 12 +++++++----- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/pychdk/device.py b/src/pychdk/device.py index b2260fe..2cc289b 100644 --- a/src/pychdk/device.py +++ b/src/pychdk/device.py @@ -273,9 +273,15 @@ def _shoot_streaming(self, setup_parts, dng): while time.monotonic() < deadline: ready, formats = self._chdk.remote_capture_is_ready() if ready: + # A mask without the format we asked for is a fault, not + # a menu: the other bits are a different picture. + if not formats & fmt: + raise RuntimeError( + f"The camera has no 0x{fmt:02x} data ready; " + f"it offers 0x{formats:02x}" + ) # The request parameter is one bit, not the whole mask. - data_type = fmt if formats & fmt else formats & -formats - return self._chdk.remote_capture_get_data(data_type) + return self._chdk.remote_capture_get_data(fmt) time.sleep(0.1) raise TimeoutError("Remote capture did not complete") diff --git a/tests/test_device.py b/tests/test_device.py index 8ba88d6..3fea25d 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -114,13 +114,15 @@ def test_streaming_asks_for_a_single_data_type(self): assert dev.shoot(stream=True) == b"jpeg" mock_chdk.remote_capture_get_data.assert_called_once_with(1) - def test_streaming_falls_back_to_the_lowest_ready_bit(self): + def test_streaming_refuses_a_mask_without_the_requested_format(self): dev, mock_chdk = self._make_device() - # No JPEG on offer: RAW (0x2) and DNG header (0x4). + # No JPEG on offer: RAW (0x2) and DNG header (0x4). Returning + # raw framebuffer bytes as though they were the JPEG asked for + # would be a wrong picture, not a substitute. mock_chdk.remote_capture_is_ready.return_value = (True, 0x06) - mock_chdk.remote_capture_get_data.return_value = b"raw" - assert dev.shoot(stream=True) == b"raw" - mock_chdk.remote_capture_get_data.assert_called_once_with(2) + with pytest.raises(RuntimeError, match="0x01.*0x06"): + dev.shoot(stream=True) + mock_chdk.remote_capture_get_data.assert_not_called() def test_streaming_jpeg_is_unchanged(self): dev, mock_chdk = self._make_device() From f62fa6d1083cbf4872965e6a9bae1d30858ed457 Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 15:15:15 -0700 Subject: [PATCH 16/34] fix(flasher): keep the card's id even when parity is skipped MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Answering "skip" — or pressing Enter, or mistyping — returned from write_camera_side without writing anything. By that point main has already erased the card, so the id it went out of its way to rescue beforehand was dropped on the floor at exactly the moment the operator said the least. Declining to choose a parity is not declining to be a camera. The id is now written back whichever way the operator answers, which needed format_own_txt to accept no parity and emit the id line alone; parse_own_txt already read that shape correctly. A card with neither a parity nor an id has nothing to record, so nothing is written. Passing None as the parity used to produce a file whose first line was the word NONE, which parse_own_txt would have read as no parity at all — right answer, wrong reason, and only by luck. --- src/pychdk/util.py | 17 +++++++++++++---- tests/test_flash_chdk.py | 25 +++++++++++++++++++++++++ tests/test_util.py | 10 ++++++++++ tools/flash_chdk.py | 16 +++++++++++----- 4 files changed, 59 insertions(+), 9 deletions(-) diff --git a/src/pychdk/util.py b/src/pychdk/util.py index e9e4857..e6b49ba 100644 --- a/src/pychdk/util.py +++ b/src/pychdk/util.py @@ -124,16 +124,25 @@ def format_own_txt(side, camera_id=None): """Render the canonical OWN.TXT for a page parity and camera id. The parity is which pages the body shoots, ODD or EVEN, not a side - of the table. The id line is written only when an id is given. + of the table. Each line is written only when there is something to + put on it: an id with no parity is a valid file, since a body keeps + its identity whether or not an operator has decided which pages it + shoots, and parse_own_txt reads it back. With neither, there is + nothing to record and the result is empty. Args: - side: 'ODD' or 'EVEN', in any case. + side: 'ODD' or 'EVEN', in any case, or None for no parity. camera_id: Stable hex identity for the body, or None. Returns: - File contents as a str, with a single trailing newline. + File contents as a str with a single trailing newline, or an + empty string when there is nothing to write. """ - lines = [str(side).strip().upper()] + lines = [] + if side: + lines.append(str(side).strip().upper()) if camera_id: lines.append("id=" + str(camera_id).strip()) + if not lines: + return "" return "\n".join(lines) + "\n" diff --git a/tests/test_flash_chdk.py b/tests/test_flash_chdk.py index 0898e8c..6d4e8a6 100644 --- a/tests/test_flash_chdk.py +++ b/tests/test_flash_chdk.py @@ -72,6 +72,31 @@ def test_write_camera_side_mints_an_id_when_there_is_none( assert camera_id is not None assert "minted" in capsys.readouterr().out + def test_skipping_parity_still_writes_the_id_back( + self, tmp_path, monkeypatch, capsys, + ): + tool = _load_tool() + monkeypatch.setattr("builtins.input", lambda prompt="": "s") + tool.write_camera_side(str(tmp_path), existing_id="abc123def456") + assert (tmp_path / "OWN.TXT").read_text() == "id=abc123def456\n" + assert "kept" in capsys.readouterr().out + + def test_an_unrecognized_answer_still_writes_the_id_back( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + monkeypatch.setattr("builtins.input", lambda prompt="": "banana") + tool.write_camera_side(str(tmp_path), existing_id="abc123def456") + assert (tmp_path / "OWN.TXT").read_text() == "id=abc123def456\n" + + def test_skipping_parity_with_no_id_writes_nothing( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + monkeypatch.setattr("builtins.input", lambda prompt="": "s") + tool.write_camera_side(str(tmp_path)) + assert not (tmp_path / "OWN.TXT").exists() + def test_reading_an_id_from_an_unusable_card_is_quiet(self, monkeypatch): tool = _load_tool() diff --git a/tests/test_util.py b/tests/test_util.py index b680c58..b296100 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -136,6 +136,16 @@ def test_id_line_omitted_without_an_id(self): def test_parity_is_uppercased(self): assert format_own_txt("even", "abc123def456") == "EVEN\nid=abc123def456\n" + def test_an_id_alone_needs_no_parity(self): + assert format_own_txt(None, "3f9a1c2b7d4e") == "id=3f9a1c2b7d4e\n" + + def test_nothing_to_say_writes_nothing(self): + assert format_own_txt(None, None) == "" + + def test_round_trip_of_an_id_without_a_parity(self): + text = format_own_txt(None, "3f9a1c2b7d4e") + assert parse_own_txt(text) == (None, "3f9a1c2b7d4e") + def test_round_trip(self): text = format_own_txt("odd", "3f9a1c2b7d4e") assert parse_own_txt(text) == ("ODD", "3f9a1c2b7d4e") diff --git a/tools/flash_chdk.py b/tools/flash_chdk.py index 224ac0d..f371a3e 100755 --- a/tools/flash_chdk.py +++ b/tools/flash_chdk.py @@ -217,7 +217,10 @@ def write_camera_side(mount_point: str, existing_id: str | None = None): The file carries the page parity and a stable id for the body. An id already on the card is kept, so re-flashing a card does not - change which camera the toolkit thinks it is. + change which camera the toolkit thinks it is — including when the + operator declines to set a parity, since the card has already been + erased by then and skipping would otherwise throw the rescued id + away. A card with neither parity nor id has nothing worth writing. Args: mount_point: Where the card is mounted. @@ -232,10 +235,10 @@ def write_camera_side(mount_point: str, existing_id: str | None = None): side = "EVEN" elif choice in ("s", "skip", ""): print("Skipping camera side assignment.") - return + side = None else: print(f"Unknown choice '{choice}', skipping.") - return + side = None own_txt = Path(mount_point) / "OWN.TXT" camera_id = existing_id @@ -246,12 +249,15 @@ def write_camera_side(mount_point: str, existing_id: str | None = None): camera_id = None if camera_id: origin = "kept the id already on the card" - else: + elif side: camera_id = secrets.token_hex(6) origin = "minted a new id" + else: + # No parity to record and no identity to preserve. + return own_txt.write_text(format_own_txt(side, camera_id)) - print(f"Wrote OWN.TXT ({side}, id={camera_id}) — {origin}") + print(f"Wrote OWN.TXT ({side or 'no parity'}, id={camera_id}) — {origin}") def eject_card(disk: str): From 2ca437560f42115954ad7237c3649c136886922c Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 15:16:31 -0700 Subject: [PATCH 17/34] fix(flasher): stop rather than erase a card whose identity could not be read MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit read_existing_camera_id caught OSError and ValueError together and returned None, so a permission failure or a bad read on OWN.TXT was indistinguishable from a card that simply has no id. The card was then erased and given a fresh identity — the exact outcome the id exists to prevent, reached by way of an error nobody saw. Three cases, three answers. A card with no mountable volume is blank, which is what this tool is for, so it says so and carries on. A mounted card with no OWN.TXT genuinely has no id, so it carries on silently. A card whose OWN.TXT is there but unreadable is unknown, and unknown is not empty: it stops with a message saying the card could not be checked and that erasing it would lose the body's identity. Stopping is in read_existing_camera_id itself rather than left to a check in main, so there is no path that formats after an unknown result. --- tests/test_flash_chdk.py | 39 ++++++++++++++++++++++++++++++- tools/flash_chdk.py | 50 ++++++++++++++++++++++++++++++++-------- 2 files changed, 79 insertions(+), 10 deletions(-) diff --git a/tests/test_flash_chdk.py b/tests/test_flash_chdk.py index 6d4e8a6..4bf2301 100644 --- a/tests/test_flash_chdk.py +++ b/tests/test_flash_chdk.py @@ -97,7 +97,9 @@ def test_skipping_parity_with_no_id_writes_nothing( tool.write_camera_side(str(tmp_path)) assert not (tmp_path / "OWN.TXT").exists() - def test_reading_an_id_from_an_unusable_card_is_quiet(self, monkeypatch): + def test_a_card_that_will_not_mount_is_treated_as_blank( + self, monkeypatch, capsys, + ): tool = _load_tool() def refuse(disk): @@ -105,3 +107,38 @@ def refuse(disk): monkeypatch.setattr(tool, "get_mount_point", refuse) assert tool.read_existing_camera_id("/dev/disk9") is None + assert "blank" in capsys.readouterr().out + + def test_a_mounted_card_with_no_own_txt_has_no_id( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) + assert tool.read_existing_camera_id("/dev/disk9") is None + + def test_an_unreadable_own_txt_stops_rather_than_reporting_no_id( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + # A path that exists but cannot be read as a file: not absence. + (tmp_path / "OWN.TXT").mkdir() + monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) + with pytest.raises(SystemExit): + tool.read_existing_camera_id("/dev/disk9") + + def test_main_does_not_erase_a_card_it_could_not_check( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + (tmp_path / "OWN.TXT").mkdir() + formatted = [] + monkeypatch.setattr(tool, "download_chdk", lambda: None) + monkeypatch.setattr(tool, "find_removable_disks", lambda: []) + monkeypatch.setattr(tool, "pick_disk", lambda disks: "/dev/disk9") + monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) + monkeypatch.setattr( + tool, "format_card", lambda disk: formatted.append(disk), + ) + with pytest.raises(SystemExit): + tool.main() + assert formatted == [] diff --git a/tools/flash_chdk.py b/tools/flash_chdk.py index f371a3e..d9c6514 100755 --- a/tools/flash_chdk.py +++ b/tools/flash_chdk.py @@ -188,27 +188,59 @@ def get_mount_point(disk: str) -> str: return info.get("MountPoint", f"/Volumes/{VOLUME_LABEL}") +def _mounted_path(disk: str) -> str | None: + """Return where the card is mounted, or None if it will not mount. + + get_mount_point exits the process when diskutil fails, which is + why SystemExit is caught here. + """ + try: + return get_mount_point(disk) + except (SystemExit, ValueError): + return None + + def read_existing_camera_id(disk: str) -> str | None: """Read the camera id from a card before the card is erased. main() formats the card long before OWN.TXT could be read off it, - so the id has to be salvaged first or it is gone. A card that will - not mount, is unformatted, or carries no readable OWN.TXT simply - has no id: this never raises and never prompts. get_mount_point - exits the process when diskutil fails, which is why SystemExit is - caught here. + so the id has to be salvaged first or it is gone. That makes the + difference between "this card has no id" and "this card's id could + not be read" worth keeping: the first is an ordinary blank card, + the second means erasing would destroy an identity we cannot see. + A card that will not mount at all is the blank case — an + unformatted card is what this tool exists to format. Args: disk: /dev/diskN path. Returns: - The id already on the card, or None. + The id already on the card, or None if the card genuinely + carries none. + + Raises: + SystemExit: If OWN.TXT is there but cannot be read, so that no + caller can go on to format the card. """ + mount_point = _mounted_path(disk) + if mount_point is None: + print("Card has no mountable volume; treating it as blank.") + return None + + own_txt = Path(mount_point) / "OWN.TXT" try: - mount_point = get_mount_point(disk) - data = (Path(mount_point) / "OWN.TXT").read_bytes() - except (SystemExit, OSError, ValueError): + data = own_txt.read_bytes() + except FileNotFoundError: return None + except OSError as exc: + print(f"Could not read {own_txt}: {exc}") + print( + "Stopping before the card is erased. This card may carry a " + "camera id, and formatting it would lose that body's " + "identity. Repair the card, or delete OWN.TXT deliberately, " + "then run this again." + ) + sys.exit(1) return parse_own_txt(data)[1] From 2722b65b4df0604a19e7dee87c617b95a6f4cdc8 Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 17:47:12 -0600 Subject: [PATCH 18/34] fix(capture): download while the script runs instead of waiting for it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Waiting for the combined script to return before downloading traded one deadlock for another. CHDK can hold the capture pipeline until the host takes the data, so the script does not return until we download and we did not download until it returned. The capture ran out its thirty seconds without asking once whether data was ready — the failure looked identical to a camera that never fired. The script is started rather than waited on, and the loop services the camera while it runs: readiness first, so the data is taken the moment it exists, then the message queue, so an error arrives with its text and a false return is recognized as the refusal it is. A script that ends with nothing waiting and no data means the shot did not happen, which is worth saying immediately instead of spinning to the deadline. The single script stays, since that is what stops the shot from killing its own setup. Messages left over are drained after the download so the next capture does not read a stale one, and a failure draining cannot take away a picture already in hand. --- src/pychdk/device.py | 55 ++++++++++++++++++++------ tests/test_device.py | 92 ++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 127 insertions(+), 20 deletions(-) diff --git a/src/pychdk/device.py b/src/pychdk/device.py index 2cc289b..ba04be1 100644 --- a/src/pychdk/device.py +++ b/src/pychdk/device.py @@ -233,9 +233,15 @@ def _shoot_streaming(self, setup_parts, dng): return error instead of killing", core/ptp.h) — so a separate shoot() could terminate the init_usb_capture that was still running and leave the camera taking an ordinary card shot while - we waited for bytes that were never coming. The script returns - after the shutter, so the readiness poll below usually finds - the data waiting on its first pass. + we waited for bytes that were never coming. + + The script is started, not waited on, and that order matters: + CHDK can hold the capture pipeline until the host takes the + data, so waiting for the script to return before downloading + leaves both sides waiting on each other and the capture times + out having never once asked whether data was ready. We service + the camera while the script runs — readiness first, messages + second — and collect the script's result afterwards. Raises: RuntimeError: If the camera refuses to initialize remote @@ -261,14 +267,9 @@ def _shoot_streaming(self, setup_parts, dng): "shoot(); " "return true" ) - # Only an explicit false is a refusal: an older CHDK returns - # nothing at all, and nil must not be read as failure. - if self.lua_execute(script, timeout=30) is False: - raise RuntimeError( - "The camera refused to initialize remote capture: " - "init_usb_capture returned false" - ) + script_id = self._chdk.execute_script(script) + image = None deadline = time.monotonic() + 30 while time.monotonic() < deadline: ready, formats = self._chdk.remote_capture_is_ready() @@ -281,9 +282,39 @@ def _shoot_streaming(self, setup_parts, dng): f"it offers 0x{formats:02x}" ) # The request parameter is one bit, not the whole mask. - return self._chdk.remote_capture_get_data(fmt) + image = self._chdk.remote_capture_get_data(fmt) + break + + running, has_msgs = self._chdk.get_script_status() + if has_msgs: + msg = self._chdk.read_script_message() + if msg.script_id == script_id: + if msg.msg_type == MessageType.ERR: + raise RuntimeError(f"Capture script failed: {msg.value}") + # Only an explicit false is a refusal: an older CHDK + # returns nil, which must not be read as failure. + if msg.msg_type == MessageType.RET and msg.value is False: + raise RuntimeError( + "The camera refused to initialize remote " + "capture: init_usb_capture returned false" + ) + continue + if not running: + raise RuntimeError( + "The capture script finished without producing a capture" + ) time.sleep(0.1) - raise TimeoutError("Remote capture did not complete") + + if image is None: + raise TimeoutError("Remote capture did not complete") + + # Clear what the script left behind so the next capture does not + # read a stale message — but never at the cost of this picture. + try: + self._chdk.drain_messages() + except Exception: + pass + return image def _shoot_standard(self, setup_parts, download, remove): """Capture to SD card, optionally download and delete.""" diff --git a/tests/test_device.py b/tests/test_device.py index 3fea25d..3962d93 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -7,6 +7,12 @@ import pytest import pychdk from pychdk import device +from pychdk.chdk import ( + MessageType, + ScriptDataType, + ScriptErrorType, + ScriptMessage, +) from pychdk.device import ChdkDevice, list_devices, DeviceInfo @@ -80,32 +86,102 @@ def test_streamed_dng_is_refused(self): with pytest.raises(NotImplementedError, match="DNG"): dev.shoot(dng=True, stream=True) + def _ready_camera(self, mock_chdk, formats=0x01, data=b"jpeg"): + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = (True, formats) + mock_chdk.remote_capture_get_data.return_value = data + def test_streaming_initializes_and_shoots_in_one_script(self): dev, mock_chdk = self._make_device() - mock_chdk.execute_lua_wait.return_value = True - mock_chdk.remote_capture_is_ready.return_value = (True, 0x01) - mock_chdk.remote_capture_get_data.return_value = b"jpeg" + self._ready_camera(mock_chdk) assert dev.shoot(stream=True) == b"jpeg" # One script: a second one would kill the first, setup included. - assert mock_chdk.execute_lua_wait.call_count == 1 - script = mock_chdk.execute_lua_wait.call_args[0][0] + assert mock_chdk.execute_script.call_count == 1 + script = mock_chdk.execute_script.call_args[0][0] assert "init_usb_capture" in script assert "shoot()" in script + def test_streaming_downloads_without_waiting_for_the_script(self): + dev, mock_chdk = self._make_device() + self._ready_camera(mock_chdk) + assert dev.shoot(stream=True) == b"jpeg" + # Waiting for the script's return before downloading deadlocks: + # CHDK holds the pipeline until the host takes the data. + mock_chdk.execute_lua_wait.assert_not_called() + assert mock_chdk.remote_capture_is_ready.call_count >= 1 + def test_streaming_raises_when_the_camera_refuses_to_initialize(self): dev, mock_chdk = self._make_device() - mock_chdk.execute_lua_wait.return_value = False + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = (False, 0) + mock_chdk.get_script_status.return_value = (True, True) + # init_usb_capture returned false, so the script returns false. + mock_chdk.read_script_message.return_value = ScriptMessage( + MessageType.RET, ScriptDataType.BOOLEAN, 7, False, + ) with pytest.raises(RuntimeError, match="initialize remote capture"): dev.shoot(stream=True) + def test_streaming_raises_a_script_error_with_its_text(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = (False, 0) + mock_chdk.get_script_status.return_value = (True, True) + mock_chdk.read_script_message.return_value = ScriptMessage( + MessageType.ERR, ScriptErrorType.RUN, 7, "no such function", + ) + with pytest.raises(RuntimeError, match="no such function"): + dev.shoot(stream=True) + + def test_streaming_ignores_a_message_from_another_script(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.side_effect = [ + (False, 0), (True, 0x01), + ] + mock_chdk.get_script_status.return_value = (True, True) + mock_chdk.read_script_message.return_value = ScriptMessage( + MessageType.ERR, ScriptErrorType.RUN, 3, "stale error", + ) + mock_chdk.remote_capture_get_data.return_value = b"jpeg" + assert dev.shoot(stream=True) == b"jpeg" + def test_streaming_tolerates_a_camera_that_returns_nothing(self): dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.side_effect = [ + (False, 0), (True, 0x01), + ] + mock_chdk.get_script_status.return_value = (True, True) # An older CHDK returns nil, which is not a refusal. - mock_chdk.execute_lua_wait.return_value = None - mock_chdk.remote_capture_is_ready.return_value = (True, 0x01) + mock_chdk.read_script_message.return_value = ScriptMessage( + MessageType.RET, ScriptDataType.NIL, 7, None, + ) mock_chdk.remote_capture_get_data.return_value = b"jpeg" assert dev.shoot(stream=True) == b"jpeg" + def test_streaming_stops_when_the_script_ends_without_a_capture(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = (False, 0) + mock_chdk.get_script_status.return_value = (False, False) + with pytest.raises(RuntimeError, match="without producing a capture"): + dev.shoot(stream=True) + # Promptly, rather than spinning out the thirty-second deadline. + assert mock_chdk.remote_capture_is_ready.call_count == 1 + + def test_streaming_drains_the_script_after_downloading(self): + dev, mock_chdk = self._make_device() + self._ready_camera(mock_chdk) + assert dev.shoot(stream=True) == b"jpeg" + mock_chdk.drain_messages.assert_called_once() + + def test_a_failure_draining_does_not_lose_the_picture(self): + dev, mock_chdk = self._make_device() + self._ready_camera(mock_chdk) + mock_chdk.drain_messages.side_effect = RuntimeError("late boom") + assert dev.shoot(stream=True) == b"jpeg" + def test_streaming_asks_for_a_single_data_type(self): dev, mock_chdk = self._make_device() # JPEG and RAW both ready; the request parameter takes one bit. From 2c1213a6fc58602634ffde92c57eecc4be9652bf Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 17:48:13 -0600 Subject: [PATCH 19/34] fix(flasher): never erase a card whose filesystem could not be inspected MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit _mounted_path collapsed two different answers into None: a card with nothing on it, and a card whose volume we failed to mount or whose diskutil output we failed to parse. main read None as "blank" and went on to erase, so a reader that dropped out at the wrong moment cost a body its identity — the same failure the id was added to prevent, reached by a different route. The card is now asked what it holds before that conclusion is drawn. diskutil info exits nonzero for a partition that is not there, so a card reporting no filesystem is genuinely blank and formatting one is the point of this tool. A card that reports a volume it will not then let us read is not blank, it is unexamined, and it stops the run with a message saying so. The stop stays inside read_existing_camera_id, so there is still no path that formats after an unknown answer. --- tests/test_flash_chdk.py | 40 +++++++++++++++++++++++++++++++++++++++- tools/flash_chdk.py | 39 +++++++++++++++++++++++++++++++++------ 2 files changed, 72 insertions(+), 7 deletions(-) diff --git a/tests/test_flash_chdk.py b/tests/test_flash_chdk.py index 4bf2301..c25b80b 100644 --- a/tests/test_flash_chdk.py +++ b/tests/test_flash_chdk.py @@ -97,7 +97,7 @@ def test_skipping_parity_with_no_id_writes_nothing( tool.write_camera_side(str(tmp_path)) assert not (tmp_path / "OWN.TXT").exists() - def test_a_card_that_will_not_mount_is_treated_as_blank( + def test_a_card_with_no_filesystem_is_treated_as_blank( self, monkeypatch, capsys, ): tool = _load_tool() @@ -106,14 +106,52 @@ def refuse(disk): raise SystemExit(1) monkeypatch.setattr(tool, "get_mount_point", refuse) + monkeypatch.setattr(tool, "_card_holds_a_volume", lambda disk: False) assert tool.read_existing_camera_id("/dev/disk9") is None assert "blank" in capsys.readouterr().out + def test_a_volume_that_will_not_mount_stops_the_run( + self, monkeypatch, capsys, + ): + tool = _load_tool() + + def refuse(disk): + raise SystemExit(1) + + monkeypatch.setattr(tool, "get_mount_point", refuse) + # diskutil says there is a filesystem, but it would not mount. + monkeypatch.setattr(tool, "_card_holds_a_volume", lambda disk: True) + with pytest.raises(SystemExit): + tool.read_existing_camera_id("/dev/disk9") + assert "could not be inspected" in capsys.readouterr().out + + def test_main_does_not_erase_a_volume_it_could_not_mount( + self, monkeypatch, + ): + tool = _load_tool() + formatted = [] + + def refuse(disk): + raise SystemExit(1) + + monkeypatch.setattr(tool, "download_chdk", lambda: None) + monkeypatch.setattr(tool, "find_removable_disks", lambda: []) + monkeypatch.setattr(tool, "pick_disk", lambda disks: "/dev/disk9") + monkeypatch.setattr(tool, "get_mount_point", refuse) + monkeypatch.setattr(tool, "_card_holds_a_volume", lambda disk: True) + monkeypatch.setattr( + tool, "format_card", lambda disk: formatted.append(disk), + ) + with pytest.raises(SystemExit): + tool.main() + assert formatted == [] + def test_a_mounted_card_with_no_own_txt_has_no_id( self, tmp_path, monkeypatch, ): tool = _load_tool() monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) + monkeypatch.setattr(tool, "_card_holds_a_volume", lambda disk: True) assert tool.read_existing_camera_id("/dev/disk9") is None def test_an_unreadable_own_txt_stops_rather_than_reporting_no_id( diff --git a/tools/flash_chdk.py b/tools/flash_chdk.py index d9c6514..21c204f 100755 --- a/tools/flash_chdk.py +++ b/tools/flash_chdk.py @@ -200,6 +200,23 @@ def _mounted_path(disk: str) -> str | None: return None +def _card_holds_a_volume(disk: str) -> bool: + """Ask diskutil whether the card has a first partition at all. + + diskutil info exits nonzero for a partition that does not exist, so + a card with no filesystem answers False here. That is the only + card safe to erase without looking at it first. + + Args: + disk: /dev/diskN path. + + Returns: + True if the card reports a volume, False if it holds none. + """ + result = _run(["diskutil", "info", "-plist", disk + "s1"], check=False) + return result.returncode == 0 + + def read_existing_camera_id(disk: str) -> str | None: """Read the camera id from a card before the card is erased. @@ -208,8 +225,10 @@ def read_existing_camera_id(disk: str) -> str | None: difference between "this card has no id" and "this card's id could not be read" worth keeping: the first is an ordinary blank card, the second means erasing would destroy an identity we cannot see. - A card that will not mount at all is the blank case — an - unformatted card is what this tool exists to format. + A card that reports no filesystem at all is genuinely blank, and + formatting one is what this tool is for. A card that reports a + volume we then could not mount or read is not blank — it is + unexamined, and erasing it would be a guess. Args: disk: /dev/diskN path. @@ -219,13 +238,21 @@ def read_existing_camera_id(disk: str) -> str | None: carries none. Raises: - SystemExit: If OWN.TXT is there but cannot be read, so that no - caller can go on to format the card. + SystemExit: If the card holds a filesystem that could not be + inspected, so that no caller can go on to format it. """ mount_point = _mounted_path(disk) if mount_point is None: - print("Card has no mountable volume; treating it as blank.") - return None + if not _card_holds_a_volume(disk): + print("Card holds no filesystem; treating it as blank.") + return None + print( + "The card holds a filesystem that could not be inspected. " + "Stopping before it is erased: it may carry a camera id, " + "and formatting would lose that body's identity. Check the " + "card and the reader, then run this again." + ) + sys.exit(1) own_txt = Path(mount_point) / "OWN.TXT" try: From c10e9c939eec0cdb40149e3b7d155e2c7d955210 Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 17:49:21 -0600 Subject: [PATCH 20/34] fix(flasher): leave parity alone when the operator skips it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Only the id was salvaged before the format, so skipping the parity prompt on a card that already said EVEN wrote back an id and no parity. Skip should mean "leave the assignment as it is", and instead it was the one answer that quietly erased half of it — the operator declines to make a decision and the tool makes one for them. Both fields are now read off the card before it is erased, and both are written back when the prompt is skipped or misanswered. Choosing a parity still overrides whatever the card said, since that is the point of choosing. A card that had no parity to begin with has none to preserve, so the id-only file stays exactly as it was. --- tests/test_flash_chdk.py | 50 +++++++++++++++++++++++++++++----------- tools/flash_chdk.py | 43 +++++++++++++++++++++------------- 2 files changed, 64 insertions(+), 29 deletions(-) diff --git a/tests/test_flash_chdk.py b/tests/test_flash_chdk.py index c25b80b..bab33e4 100644 --- a/tests/test_flash_chdk.py +++ b/tests/test_flash_chdk.py @@ -29,16 +29,17 @@ def fake(*args, **kwargs): return result return fake - def fake_write(mount_point, existing_id=None): + def fake_write(mount_point, existing_side=None, existing_id=None): calls.append("write_camera_side") + received["existing_side"] = existing_side received["existing_id"] = existing_id monkeypatch.setattr(tool, "download_chdk", record("download_chdk")) monkeypatch.setattr(tool, "find_removable_disks", record("find", [])) monkeypatch.setattr(tool, "pick_disk", record("pick_disk", "/dev/disk9")) monkeypatch.setattr( - tool, "read_existing_camera_id", - record("read_existing_camera_id", "abc123def456"), + tool, "read_existing_own_txt", + record("read_existing_own_txt", ("EVEN", "abc123def456")), ) monkeypatch.setattr(tool, "format_card", record("format_card", "/Volumes/X")) monkeypatch.setattr(tool, "extract_chdk", record("extract_chdk")) @@ -49,8 +50,9 @@ def fake_write(mount_point, existing_id=None): tool.main() - assert calls.index("read_existing_camera_id") < calls.index("format_card") + assert calls.index("read_existing_own_txt") < calls.index("format_card") assert received["existing_id"] == "abc123def456" + assert received["existing_side"] == "EVEN" def test_write_camera_side_keeps_the_id_it_is_handed( self, tmp_path, monkeypatch, capsys, @@ -72,23 +74,45 @@ def test_write_camera_side_mints_an_id_when_there_is_none( assert camera_id is not None assert "minted" in capsys.readouterr().out - def test_skipping_parity_still_writes_the_id_back( + def test_skipping_parity_leaves_the_existing_assignment_alone( self, tmp_path, monkeypatch, capsys, ): tool = _load_tool() monkeypatch.setattr("builtins.input", lambda prompt="": "s") - tool.write_camera_side(str(tmp_path), existing_id="abc123def456") - assert (tmp_path / "OWN.TXT").read_text() == "id=abc123def456\n" + tool.write_camera_side( + str(tmp_path), existing_side="EVEN", existing_id="abc123def456", + ) + assert (tmp_path / "OWN.TXT").read_text() == "EVEN\nid=abc123def456\n" assert "kept" in capsys.readouterr().out - def test_an_unrecognized_answer_still_writes_the_id_back( + def test_skipping_parity_on_a_card_that_had_none_writes_the_id_alone( self, tmp_path, monkeypatch, ): tool = _load_tool() - monkeypatch.setattr("builtins.input", lambda prompt="": "banana") + monkeypatch.setattr("builtins.input", lambda prompt="": "s") tool.write_camera_side(str(tmp_path), existing_id="abc123def456") assert (tmp_path / "OWN.TXT").read_text() == "id=abc123def456\n" + def test_an_unrecognized_answer_leaves_the_assignment_alone( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + monkeypatch.setattr("builtins.input", lambda prompt="": "banana") + tool.write_camera_side( + str(tmp_path), existing_side="ODD", existing_id="abc123def456", + ) + assert (tmp_path / "OWN.TXT").read_text() == "ODD\nid=abc123def456\n" + + def test_choosing_a_parity_overrides_the_one_on_the_card( + self, tmp_path, monkeypatch, + ): + tool = _load_tool() + monkeypatch.setattr("builtins.input", lambda prompt="": "o") + tool.write_camera_side( + str(tmp_path), existing_side="EVEN", existing_id="abc123def456", + ) + assert (tmp_path / "OWN.TXT").read_text() == "ODD\nid=abc123def456\n" + def test_skipping_parity_with_no_id_writes_nothing( self, tmp_path, monkeypatch, ): @@ -107,7 +131,7 @@ def refuse(disk): monkeypatch.setattr(tool, "get_mount_point", refuse) monkeypatch.setattr(tool, "_card_holds_a_volume", lambda disk: False) - assert tool.read_existing_camera_id("/dev/disk9") is None + assert tool.read_existing_own_txt("/dev/disk9") == (None, None) assert "blank" in capsys.readouterr().out def test_a_volume_that_will_not_mount_stops_the_run( @@ -122,7 +146,7 @@ def refuse(disk): # diskutil says there is a filesystem, but it would not mount. monkeypatch.setattr(tool, "_card_holds_a_volume", lambda disk: True) with pytest.raises(SystemExit): - tool.read_existing_camera_id("/dev/disk9") + tool.read_existing_own_txt("/dev/disk9") assert "could not be inspected" in capsys.readouterr().out def test_main_does_not_erase_a_volume_it_could_not_mount( @@ -152,7 +176,7 @@ def test_a_mounted_card_with_no_own_txt_has_no_id( tool = _load_tool() monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) monkeypatch.setattr(tool, "_card_holds_a_volume", lambda disk: True) - assert tool.read_existing_camera_id("/dev/disk9") is None + assert tool.read_existing_own_txt("/dev/disk9") == (None, None) def test_an_unreadable_own_txt_stops_rather_than_reporting_no_id( self, tmp_path, monkeypatch, @@ -162,7 +186,7 @@ def test_an_unreadable_own_txt_stops_rather_than_reporting_no_id( (tmp_path / "OWN.TXT").mkdir() monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) with pytest.raises(SystemExit): - tool.read_existing_camera_id("/dev/disk9") + tool.read_existing_own_txt("/dev/disk9") def test_main_does_not_erase_a_card_it_could_not_check( self, tmp_path, monkeypatch, diff --git a/tools/flash_chdk.py b/tools/flash_chdk.py index 21c204f..7064c24 100755 --- a/tools/flash_chdk.py +++ b/tools/flash_chdk.py @@ -217,8 +217,8 @@ def _card_holds_a_volume(disk: str) -> bool: return result.returncode == 0 -def read_existing_camera_id(disk: str) -> str | None: - """Read the camera id from a card before the card is erased. +def read_existing_own_txt(disk: str) -> tuple[str | None, str | None]: + """Read a card's parity and camera id before the card is erased. main() formats the card long before OWN.TXT could be read off it, so the id has to be salvaged first or it is gone. That makes the @@ -233,8 +233,12 @@ def read_existing_camera_id(disk: str) -> str | None: Args: disk: /dev/diskN path. + Both fields are salvaged, not just the id: an operator who skips + the parity prompt means "leave the assignment alone", which is only + possible if we still know what the assignment was. + Returns: - The id already on the card, or None if the card genuinely + Tuple of (side, camera_id), each None if the card genuinely carries none. Raises: @@ -245,7 +249,7 @@ def read_existing_camera_id(disk: str) -> str | None: if mount_point is None: if not _card_holds_a_volume(disk): print("Card holds no filesystem; treating it as blank.") - return None + return None, None print( "The card holds a filesystem that could not be inspected. " "Stopping before it is erased: it may carry a camera id, " @@ -258,7 +262,7 @@ def read_existing_camera_id(disk: str) -> str | None: try: data = own_txt.read_bytes() except FileNotFoundError: - return None + return None, None except OSError as exc: print(f"Could not read {own_txt}: {exc}") print( @@ -268,10 +272,11 @@ def read_existing_camera_id(disk: str) -> str | None: "then run this again." ) sys.exit(1) - return parse_own_txt(data)[1] + return parse_own_txt(data) -def write_camera_side(mount_point: str, existing_id: str | None = None): +def write_camera_side(mount_point: str, existing_side: str | None = None, + existing_id: str | None = None): """Ask which pages this camera shoots and write OWN.TXT. The file carries the page parity and a stable id for the body. An @@ -283,9 +288,12 @@ def write_camera_side(mount_point: str, existing_id: str | None = None): Args: mount_point: Where the card is mounted. + existing_side: Parity read off the card before it was erased. + Skipping the prompt keeps it, so a card that said EVEN + still says EVEN. existing_id: Id read off the card before it was erased, if any. - Falls back to reading OWN.TXT here, for a card that was not - formatted in this run. + Both fall back to reading OWN.TXT here, for a card that was + not formatted in this run. """ choice = input("Which pages does this camera shoot? [o]dd / [e]ven / [s]kip: ").strip().lower() if choice in ("o", "odd"): @@ -294,18 +302,20 @@ def write_camera_side(mount_point: str, existing_id: str | None = None): side = "EVEN" elif choice in ("s", "skip", ""): print("Skipping camera side assignment.") - side = None + side = existing_side else: print(f"Unknown choice '{choice}', skipping.") - side = None + side = existing_side own_txt = Path(mount_point) / "OWN.TXT" camera_id = existing_id - if not camera_id: + if side is None or camera_id is None: try: - camera_id = parse_own_txt(own_txt.read_bytes())[1] + on_card_side, on_card_id = parse_own_txt(own_txt.read_bytes()) except OSError: - camera_id = None + on_card_side, on_card_id = None, None + side = side or on_card_side + camera_id = camera_id or on_card_id if camera_id: origin = "kept the id already on the card" elif side: @@ -330,13 +340,14 @@ def main(): disks = find_removable_disks() disk = pick_disk(disks) # Salvage the body's identity before eraseDisk takes it away. - existing_id = read_existing_camera_id(disk) + existing_side, existing_id = read_existing_own_txt(disk) mount_point = format_card(disk) extract_chdk(zip_path, mount_point) patch_boot_sector(disk) mount_point = get_mount_point(disk) - write_camera_side(mount_point, existing_id=existing_id) + write_camera_side(mount_point, existing_side=existing_side, + existing_id=existing_id) eject_card(disk) print("Done! Lock the SD card and insert into camera.") From 6cb9e7bf9dae657607e8a06d83b0de2a02af53ba Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 17:50:10 -0600 Subject: [PATCH 21/34] fix(script): raise on a script that fails after it starts wait_for_script watched the running flag and nothing else. A script that started cleanly and then failed cleared that flag exactly like one that succeeded, so _shoot_standard treated a failed shot as a finished one and went looking for a file that was never written. The error stayed in the queue for whichever call read it next, which is how a failure ends up reported against the wrong operation. It now reads waiting messages while it waits and raises on an error with its kind and text, the same way the streaming loop does. _shoot_standard needs no change to benefit: it already waits here. That closes the last path where a script could fail in silence. --- src/pychdk/chdk.py | 24 ++++++++++++++++++++++-- tests/test_chdk.py | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/src/pychdk/chdk.py b/src/pychdk/chdk.py index 4997c35..87df49e 100644 --- a/src/pychdk/chdk.py +++ b/src/pychdk/chdk.py @@ -428,10 +428,30 @@ def remote_capture_get_data(self, format_flag): ) def wait_for_script(self, timeout=30.0): - """Wait until no script is running on the camera.""" + """Wait until no script is running on the camera. + + Reads waiting messages as it goes, rather than watching only + the running flag: a script that starts and then fails clears + that flag like any other, so waiting without reading the queue + reported a failed capture as a clean one and left the error + behind for the next caller to trip over. + + Args: + timeout: Max seconds to wait for the script to finish. + + Raises: + RuntimeError: If the script reported an error. + TimeoutError: If the script is still running at the deadline. + """ deadline = time.monotonic() + timeout while time.monotonic() < deadline: - running, _ = self.get_script_status() + running, has_msgs = self.get_script_status() + if has_msgs: + msg = self.read_script_message() + if msg.msg_type == MessageType.ERR: + kind = _script_error_name(msg.data_type) + raise RuntimeError(f"Script error ({kind}): {msg.value}") + continue if not running: return time.sleep(0.5) diff --git a/tests/test_chdk.py b/tests/test_chdk.py index 15b2fc1..d7deeb2 100644 --- a/tests/test_chdk.py +++ b/tests/test_chdk.py @@ -186,6 +186,46 @@ def test_a_refused_script_fails_without_waiting(self): assert session.transaction.call_count == 2 +class TestWaitForScript: + """Waiting must notice a script that fails after it starts.""" + + def _make_chdk(self): + mock_session = MagicMock() + return ChdkPTP(mock_session), mock_session + + def test_a_script_that_fails_after_starting_raises_with_its_text(self): + chdk, session = self._make_chdk() + session.transaction.side_effect = [ + # running, message waiting + ([0b11], b""), + ([MessageType.ERR, ScriptErrorType.RUN, 7, 13], + b"shoot failed\x00"), + ] + with pytest.raises(RuntimeError, match="shoot failed"): + chdk.wait_for_script(timeout=5) + + def test_a_clean_completion_still_returns(self): + chdk, session = self._make_chdk() + session.transaction.return_value = ([0], b"") + assert chdk.wait_for_script(timeout=5) is None + + def test_a_return_message_is_not_an_error(self): + chdk, session = self._make_chdk() + session.transaction.side_effect = [ + ([0b10], b""), # not running, message waiting + ([MessageType.RET, ScriptDataType.INTEGER, 7, 4], + struct.pack(" Date: Wed, 9 Sep 2026 17:58:38 -0600 Subject: [PATCH 22/34] fix(capture): let the caller decide what an uninitialized capture means MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit remote_capture_is_ready raised the moment CHDK answered 0x10000000, and that was the wrong place to decide. CHDK acknowledges a script as loaded and scheduled, not as run, so the first readiness poll can legitimately arrive before init_usb_capture has executed and get that answer for no reason worse than being early. We raised on it before the loop had looked at the script's status even once — and when the initialization really had failed, its error or its false return was sitting unread in the queue while we reported the status instead. The protocol layer now reports the status as itself, which lets a caller tell "not initialized" from "nothing ready yet", and the decision moves to _shoot_streaming, which is the only place that knows whether the script has had its chance. It treats the status as "not yet" while the script may still be starting, keeps servicing the message queue in the same pass so a real failure is reported in the script's own words, and calls it a failure once the script has ended without initializing or a bounded grace has run out. --- src/pychdk/chdk.py | 34 ++++++++++++++-------------- src/pychdk/device.py | 22 +++++++++++++++++- tests/test_chdk.py | 8 ++++--- tests/test_device.py | 53 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 96 insertions(+), 21 deletions(-) diff --git a/src/pychdk/chdk.py b/src/pychdk/chdk.py index 87df49e..85b02e7 100644 --- a/src/pychdk/chdk.py +++ b/src/pychdk/chdk.py @@ -322,18 +322,23 @@ def remote_capture_is_ready(self): CHDK's PTP_CHDK_RemoteCaptureIsReady (core/ptp.h) returns a status in param1: 0 is not ready yet, 0x10000000 says remote - capture was never initialized, and any other value is a bitmask - of the PTP_CHDK_CAPTURE_* data types that are ready. The - uninitialized status is not a bitmask and must not be passed - back as one. + capture is not initialized, and any other value is a bitmask of + the PTP_CHDK_CAPTURE_* data types that are ready. + + The uninitialized status is reported rather than raised on, + because on its own it does not mean anything is wrong. CHDK + acknowledges a script as loaded and scheduled, not as run, so a + poll can arrive before init_usb_capture has executed and get + this answer perfectly legitimately. It is a failure only once + the script has had its chance — which the caller knows and this + method does not. A caller seeing it after the script has ended + is looking at an initialization that never happened. Returns: - Tuple of (is_ready, formats), where formats is a bitmask of - the data types ready to download. - - Raises: - RuntimeError: If the camera says remote capture was never - initialized. + Tuple of (is_ready, status). status is REMOTE_CAP_NOTSET + when the camera reports remote capture uninitialized, 0 + when there is simply nothing ready yet, and otherwise a + bitmask of the data types ready to download. """ params, _ = self._session.transaction( OperationCode.CHDK, @@ -341,13 +346,8 @@ def remote_capture_is_ready(self): receive_data=False, ) status = params[0] if params else 0 - if status == REMOTE_CAP_NOTSET: - raise RuntimeError( - "Remote capture is not initialized on the camera: " - "init_usb_capture must run before the shot" - ) - if status == 0: - return False, 0 + if status == 0 or status == REMOTE_CAP_NOTSET: + return False, status return True, status def remote_capture_get_chunk(self, format_flag): diff --git a/src/pychdk/device.py b/src/pychdk/device.py index ba04be1..f207ccf 100644 --- a/src/pychdk/device.py +++ b/src/pychdk/device.py @@ -16,12 +16,20 @@ ChdkPTP, MessageType, REMOTE_CAP_JPEG, + REMOTE_CAP_NOTSET, REMOTE_CAP_RAW, REMOTE_CAP_DNG_HDR, ) from pychdk.util import shutter_to_tv96, iso_to_sv96 +# How long a capture script is allowed to still be starting before an +# "uninitialized" answer counts against it. CHDK acknowledges a script +# as scheduled, not as run, so the first polls can legitimately land +# before init_usb_capture has executed. +CAPTURE_INIT_GRACE = 5.0 + + DeviceInfo = namedtuple("DeviceInfo", [ "vendor_id", "product_id", "bus_num", "device_num", "serial_num", ]) @@ -271,8 +279,10 @@ def _shoot_streaming(self, setup_parts, dng): image = None deadline = time.monotonic() + 30 + init_deadline = time.monotonic() + CAPTURE_INIT_GRACE while time.monotonic() < deadline: - ready, formats = self._chdk.remote_capture_is_ready() + ready, status = self._chdk.remote_capture_is_ready() + formats = status if ready: # A mask without the format we asked for is a fault, not # a menu: the other bits are a different picture. @@ -299,6 +309,16 @@ def _shoot_streaming(self, setup_parts, dng): "capture: init_usb_capture returned false" ) continue + + # Checked after the queue, so a script that explained itself + # is reported by its own words rather than by this status. + if status == REMOTE_CAP_NOTSET and ( + not running or time.monotonic() >= init_deadline + ): + raise RuntimeError( + "The camera never initialized remote capture: " + "init_usb_capture did not take effect" + ) if not running: raise RuntimeError( "The capture script finished without producing a capture" diff --git a/tests/test_chdk.py b/tests/test_chdk.py index d7deeb2..78eff17 100644 --- a/tests/test_chdk.py +++ b/tests/test_chdk.py @@ -4,6 +4,7 @@ import pytest from pychdk.chdk import ( ChdkPTP, + REMOTE_CAP_NOTSET, ChdkCommand, ScriptLanguage, ScriptDataType, @@ -251,12 +252,13 @@ def _make_chdk(self): mock_session = MagicMock() return ChdkPTP(mock_session), mock_session - def test_uninitialized_capture_raises(self): + def test_uninitialized_is_reported_rather_than_raised(self): chdk, session = self._make_chdk() # 0x10000000 is PTP_CHDK_CAPTURE_NOTSET, not a data type bitmask. + # Only the caller knows whether the script has had its chance, + # so this reports the status instead of deciding on it. session.transaction.return_value = ([0x10000000], b"") - with pytest.raises(RuntimeError, match="init_usb_capture"): - chdk.remote_capture_is_ready() + assert chdk.remote_capture_is_ready() == (False, REMOTE_CAP_NOTSET) def test_status_zero_is_not_ready(self): chdk, session = self._make_chdk() diff --git a/tests/test_device.py b/tests/test_device.py index 3962d93..89e386e 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -9,6 +9,7 @@ from pychdk import device from pychdk.chdk import ( MessageType, + REMOTE_CAP_NOTSET, ScriptDataType, ScriptErrorType, ScriptMessage, @@ -160,6 +161,58 @@ def test_streaming_tolerates_a_camera_that_returns_nothing(self): mock_chdk.remote_capture_get_data.return_value = b"jpeg" assert dev.shoot(stream=True) == b"jpeg" + def test_an_early_not_initialized_poll_is_not_a_failure(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + # CHDK acknowledges a script as scheduled, not as run, so the + # first poll can land before init_usb_capture has executed. + mock_chdk.remote_capture_is_ready.side_effect = [ + (False, REMOTE_CAP_NOTSET), + (True, 0x01), + ] + mock_chdk.get_script_status.return_value = (True, False) + mock_chdk.remote_capture_get_data.return_value = b"jpeg" + assert dev.shoot(stream=True) == b"jpeg" + + def test_not_initialized_after_the_script_ended_is_a_failure(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = ( + False, REMOTE_CAP_NOTSET, + ) + mock_chdk.get_script_status.return_value = (False, False) + with pytest.raises(RuntimeError, match="never initialized"): + dev.shoot(stream=True) + assert mock_chdk.remote_capture_is_ready.call_count == 1 + + def test_an_initialization_failure_beats_the_early_status(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + # The status arrives first, but the script's own false is the + # better answer and must be the one reported. + mock_chdk.remote_capture_is_ready.return_value = ( + False, REMOTE_CAP_NOTSET, + ) + mock_chdk.get_script_status.return_value = (True, True) + mock_chdk.read_script_message.return_value = ScriptMessage( + MessageType.RET, ScriptDataType.BOOLEAN, 7, False, + ) + with pytest.raises(RuntimeError, match="refused to initialize"): + dev.shoot(stream=True) + + def test_a_script_error_beats_the_early_status(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = ( + False, REMOTE_CAP_NOTSET, + ) + mock_chdk.get_script_status.return_value = (True, True) + mock_chdk.read_script_message.return_value = ScriptMessage( + MessageType.ERR, ScriptErrorType.RUN, 7, "no such function", + ) + with pytest.raises(RuntimeError, match="no such function"): + dev.shoot(stream=True) + def test_streaming_stops_when_the_script_ends_without_a_capture(self): dev, mock_chdk = self._make_device() mock_chdk.execute_script.return_value = 7 From febc7845abf94ee9b2a34cffab97720441fd484c Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 17:59:58 -0600 Subject: [PATCH 23/34] fix(flasher): read the whole card's layout before calling it blank MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit _card_holds_a_volume asked diskutil about diskNs1 and drew a conclusion about the whole card from the answer. Both directions were wrong. An existing but unformatted first partition reports fine and then refuses to mount, and a missing diskNs1 proves nothing, since the filesystem may sit on the whole device or on another partition — diskutil info inspects whatever it is pointed at, it does not test for a filesystem. A card we simply failed to inspect was being called blank and erased. It now reads the whole device's layout and judges from every entry. Three outcomes, not two: a layout that positively shows an empty card may be erased, a layout showing any filesystem must be mounted and read first, and anything unreadable or unrecognized is unknown and stops the run. Unknown never falls through to blank, which is the property that matters — the cost of stopping is a rerun, the cost of guessing is a body's identity. The tests parse a real `diskutil list -plist` capture from this machine rather than stubbing the classification. A genuinely blank card cannot be produced here, so its layout is written as the captured structure with the partition map removed, and the test file says so: that one still wants confirming at the bench. --- tests/test_flash_chdk.py | 123 +++++++++++++++++++++++++++++++++++++-- tools/flash_chdk.py | 64 +++++++++++++++----- 2 files changed, 170 insertions(+), 17 deletions(-) diff --git a/tests/test_flash_chdk.py b/tests/test_flash_chdk.py index bab33e4..91e7587 100644 --- a/tests/test_flash_chdk.py +++ b/tests/test_flash_chdk.py @@ -1,5 +1,7 @@ """The flasher must not change a body's identity when a card is re-flashed.""" import importlib.util +import plistlib +import subprocess from pathlib import Path import pytest @@ -8,6 +10,64 @@ TOOL = Path(__file__).resolve().parent.parent / "tools" / "flash_chdk.py" +# Real `diskutil list -plist` output, captured on macOS 15 from a disk +# with a GUID partition scheme. The shapes below are taken from it: +# AllDisksAndPartitions holds whole disks, each with a Content naming +# the partition scheme and a Partitions list (APFS containers add +# APFSVolumes). A genuinely blank card — no partition map at all — +# could not be captured here, since it needs an SD card in a reader; +# _blank_layout() is this structure with the layout emptied, and the +# real thing is still worth one check at the bench. +PARTITIONED_LAYOUT = { + "AllDisks": ["disk4", "disk4s1"], + "AllDisksAndPartitions": [ + { + "Content": "GUID_partition_scheme", + "DeviceIdentifier": "disk4", + "OSInternal": False, + "Partitions": [ + { + "Content": "Apple_HFS", + "DeviceIdentifier": "disk4s1", + "DiskUUID": "12EEA754-2CA1-4EA7-A1B4-54DF40936F21", + "Size": 15931539456, + }, + ], + "Size": 15931539456, + }, + ], + "VolumesFromDisks": [], + "WholeDisks": ["disk4"], +} + + +def _blank_layout(): + """PARTITIONED_LAYOUT with no partition map and no filesystem.""" + return { + "AllDisks": ["disk4"], + "AllDisksAndPartitions": [ + { + "Content": "", + "DeviceIdentifier": "disk4", + "OSInternal": False, + "Size": 15931539456, + }, + ], + "VolumesFromDisks": [], + "WholeDisks": ["disk4"], + } + + +def _fake_run(layout=None, returncode=0, stdout=None): + """Stand in for _run, answering `diskutil list -plist` with a plist.""" + if stdout is None: + stdout = plistlib.dumps(layout).decode() if layout else "" + + def run(cmd, **kwargs): + return subprocess.CompletedProcess(cmd, returncode, stdout, "") + + return run + def _load_tool(): """Load tools/flash_chdk.py, which is a script and not a package.""" @@ -130,7 +190,7 @@ def refuse(disk): raise SystemExit(1) monkeypatch.setattr(tool, "get_mount_point", refuse) - monkeypatch.setattr(tool, "_card_holds_a_volume", lambda disk: False) + monkeypatch.setattr(tool, "_run", _fake_run(_blank_layout())) assert tool.read_existing_own_txt("/dev/disk9") == (None, None) assert "blank" in capsys.readouterr().out @@ -144,7 +204,7 @@ def refuse(disk): monkeypatch.setattr(tool, "get_mount_point", refuse) # diskutil says there is a filesystem, but it would not mount. - monkeypatch.setattr(tool, "_card_holds_a_volume", lambda disk: True) + monkeypatch.setattr(tool, "_run", _fake_run(PARTITIONED_LAYOUT)) with pytest.raises(SystemExit): tool.read_existing_own_txt("/dev/disk9") assert "could not be inspected" in capsys.readouterr().out @@ -162,7 +222,7 @@ def refuse(disk): monkeypatch.setattr(tool, "find_removable_disks", lambda: []) monkeypatch.setattr(tool, "pick_disk", lambda disks: "/dev/disk9") monkeypatch.setattr(tool, "get_mount_point", refuse) - monkeypatch.setattr(tool, "_card_holds_a_volume", lambda disk: True) + monkeypatch.setattr(tool, "_run", _fake_run(PARTITIONED_LAYOUT)) monkeypatch.setattr( tool, "format_card", lambda disk: formatted.append(disk), ) @@ -170,12 +230,67 @@ def refuse(disk): tool.main() assert formatted == [] + def test_a_layout_that_cannot_be_inspected_stops_the_run( + self, monkeypatch, + ): + tool = _load_tool() + + def refuse(disk): + raise SystemExit(1) + + monkeypatch.setattr(tool, "get_mount_point", refuse) + # diskutil itself failed: the card is not demonstrably blank. + monkeypatch.setattr(tool, "_run", _fake_run(returncode=1)) + with pytest.raises(SystemExit): + tool.read_existing_own_txt("/dev/disk4") + + def test_unparseable_layout_stops_the_run(self, monkeypatch): + tool = _load_tool() + + def refuse(disk): + raise SystemExit(1) + + monkeypatch.setattr(tool, "get_mount_point", refuse) + monkeypatch.setattr(tool, "_run", _fake_run(stdout="not a plist")) + with pytest.raises(SystemExit): + tool.read_existing_own_txt("/dev/disk4") + + def test_an_apfs_container_counts_as_a_filesystem(self, monkeypatch): + tool = _load_tool() + layout = { + "AllDisksAndPartitions": [ + { + "Content": "Apple_APFS_Container", + "DeviceIdentifier": "disk4", + "APFSVolumes": [{"DeviceIdentifier": "disk4s1"}], + "Partitions": [], + }, + ], + } + monkeypatch.setattr(tool, "_run", _fake_run(layout)) + assert tool._classify_card("/dev/disk4") == tool.CARD_HAS_FILESYSTEM + + def test_a_blank_layout_is_classified_blank(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr(tool, "_run", _fake_run(_blank_layout())) + assert tool._classify_card("/dev/disk4") == tool.CARD_BLANK + + def test_a_partitioned_layout_holds_a_filesystem(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr(tool, "_run", _fake_run(PARTITIONED_LAYOUT)) + assert tool._classify_card("/dev/disk4") == tool.CARD_HAS_FILESYSTEM + + def test_an_empty_layout_list_is_unknown_not_blank(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr(tool, "_run", _fake_run({"AllDisksAndPartitions": []})) + assert tool._classify_card("/dev/disk4") == tool.CARD_UNKNOWN + def test_a_mounted_card_with_no_own_txt_has_no_id( self, tmp_path, monkeypatch, ): tool = _load_tool() monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) - monkeypatch.setattr(tool, "_card_holds_a_volume", lambda disk: True) + monkeypatch.setattr(tool, "_run", _fake_run(PARTITIONED_LAYOUT)) assert tool.read_existing_own_txt("/dev/disk9") == (None, None) def test_an_unreadable_own_txt_stops_rather_than_reporting_no_id( diff --git a/tools/flash_chdk.py b/tools/flash_chdk.py index 7064c24..dbc6cd1 100755 --- a/tools/flash_chdk.py +++ b/tools/flash_chdk.py @@ -200,21 +200,58 @@ def _mounted_path(disk: str) -> str | None: return None -def _card_holds_a_volume(disk: str) -> bool: - """Ask diskutil whether the card has a first partition at all. +CARD_BLANK = "blank" +CARD_HAS_FILESYSTEM = "filesystem" +CARD_UNKNOWN = "unknown" - diskutil info exits nonzero for a partition that does not exist, so - a card with no filesystem answers False here. That is the only - card safe to erase without looking at it first. + +def _entry_holds_a_filesystem(entry: dict) -> bool: + """Whether one diskutil layout entry describes anything mountable.""" + if entry.get("Content"): + return True + return bool(entry.get("Partitions") or entry.get("APFSVolumes")) + + +def _classify_card(disk: str) -> str: + """Ask diskutil what the whole card holds. + + Inspecting one partition cannot answer this: an existing but + unformatted diskNs1 reports fine and then will not mount, and a + diskNs1 that is missing does not prove the card is empty, since the + filesystem may be on the whole device or on another partition. So + read the layout of the whole device and judge from every entry in + it. `diskutil list -plist` returns AllDisksAndPartitions, whose + entries carry a Content naming the partition scheme or filesystem + and, when there is one, a Partitions or APFSVolumes list. + + Anything we cannot read or cannot understand is CARD_UNKNOWN, never + CARD_BLANK: only a layout that positively shows an empty card is + safe to erase without looking first. Args: disk: /dev/diskN path. Returns: - True if the card reports a volume, False if it holds none. + CARD_BLANK, CARD_HAS_FILESYSTEM or CARD_UNKNOWN. """ - result = _run(["diskutil", "info", "-plist", disk + "s1"], check=False) - return result.returncode == 0 + result = _run(["diskutil", "list", "-plist", disk], check=False) + if result.returncode != 0: + return CARD_UNKNOWN + try: + layout = plistlib.loads(result.stdout.encode()) + except Exception: + return CARD_UNKNOWN + entries = layout.get("AllDisksAndPartitions") + if not entries: + # diskutil succeeded but told us nothing about this disk. + return CARD_UNKNOWN + for entry in entries: + if _entry_holds_a_filesystem(entry): + return CARD_HAS_FILESYSTEM + for part in entry.get("Partitions", []) + entry.get("APFSVolumes", []): + if _entry_holds_a_filesystem(part): + return CARD_HAS_FILESYSTEM + return CARD_BLANK def read_existing_own_txt(disk: str) -> tuple[str | None, str | None]: @@ -247,14 +284,15 @@ def read_existing_own_txt(disk: str) -> tuple[str | None, str | None]: """ mount_point = _mounted_path(disk) if mount_point is None: - if not _card_holds_a_volume(disk): + if _classify_card(disk) == CARD_BLANK: print("Card holds no filesystem; treating it as blank.") return None, None print( - "The card holds a filesystem that could not be inspected. " - "Stopping before it is erased: it may carry a camera id, " - "and formatting would lose that body's identity. Check the " - "card and the reader, then run this again." + "The card holds a filesystem that could not be inspected, " + "or its layout could not be read at all. Stopping before it " + "is erased: it may carry a camera id, and formatting would " + "lose that body's identity. Check the card and the reader, " + "then run this again." ) sys.exit(1) From 66526c47ef5f1b3786ac98b0e6c17da72f6f02ec Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 18:01:30 -0600 Subject: [PATCH 24/34] fix(script): match a script's messages to the script that started MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit wait_for_script raised on any error in the queue without asking whose it was, and _shoot_standard threw away the id execute_script hands back. Starting a script does not flush the queue, so an error left behind by the previous shot failed the next one — a camera that hiccups once then fails every shot after it, each with the first shot's message. On a bench that reads as a dead camera rather than as one bad frame. wait_for_script now takes the id to match and ignores errors belonging to anything else, and _shoot_standard keeps its id and passes it. The streaming path already matched. A caller with no id to give still matches any error, which is the best that can be done without one. The collection after a successful download was already bounded, by drain_messages' own limit, and already unable to take the picture away, by the try around it. Both now have tests saying so rather than relying on someone rereading the loop: a camera that never stops reporting messages ends the drain, and it ends the shot with the bytes. --- src/pychdk/chdk.py | 10 ++++++++-- src/pychdk/device.py | 7 ++++--- tests/test_chdk.py | 39 +++++++++++++++++++++++++++++++++++++++ tests/test_device.py | 8 ++++++++ 4 files changed, 59 insertions(+), 5 deletions(-) diff --git a/src/pychdk/chdk.py b/src/pychdk/chdk.py index 85b02e7..a6ae810 100644 --- a/src/pychdk/chdk.py +++ b/src/pychdk/chdk.py @@ -427,7 +427,7 @@ def remote_capture_get_data(self, format_flag): f"Remote capture did not end after {MAX_CAPTURE_CHUNKS} chunks" ) - def wait_for_script(self, timeout=30.0): + def wait_for_script(self, timeout=30.0, script_id=None): """Wait until no script is running on the camera. Reads waiting messages as it goes, rather than watching only @@ -438,6 +438,11 @@ def wait_for_script(self, timeout=30.0): Args: timeout: Max seconds to wait for the script to finish. + script_id: Only raise on errors from this script. Starting + a script does not flush the queue, so an error left by + a previous one would otherwise fail this one. None + matches any script, which is only right when the caller + has no id to match. Raises: RuntimeError: If the script reported an error. @@ -448,7 +453,8 @@ def wait_for_script(self, timeout=30.0): running, has_msgs = self.get_script_status() if has_msgs: msg = self.read_script_message() - if msg.msg_type == MessageType.ERR: + is_ours = script_id is None or msg.script_id == script_id + if is_ours and msg.msg_type == MessageType.ERR: kind = _script_error_name(msg.data_type) raise RuntimeError(f"Script error ({kind}): {msg.value}") continue diff --git a/src/pychdk/device.py b/src/pychdk/device.py index f207ccf..dda4ec2 100644 --- a/src/pychdk/device.py +++ b/src/pychdk/device.py @@ -339,9 +339,10 @@ def _shoot_streaming(self, setup_parts, dng): def _shoot_standard(self, setup_parts, download, remove): """Capture to SD card, optionally download and delete.""" script = "; ".join(setup_parts + ["shoot()"]) - self.lua_execute(script, do_return=False) - # Wait for the shoot script to finish (shutter + SD write) - self._chdk.wait_for_script(timeout=30) + script_id = self._chdk.execute_script(script) + # Wait for the shoot script to finish (shutter + SD write), + # matching its id so a previous shot's error is not ours. + self._chdk.wait_for_script(timeout=30, script_id=script_id) if not download: return None diff --git a/tests/test_chdk.py b/tests/test_chdk.py index 78eff17..b0346ce 100644 --- a/tests/test_chdk.py +++ b/tests/test_chdk.py @@ -187,6 +187,24 @@ def test_a_refused_script_fails_without_waiting(self): assert session.transaction.call_count == 2 +class TestDrainMessages: + """Collecting leftovers must be bounded: a camera can keep talking.""" + + def _make_chdk(self): + mock_session = MagicMock() + return ChdkPTP(mock_session), mock_session + + def test_a_queue_that_never_clears_still_ends(self): + chdk, session = self._make_chdk() + # Always "message waiting", never anything that ends it. + session.transaction.return_value = ( + [MessageType.USER, ScriptDataType.STRING, 3, 1], b"x", + ) + chdk.drain_messages() + # Bounded, so the call returns instead of reading forever. + assert session.transaction.call_count < 200 + + class TestWaitForScript: """Waiting must notice a script that fails after it starts.""" @@ -205,6 +223,27 @@ def test_a_script_that_fails_after_starting_raises_with_its_text(self): with pytest.raises(RuntimeError, match="shoot failed"): chdk.wait_for_script(timeout=5) + def test_an_error_from_another_script_does_not_fail_this_one(self): + chdk, session = self._make_chdk() + session.transaction.side_effect = [ + ([0b11], b""), # running, message waiting + # Left over from the previous shot, not ours. + ([MessageType.ERR, ScriptErrorType.RUN, 3, 13], + b"stale error\x00"), + ([0], b""), # ours finished cleanly + ] + assert chdk.wait_for_script(timeout=5, script_id=7) is None + + def test_an_error_from_this_script_still_raises(self): + chdk, session = self._make_chdk() + session.transaction.side_effect = [ + ([0b11], b""), + ([MessageType.ERR, ScriptErrorType.RUN, 7, 13], + b"our error\x00"), + ] + with pytest.raises(RuntimeError, match="our error"): + chdk.wait_for_script(timeout=5, script_id=7) + def test_a_clean_completion_still_returns(self): chdk, session = self._make_chdk() session.transaction.return_value = ([0], b"") diff --git a/tests/test_device.py b/tests/test_device.py index 89e386e..d10a41a 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -260,6 +260,14 @@ def test_streaming_jpeg_is_unchanged(self): assert dev.shoot(stream=True) == b"jpeg" mock_chdk.remote_capture_get_data.assert_called_once_with(1) + def test_standard_shot_waits_on_its_own_script_id(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 11 + dev.shoot() + mock_chdk.wait_for_script.assert_called_once_with( + timeout=30, script_id=11, + ) + def test_close(self): dev, mock_chdk = self._make_device() dev.close() From 1f059223f9477038869f6ef8e85ba6764d626215 Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 18:06:46 -0600 Subject: [PATCH 25/34] fix(flasher): recognize a blank card rather than assuming one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The last commit claimed the classification failed closed and it did not. Blank was whatever was left after looking for a filesystem and not finding one, so a payload of {} — or one made entirely of keys we do not know, or one describing a different disk than the one asked about — came back blank and authorized the erase. Failing to recognize a filesystem is not the same as recognizing there is none, and the whole point of the check was the difference. Blank is now something the payload has to say. It must parse, describe exactly one entry for the device we asked about, carry the keys real diskutil output carries, and show that device empty. Everything else — unreadable, unfamiliar, about another disk, or more entries than we can account for — is unknown and stops the run. The nested lists are type checked too, since a payload that is the wrong shape inside is no more trustworthy than one that is the wrong shape outside. --- tests/test_flash_chdk.py | 40 +++++++++++++++++++++++---- tools/flash_chdk.py | 60 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 88 insertions(+), 12 deletions(-) diff --git a/tests/test_flash_chdk.py b/tests/test_flash_chdk.py index 91e7587..572c1de 100644 --- a/tests/test_flash_chdk.py +++ b/tests/test_flash_chdk.py @@ -191,7 +191,7 @@ def refuse(disk): monkeypatch.setattr(tool, "get_mount_point", refuse) monkeypatch.setattr(tool, "_run", _fake_run(_blank_layout())) - assert tool.read_existing_own_txt("/dev/disk9") == (None, None) + assert tool.read_existing_own_txt("/dev/disk4") == (None, None) assert "blank" in capsys.readouterr().out def test_a_volume_that_will_not_mount_stops_the_run( @@ -206,7 +206,7 @@ def refuse(disk): # diskutil says there is a filesystem, but it would not mount. monkeypatch.setattr(tool, "_run", _fake_run(PARTITIONED_LAYOUT)) with pytest.raises(SystemExit): - tool.read_existing_own_txt("/dev/disk9") + tool.read_existing_own_txt("/dev/disk4") assert "could not be inspected" in capsys.readouterr().out def test_main_does_not_erase_a_volume_it_could_not_mount( @@ -220,7 +220,7 @@ def refuse(disk): monkeypatch.setattr(tool, "download_chdk", lambda: None) monkeypatch.setattr(tool, "find_removable_disks", lambda: []) - monkeypatch.setattr(tool, "pick_disk", lambda disks: "/dev/disk9") + monkeypatch.setattr(tool, "pick_disk", lambda disks: "/dev/disk4") monkeypatch.setattr(tool, "get_mount_point", refuse) monkeypatch.setattr(tool, "_run", _fake_run(PARTITIONED_LAYOUT)) monkeypatch.setattr( @@ -285,13 +285,41 @@ def test_an_empty_layout_list_is_unknown_not_blank(self, monkeypatch): monkeypatch.setattr(tool, "_run", _fake_run({"AllDisksAndPartitions": []})) assert tool._classify_card("/dev/disk4") == tool.CARD_UNKNOWN + def test_an_empty_entry_is_unknown_not_blank(self, monkeypatch): + tool = _load_tool() + # Nothing here says the device is empty; it says nothing at all. + monkeypatch.setattr(tool, "_run", _fake_run({ + "AllDisksAndPartitions": [{}], + })) + assert tool._classify_card("/dev/disk4") == tool.CARD_UNKNOWN + + def test_an_entry_of_unrecognized_fields_is_unknown(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr(tool, "_run", _fake_run({ + "AllDisksAndPartitions": [ + {"SomeFutureKey": "whatever", "DeviceIdentifier": "disk4"}, + ], + })) + assert tool._classify_card("/dev/disk4") == tool.CARD_UNKNOWN + + def test_a_payload_about_another_device_is_unknown(self, monkeypatch): + tool = _load_tool() + # A blank layout, but not for the card we asked about. + monkeypatch.setattr(tool, "_run", _fake_run(_blank_layout())) + assert tool._classify_card("/dev/disk9") == tool.CARD_UNKNOWN + + def test_a_bare_disk_identifier_is_accepted(self, monkeypatch): + tool = _load_tool() + monkeypatch.setattr(tool, "_run", _fake_run(_blank_layout())) + assert tool._classify_card("disk4") == tool.CARD_BLANK + def test_a_mounted_card_with_no_own_txt_has_no_id( self, tmp_path, monkeypatch, ): tool = _load_tool() monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) monkeypatch.setattr(tool, "_run", _fake_run(PARTITIONED_LAYOUT)) - assert tool.read_existing_own_txt("/dev/disk9") == (None, None) + assert tool.read_existing_own_txt("/dev/disk4") == (None, None) def test_an_unreadable_own_txt_stops_rather_than_reporting_no_id( self, tmp_path, monkeypatch, @@ -301,7 +329,7 @@ def test_an_unreadable_own_txt_stops_rather_than_reporting_no_id( (tmp_path / "OWN.TXT").mkdir() monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) with pytest.raises(SystemExit): - tool.read_existing_own_txt("/dev/disk9") + tool.read_existing_own_txt("/dev/disk4") def test_main_does_not_erase_a_card_it_could_not_check( self, tmp_path, monkeypatch, @@ -311,7 +339,7 @@ def test_main_does_not_erase_a_card_it_could_not_check( formatted = [] monkeypatch.setattr(tool, "download_chdk", lambda: None) monkeypatch.setattr(tool, "find_removable_disks", lambda: []) - monkeypatch.setattr(tool, "pick_disk", lambda disks: "/dev/disk9") + monkeypatch.setattr(tool, "pick_disk", lambda disks: "/dev/disk4") monkeypatch.setattr(tool, "get_mount_point", lambda disk: str(tmp_path)) monkeypatch.setattr( tool, "format_card", lambda disk: formatted.append(disk), diff --git a/tools/flash_chdk.py b/tools/flash_chdk.py index dbc6cd1..6bf2bca 100755 --- a/tools/flash_chdk.py +++ b/tools/flash_chdk.py @@ -205,6 +205,17 @@ def _mounted_path(disk: str) -> str | None: CARD_UNKNOWN = "unknown" +# The keys every whole-disk entry of `diskutil list -plist` carries, +# captured from real output. An entry without them is not a shape we +# recognize, and an unrecognized shape is never called blank. +_WHOLE_DISK_KEYS = frozenset({"Content", "DeviceIdentifier", "Size"}) + + +def _disk_identifier(disk: str) -> str: + """Reduce /dev/diskN to the diskN that diskutil reports.""" + return disk.rsplit("/", 1)[-1] + + def _entry_holds_a_filesystem(entry: dict) -> bool: """Whether one diskutil layout entry describes anything mountable.""" if entry.get("Content"): @@ -212,6 +223,18 @@ def _entry_holds_a_filesystem(entry: dict) -> bool: return bool(entry.get("Partitions") or entry.get("APFSVolumes")) +def _entry_is_recognizably_blank(entry: dict) -> bool: + """Whether an entry positively shows a device with nothing on it. + + Being unable to find a filesystem is not the same as finding none: + an empty entry, or one made of keys we do not know, says nothing + about the card and must not be read as saying it is empty. + """ + if not _WHOLE_DISK_KEYS.issubset(entry): + return False + return not _entry_holds_a_filesystem(entry) + + def _classify_card(disk: str) -> str: """Ask diskutil what the whole card holds. @@ -224,9 +247,12 @@ def _classify_card(disk: str) -> str: entries carry a Content naming the partition scheme or filesystem and, when there is one, a Partitions or APFSVolumes list. - Anything we cannot read or cannot understand is CARD_UNKNOWN, never - CARD_BLANK: only a layout that positively shows an empty card is - safe to erase without looking first. + Blank has to be recognized, not inferred from failing to recognize + anything else: the payload must describe the device we asked about, + in the shape we captured, and show it empty. Anything we cannot + read, cannot understand, or that turns out to be about some other + disk is CARD_UNKNOWN and stops the run. Only a layout that + positively shows an empty card is safe to erase without looking. Args: disk: /dev/diskN path. @@ -241,16 +267,38 @@ def _classify_card(disk: str) -> str: layout = plistlib.loads(result.stdout.encode()) except Exception: return CARD_UNKNOWN + if not isinstance(layout, dict): + return CARD_UNKNOWN entries = layout.get("AllDisksAndPartitions") - if not entries: + if not isinstance(entries, list) or not entries: # diskutil succeeded but told us nothing about this disk. return CARD_UNKNOWN + if not all(isinstance(entry, dict) for entry in entries): + return CARD_UNKNOWN + + # Any filesystem anywhere in the payload is enough to stop. for entry in entries: + parts = entry.get("Partitions") or [] + volumes = entry.get("APFSVolumes") or [] + if not isinstance(parts, list) or not isinstance(volumes, list): + return CARD_UNKNOWN if _entry_holds_a_filesystem(entry): return CARD_HAS_FILESYSTEM - for part in entry.get("Partitions", []) + entry.get("APFSVolumes", []): - if _entry_holds_a_filesystem(part): + for part in list(parts) + list(volumes): + if isinstance(part, dict) and _entry_holds_a_filesystem(part): return CARD_HAS_FILESYSTEM + + # Nothing found — but only the entry for the device we asked about + # can say the card is empty, and only in a shape we recognize. + wanted = _disk_identifier(disk) + described = [ + entry for entry in entries + if entry.get("DeviceIdentifier") == wanted + ] + if len(described) != 1: + return CARD_UNKNOWN + if not _entry_is_recognizably_blank(described[0]): + return CARD_UNKNOWN return CARD_BLANK From 994bf7aad108f789d82898e79620f353731dc23f Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 18:07:49 -0600 Subject: [PATCH 26/34] fix(device): match a mode switch's messages to its own script Giving wait_for_script an id to match fixed _shoot_standard and left switch_mode exactly as it was: it discarded the id execute_script returns and waited without one, so a queued error from an earlier capture failed a mode switch that had started perfectly well. The symptom is worse than the one it was meant to fix, because a failed mode switch looks like a camera that will not go into record at all. switch_mode keeps its id and passes it. These were the only two callers of wait_for_script, so with this one the gap is closed rather than narrowed. The test drives the real waiter with a stale error from another script in the queue, rather than asserting on a mock, since what needed proving was that the waiter ignores it. --- src/pychdk/device.py | 7 ++++--- tests/test_device.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/pychdk/device.py b/src/pychdk/device.py index dda4ec2..3f4e759 100644 --- a/src/pychdk/device.py +++ b/src/pychdk/device.py @@ -175,9 +175,10 @@ def switch_mode(self, mode): get_mode() to confirm the physical switch completed. """ mode_val = 1 if mode == "record" else 0 - self.lua_execute(f"switch_mode_usb({mode_val})", do_return=False) - # Wait for the script to finish before polling - self._chdk.wait_for_script(timeout=5) + script_id = self._chdk.execute_script(f"switch_mode_usb({mode_val})") + # Wait for the script to finish before polling, matching its id + # so an error left by an earlier shot is not blamed on this. + self._chdk.wait_for_script(timeout=5, script_id=script_id) # Give the camera time to physically switch (lens motor, etc.) time.sleep(1) for _ in range(8): diff --git a/tests/test_device.py b/tests/test_device.py index d10a41a..924a28f 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -82,6 +82,37 @@ def test_download_file(self): result = dev.download_file("A/OWN.TXT") assert result == b"EVEN\n" + def test_switch_mode_waits_on_its_own_script_id(self): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 21 + dev.switch_mode("record") + mock_chdk.wait_for_script.assert_called_once_with( + timeout=5, script_id=21, + ) + + def test_switch_mode_survives_a_previous_captures_error(self): + info = DeviceInfo( + vendor_id=0x04A9, product_id=0x1234, + bus_num=1, device_num=5, serial_num="ABC", + ) + mock_usb = MagicMock() + mock_session = MagicMock() + with patch("pychdk.device.PTPDevice"), \ + patch("pychdk.device.PTPSession", return_value=mock_session): + dev = ChdkDevice(info, _usb_device=mock_usb) + # The real waiter, against a queue holding an older shot's error. + mock_session.transaction.side_effect = [ + ([21, 0], b""), # switch_mode_usb starts, id 21 + ([0b11], b""), # running, message waiting + ([MessageType.ERR, ScriptErrorType.RUN, 9, 12], + b"stale error\x00"), # from script 9, not ours + ([0], b""), # ours finished cleanly + ([0, 0], b""), # get_mode() script starts + ([0], b""), # drain: nothing pending + ([0], b""), # not running, no messages + ] + dev.switch_mode("record") + def test_streamed_dng_is_refused(self): dev, mock_chdk = self._make_device() with pytest.raises(NotImplementedError, match="DNG"): From 0c8aca967db3d811c9b68bd85083f715d6d920f5 Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 18:09:13 -0600 Subject: [PATCH 27/34] fix(capture): tell a slow initialization from one that never happened MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both ways of failing to initialize produced the same sentence, and they are not the same observation. A script that ended while the camera still reported remote capture uninitialized ran and did not initialize. A script still going when our grace expired may be nothing worse than slow. At a bench those want distinguishing from the log alone, without anyone opening this file to work out which branch fired. They now read differently, and the grace one names the seconds it waited, so a camera that just needs longer says so and points at the number to raise. Neither message suggests the camera cannot do remote capture, because neither observation shows that — an operator who concludes the body is unsupported and sets it aside has lost a camera to a message, which on two bodies and one afternoon is half the rig. Also corrects the docstring's account of the post-download drain. It called it collecting the script's result, which it is not: it sweeps what is already queued and never waits for anything still to come. --- src/pychdk/device.py | 30 +++++++++++++++++++++--------- tests/test_device.py | 37 +++++++++++++++++++++++++++++++++++-- 2 files changed, 56 insertions(+), 11 deletions(-) diff --git a/src/pychdk/device.py b/src/pychdk/device.py index 3f4e759..e8e4a0a 100644 --- a/src/pychdk/device.py +++ b/src/pychdk/device.py @@ -250,7 +250,10 @@ def _shoot_streaming(self, setup_parts, dng): leaves both sides waiting on each other and the capture times out having never once asked whether data was ready. We service the camera while the script runs — readiness first, messages - second — and collect the script's result afterwards. + second. Once the picture is in hand the queue is cleared of + whatever the script left, which is housekeeping so the next + capture does not read a stale message: it is a bounded sweep of + what is already waiting, not a wait for a result still to come. Raises: RuntimeError: If the camera refuses to initialize remote @@ -280,7 +283,8 @@ def _shoot_streaming(self, setup_parts, dng): image = None deadline = time.monotonic() + 30 - init_deadline = time.monotonic() + CAPTURE_INIT_GRACE + grace = CAPTURE_INIT_GRACE + init_deadline = time.monotonic() + grace while time.monotonic() < deadline: ready, status = self._chdk.remote_capture_is_ready() formats = status @@ -313,13 +317,21 @@ def _shoot_streaming(self, setup_parts, dng): # Checked after the queue, so a script that explained itself # is reported by its own words rather than by this status. - if status == REMOTE_CAP_NOTSET and ( - not running or time.monotonic() >= init_deadline - ): - raise RuntimeError( - "The camera never initialized remote capture: " - "init_usb_capture did not take effect" - ) + # The two ways of getting here are different observations + # and read differently in a bench log: a script that ran and + # did not initialize, versus one still going after we gave + # up waiting. Neither proves the camera cannot do this. + if status == REMOTE_CAP_NOTSET: + if not running: + raise RuntimeError( + "The capture script ended without initializing " + "remote capture" + ) + if time.monotonic() >= init_deadline: + raise RuntimeError( + "The capture script did not initialize remote " + f"capture within {grace}s and is still running" + ) if not running: raise RuntimeError( "The capture script finished without producing a capture" diff --git a/tests/test_device.py b/tests/test_device.py index 924a28f..641eb09 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -205,17 +205,50 @@ def test_an_early_not_initialized_poll_is_not_a_failure(self): mock_chdk.remote_capture_get_data.return_value = b"jpeg" assert dev.shoot(stream=True) == b"jpeg" - def test_not_initialized_after_the_script_ended_is_a_failure(self): + def test_a_script_that_ended_without_initializing_says_so(self): dev, mock_chdk = self._make_device() mock_chdk.execute_script.return_value = 7 mock_chdk.remote_capture_is_ready.return_value = ( False, REMOTE_CAP_NOTSET, ) mock_chdk.get_script_status.return_value = (False, False) - with pytest.raises(RuntimeError, match="never initialized"): + with pytest.raises(RuntimeError, match="ended without initializing"): dev.shoot(stream=True) assert mock_chdk.remote_capture_is_ready.call_count == 1 + def test_an_expired_grace_says_how_long_it_waited(self, monkeypatch): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = ( + False, REMOTE_CAP_NOTSET, + ) + # Still running: the camera may merely be slow, which is a + # different observation from a script that finished. + mock_chdk.get_script_status.return_value = (True, False) + monkeypatch.setattr("pychdk.device.CAPTURE_INIT_GRACE", 0.0) + with pytest.raises(RuntimeError, match=r"within 0.0s"): + dev.shoot(stream=True) + + def test_neither_initialization_message_claims_incompatibility( + self, monkeypatch, + ): + dev, mock_chdk = self._make_device() + mock_chdk.execute_script.return_value = 7 + mock_chdk.remote_capture_is_ready.return_value = ( + False, REMOTE_CAP_NOTSET, + ) + monkeypatch.setattr("pychdk.device.CAPTURE_INIT_GRACE", 0.0) + seen = [] + for running in (True, False): + mock_chdk.get_script_status.return_value = (running, False) + with pytest.raises(RuntimeError) as caught: + dev.shoot(stream=True) + seen.append(str(caught.value)) + assert seen[0] != seen[1] + for message in seen: + assert "support" not in message.lower() + assert "incompatible" not in message.lower() + def test_an_initialization_failure_beats_the_early_status(self): dev, mock_chdk = self._make_device() mock_chdk.execute_script.return_value = 7 From 713a5ebb1f9a87f26439f27d246e15ab0182216a Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Wed, 9 Sep 2026 18:26:18 -0600 Subject: [PATCH 28/34] fix(flasher): fail rather than guess when a card will not mount MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit get_mount_point ended with a fallback to /Volumes/