cannonball-eos 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cannonball/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
cannonball/__main__.py ADDED
@@ -0,0 +1,304 @@
1
+ """cannonball: receive Canon EOS "auto send images to computer" transfers.
2
+
3
+ The supervisor (this module) never talks PTP itself. It keeps this computer
4
+ announced, watches for the camera on the network, and runs each camera
5
+ session in a child process (worker.py) that it kills and retries if it stops
6
+ making progress.
7
+ """
8
+
9
+ import argparse
10
+ import json
11
+ import logging
12
+ import logging.handlers
13
+ import math
14
+ import multiprocessing as mp
15
+ import shutil
16
+ import signal
17
+ import subprocess
18
+ import sys
19
+ import threading
20
+ import time
21
+ from pathlib import Path
22
+
23
+ from . import config, consts, discovery, systemd, worker
24
+ from .status import State, Status
25
+
26
+ log = logging.getLogger(consts.PACKAGE)
27
+
28
+ NEVER = -math.inf # a time long past
29
+ PING = "ping"
30
+ PING_TIMEOUT_FLAG = "-t" if sys.platform == "darwin" else "-W" # seconds, on both
31
+
32
+
33
+ def ping(host: str, timeout: float) -> bool:
34
+ args = [PING, "-c", "1", PING_TIMEOUT_FLAG, str(round(timeout)), host] # config keeps timeout >= 1
35
+ try:
36
+ result = subprocess.run(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout + 1)
37
+ except (OSError, subprocess.TimeoutExpired):
38
+ return False
39
+ return result.returncode == 0
40
+
41
+
42
+ class Hosts:
43
+ """Camera addresses on our networks: the configured ones, and up to
44
+ REMEMBERED_HOSTS found on the network (kept across runs, newest last)."""
45
+
46
+ def __init__(self, cfg: config.Config):
47
+ self.networks = cfg.networks
48
+ self.path = cfg.state_dir / consts.STATE_HOSTS
49
+ self.configured = [h for h in dict.fromkeys(cfg.hosts) if self._on_our_networks(h)]
50
+ try:
51
+ known = [h for h in json.loads(self.path.read_text()) if isinstance(h, str)]
52
+ except (OSError, ValueError, TypeError):
53
+ known = []
54
+ self._found = [h for h in known if h not in self.configured and self._on_our_networks(h)][-consts.REMEMBERED_HOSTS :]
55
+ self._lock = threading.Lock()
56
+
57
+ def _on_our_networks(self, host: str) -> bool:
58
+ if host in self.networks:
59
+ return True
60
+ log.warning("ignoring camera address %s: outside the configured networks", host)
61
+ return False
62
+
63
+ def add(self, host: str) -> bool:
64
+ """Remember a camera found on the network; True if it is new."""
65
+ with self._lock:
66
+ if host in self.configured or host in self._found or not self._on_our_networks(host):
67
+ return False
68
+ self._found = (self._found + [host])[-consts.REMEMBERED_HOSTS :]
69
+ self.path.parent.mkdir(parents=True, exist_ok=True)
70
+ self.path.write_text(json.dumps(self._found))
71
+ return True
72
+
73
+ def __iter__(self):
74
+ with self._lock:
75
+ return iter(self.configured + self._found)
76
+
77
+
78
+ class Supervisor:
79
+ def __init__(self, cfg: config.Config, log_queue, once: bool):
80
+ self.cfg = cfg
81
+ self.log_queue = log_queue
82
+ self.once = once
83
+ self.stop = threading.Event()
84
+ self.hosts = Hosts(cfg)
85
+ self.seen = threading.Event() # set when a camera's record is found
86
+ self.ctx = mp.get_context("spawn")
87
+ self.proc = None
88
+ self.proc_host = ""
89
+ self.heartbeat = self.ctx.Value("d", 0.0)
90
+ self.up: dict[str, bool] = {}
91
+ self.misses: dict[str, int] = {}
92
+ self.next_try: dict[str, float] = {}
93
+ self.last_announce = NEVER # announce on the first tick
94
+ self.next_restart = NEVER
95
+ self.discovery: discovery.Discovery | None = None
96
+ self.events = self.ctx.Queue() # progress events from workers
97
+ self.status = Status()
98
+
99
+ def on_camera(self, host: str, txt: dict) -> None:
100
+ if self.hosts.add(host): # only a new address is worth waking the loop for
101
+ log.info("found %r at %s", txt.get(consts.CAMERA_TXT_MODEL, "camera"), host) # %r: the record is untrusted
102
+ self.seen.set()
103
+
104
+ def announce(self) -> None:
105
+ if self.discovery and self.cfg.advertise:
106
+ self.discovery.announce()
107
+ self.last_announce = time.monotonic()
108
+
109
+ # -- worker management ----------------------------------------------
110
+
111
+ def start_worker(self, host: str) -> None:
112
+ self.heartbeat.value = time.time()
113
+ self.proc = self.ctx.Process(
114
+ target=worker.main,
115
+ args=(self.cfg, host, self.heartbeat, self.log_queue, self.events),
116
+ name=f"{consts.PACKAGE}-worker-{host}",
117
+ daemon=True,
118
+ )
119
+ self.proc.start()
120
+ self.proc_host = host
121
+ log.debug("%s: worker %d started", host, self.proc.pid)
122
+
123
+ def kill_worker(self) -> None:
124
+ self.proc.kill()
125
+ self.proc.join(consts.SUBPROCESS_STOP_TIMEOUT)
126
+ self.proc = None
127
+
128
+ def check_worker(self) -> bool:
129
+ """Reap or kill the worker. Returns True when a sync completed and --once is set."""
130
+ if self.proc is None:
131
+ return False
132
+ host = self.proc_host
133
+ timing = self.cfg.timing
134
+ if self.proc.is_alive():
135
+ idle = time.time() - self.heartbeat.value
136
+ if idle > timing.stall_timeout:
137
+ log.warning("%s: no progress for %.0fs, killing session", host, idle)
138
+ self.kill_worker()
139
+ self.next_try[host] = time.monotonic() + timing.retry_delay
140
+ return False
141
+
142
+ code = self.proc.exitcode
143
+ self.proc.join()
144
+ self.proc = None
145
+ if code == worker.OK:
146
+ self.next_try[host] = time.monotonic() + timing.resync_after
147
+ return self.once
148
+ delay = consts.NO_SPACE_RETRY if code == worker.NO_SPACE else timing.retry_delay
149
+ if code != worker.NO_CAMERA:
150
+ log.info("%s: session ended (exit %s); retrying in %.0fs", host, code, delay)
151
+ self.next_try[host] = time.monotonic() + delay
152
+ return False
153
+
154
+ # -- main loop -------------------------------------------------------
155
+
156
+ def drain_events(self) -> None:
157
+ while True:
158
+ try:
159
+ self.status.event(self.events.get_nowait())
160
+ except Exception: # queue.Empty, or a half-written event from a killed worker
161
+ return
162
+
163
+ def check_host(self, host: str, busy: bool) -> bool:
164
+ """Follow one camera address; start a session when it is up. Returns busy."""
165
+ was_up = self.up.get(host, False)
166
+ if ping(host, self.cfg.timing.ping_timeout):
167
+ self.misses[host] = 0
168
+ is_up = True
169
+ else:
170
+ # Camera Wi-Fi drops single pings; only call it gone after a few misses.
171
+ self.misses[host] = self.misses.get(host, 0) + 1
172
+ is_up = was_up and self.misses[host] < self.cfg.ping_misses
173
+ self.up[host] = is_up
174
+ if is_up and not was_up:
175
+ log.info("%s: camera is on the network", host)
176
+ if not busy:
177
+ self.announce() # make sure the freshly woken camera hears us
178
+ elif was_up and not is_up:
179
+ log.info("%s: camera left the network", host)
180
+ if is_up and not busy and time.monotonic() >= self.next_try.get(host, 0):
181
+ self.start_worker(host)
182
+ return True
183
+ return busy
184
+
185
+ def check_discovery(self) -> None:
186
+ """Start announcing/browsing, and restart it after a failure, at most every
187
+ DISCOVERY_RETRY seconds. A failure here never stops pings and sessions for known hosts."""
188
+ if self.discovery.alive() or time.monotonic() < self.next_restart:
189
+ return
190
+ self.next_restart = time.monotonic() + consts.DISCOVERY_RETRY
191
+ log.debug("(re)starting mDNS discovery")
192
+ try:
193
+ self.discovery.restart()
194
+ except Exception as e: # noqa: BLE001 - retried after DISCOVERY_RETRY
195
+ log.warning("could not start mDNS discovery: %s", e)
196
+ return
197
+ self.last_announce = NEVER # and announce again
198
+
199
+ def tick(self) -> bool:
200
+ self.drain_events()
201
+ if self.check_worker():
202
+ return True
203
+ self.drain_events()
204
+ self.check_discovery()
205
+
206
+ busy = self.proc is not None
207
+ if not busy and time.monotonic() - self.last_announce > self.cfg.timing.announce_interval:
208
+ self.announce()
209
+ for host in self.hosts:
210
+ busy = self.check_host(host, busy)
211
+ if not busy:
212
+ self.status.set(state=State.CAMERA if any(self.up.values()) else State.WAITING, file=None)
213
+ elif self.status.snapshot.state != State.RECEIVING:
214
+ self.status.set(state=State.CAMERA)
215
+ return False
216
+
217
+ def run(self) -> None:
218
+ if not shutil.which(PING):
219
+ log.error("no ping command: cannot see the camera come online (on Linux, install iputils-ping)")
220
+ self.discovery = discovery.create(self.cfg, self.on_camera) # the first tick starts it
221
+ log.info(
222
+ "%s running: GUID %s, saving to %s, networks %s, known cameras: %s",
223
+ consts.PACKAGE,
224
+ self.cfg.guid,
225
+ self.cfg.download.destination,
226
+ ", ".join(str(n) for n in self.cfg.networks.nets),
227
+ ", ".join(self.hosts) or "none yet",
228
+ )
229
+ try:
230
+ while not self.stop.is_set():
231
+ try:
232
+ if self.tick():
233
+ break
234
+ except Exception: # noqa: BLE001 - the supervisor must never die
235
+ log.exception("supervisor error; continuing")
236
+ self.seen.wait(self.cfg.timing.poll_interval)
237
+ self.seen.clear()
238
+ finally:
239
+ if self.proc and self.proc.is_alive():
240
+ self.proc.kill()
241
+ self.discovery.close()
242
+
243
+
244
+ def setup_logging(cfg: config.Config, verbose: bool):
245
+ """Log to stderr and a rotating file; workers log through a queue to here."""
246
+ fmt = logging.Formatter(consts.LOG_FORMAT)
247
+ handlers: list[logging.Handler] = [logging.StreamHandler()]
248
+ if cfg.log_file:
249
+ cfg.log_file.parent.mkdir(parents=True, exist_ok=True)
250
+ handlers.append(
251
+ logging.handlers.RotatingFileHandler(cfg.log_file, maxBytes=consts.LOG_MAX_BYTES, backupCount=consts.LOG_BACKUPS)
252
+ )
253
+ for h in handlers:
254
+ h.setFormatter(fmt)
255
+ level = logging.DEBUG if verbose else cfg.log_level
256
+ root = logging.getLogger()
257
+ root.handlers[:] = handlers
258
+ root.setLevel(level)
259
+ logging.getLogger("zeroconf").setLevel(logging.WARNING)
260
+ cfg.log_level = logging.getLevelName(level)
261
+
262
+ queue = mp.get_context("spawn").Queue()
263
+ listener = logging.handlers.QueueListener(queue, *handlers, respect_handler_level=True)
264
+ listener.start()
265
+ return queue, listener
266
+
267
+
268
+ def arguments(argv: list[str] | None = None) -> argparse.Namespace:
269
+ ap = argparse.ArgumentParser(prog=consts.PACKAGE, description="Receive Canon EOS Wi-Fi auto-send transfers.")
270
+ ap.add_argument("-c", "--config", type=Path, help=f"config file (default {config.DEFAULT_PATH})")
271
+ ap.add_argument("--once", action="store_true", help="exit after the first completed sync")
272
+ ap.add_argument("-v", "--verbose", action="store_true", help="debug logging")
273
+ ap.add_argument("--install-service", action="store_true", help="run Cannonball now and at login (Linux, systemd)")
274
+ args, _ = ap.parse_known_args(argv) # Finder may add its own arguments
275
+ return args
276
+
277
+
278
+ def supervisor(args: argparse.Namespace) -> tuple[Supervisor, logging.handlers.QueueListener]:
279
+ cfg = config.load(args.config)
280
+ try:
281
+ queue, listener = setup_logging(cfg, args.verbose)
282
+ except OSError as e:
283
+ raise config.ConfigError(f"{cfg.path or config.DEFAULT_PATH}: log_file {cfg.log_file}: {e.strerror}") from e
284
+ log.debug("config: %s", cfg)
285
+ return Supervisor(cfg, queue, args.once), listener
286
+
287
+
288
+ def main() -> None:
289
+ args = arguments()
290
+ if args.install_service:
291
+ systemd.install()
292
+ return
293
+ sup, listener = supervisor(args)
294
+ signal.signal(signal.SIGTERM, lambda *_: sup.stop.set())
295
+ try:
296
+ sup.run()
297
+ except KeyboardInterrupt:
298
+ pass
299
+ finally:
300
+ listener.stop()
301
+
302
+
303
+ if __name__ == "__main__":
304
+ main()
cannonball/app.py ADDED
@@ -0,0 +1,19 @@
1
+ """Entry point of Cannonball.app on macOS.
2
+
3
+ The menu bar and the supervisor run in one app process, opened by the user or
4
+ at login, so macOS asks for the app's Local Network permission and applies it
5
+ to the worker processes the app starts.
6
+ """
7
+
8
+ import multiprocessing
9
+
10
+
11
+ def main() -> None:
12
+ multiprocessing.freeze_support() # worker processes re-enter here
13
+ from .menubar import main as menubar
14
+
15
+ menubar()
16
+
17
+
18
+ if __name__ == "__main__":
19
+ main()
@@ -0,0 +1,13 @@
1
+ # systemd user service, written by `cannonball --install-service`, which fills in @PYTHON@.
2
+ [Unit]
3
+ Description=Cannonball: receive photos from Canon EOS cameras over Wi-Fi
4
+ Wants=network-online.target
5
+ After=network-online.target
6
+
7
+ [Service]
8
+ ExecStart="@PYTHON@" -m cannonball
9
+ Restart=always
10
+ RestartSec=5
11
+
12
+ [Install]
13
+ WantedBy=default.target
cannonball/canon.py ADDED
@@ -0,0 +1,166 @@
1
+ """Canon EOS auto-send: the operation sequence and records ITU2 uses.
2
+
3
+ The sequence was documented by epsimatic/canon-wifi-downloader (PROTOCOL.md),
4
+ from captures of Canon Image Transfer Utility 2 talking to an EOS 250D.
5
+ """
6
+
7
+ import re
8
+ import struct
9
+ from collections.abc import Iterator
10
+ from dataclasses import dataclass
11
+ from datetime import datetime
12
+ from pathlib import PureWindowsPath
13
+
14
+ RC_OK = 0x2001
15
+
16
+ OPEN_SESSION = 0x1002
17
+ SESSION_ID = 0x41
18
+ STORAGE = 0x00020001
19
+ ROOT = 0x91900000
20
+
21
+ GET_EVENT = 0x9116
22
+ OBJECT_INFO = 0x9170 # [handle]
23
+ READ = 0x9174 # [handle, offset, length, 0, 0]
24
+ STATUS = 0x9102 # [STORAGE]
25
+ PROGRESS = 0x91E9 # [handle, percent]
26
+ PROGRESS_DONE = 100
27
+ TRANSFER_COMPLETE = 0x91F0 # [handle]
28
+ SAVE_COMPLETE = 0x9177 # [handle, 0]
29
+
30
+ # After OpenSession. The data of the GetEvent in here lists pending images.
31
+ SETUP = [
32
+ (0x9114, (SESSION_ID,)),
33
+ (0x9115, (1,)),
34
+ (GET_EVENT, ()),
35
+ (OBJECT_INFO, (ROOT,)),
36
+ (OBJECT_INFO, (ROOT,)),
37
+ (STATUS, (STORAGE,)),
38
+ (0x913D, (0xFFF,)),
39
+ (0x9101, ()),
40
+ (STATUS, (STORAGE,)),
41
+ ]
42
+ # Once, before the first read of a session.
43
+ BEFORE_FIRST_READ = [
44
+ (0x913F, (0x01000000, 0x110, 0x31000000)),
45
+ (0x9101, ()),
46
+ ]
47
+ # CompleteAutoSendImages, event mode off, remote mode off, CloseSession.
48
+ FINISH = [
49
+ (0x916D, (0,)),
50
+ (0x9115, (0,)),
51
+ (0x9114, (0,)),
52
+ (0x1003, ()),
53
+ ]
54
+
55
+ OBJECT_RECORD = 0xC1AB # an image the camera wants to send
56
+ PROPERTY_RECORDS = {0xC189, 0xC18A} # property values and their allowed values
57
+ RECORD_LOG_BYTES = 64
58
+
59
+ # A camera-supplied file name is used only if it is a plain name like IMG_0001.CR3
60
+ # with an extension of a file type Canon cameras make: never one a double-click runs.
61
+ MAX_FILE_NAME = 128
62
+ FILE_NAME = re.compile(rf"[A-Za-z0-9_][A-Za-z0-9._-]{{0,{MAX_FILE_NAME - 1}}}")
63
+ MEDIA_EXTENSIONS = {".jpg", ".jpeg", ".cr2", ".cr3", ".crw", ".hif", ".heif", ".heic", ".tif", ".tiff",
64
+ ".mp4", ".mov", ".avi", ".crm", ".wav", ".thm"}
65
+ FALLBACK_NAME = "IMG_{handle:08X}" # when the camera offers no usable name
66
+
67
+ TIMESTAMP_FORMAT = "%Y%m%dT%H%M%S" # object info timestamps, e.g. 20260708T091035.0
68
+ TIMESTAMP_LENGTH = len("20260708T091035")
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class ObjectRecord:
73
+ handle: int
74
+ size: int
75
+ path: str # on the camera, e.g. B:/DCIM/100CANON/IMG_0952.JPG
76
+ format: int = 0
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class ObjectInfo:
81
+ filename: str
82
+ size: int
83
+ format: int
84
+ time1: str = "" # e.g. 20260708T091035.0
85
+ time2: str = ""
86
+
87
+
88
+ def events(data: bytes) -> Iterator[tuple[int, bytes]]:
89
+ """Split GetEvent data into (kind, body) records: [u32 length][u32 kind][body].
90
+
91
+ A generator, so a reply of many tiny records costs no more memory than the reply.
92
+ """
93
+ pos = 0
94
+ while pos + 8 <= len(data):
95
+ length, kind = struct.unpack_from("<II", data, pos)
96
+ if length < 8 or pos + length > len(data):
97
+ return
98
+ yield kind, data[pos + 8 : pos + length]
99
+ pos += length
100
+
101
+
102
+ def objects(data: bytes) -> list[ObjectRecord]:
103
+ """Images offered in GetEvent data.
104
+
105
+ Body: u32 handle, u32 format, u32 (0x20), u32 size, u32 (0),
106
+ u32 thumbnail handle, NUL-terminated path.
107
+ """
108
+ out = []
109
+ for kind, body in events(data):
110
+ if kind != OBJECT_RECORD or len(body) < 24:
111
+ continue
112
+ handle, fmt, _, size = struct.unpack_from("<4I", body)
113
+ path = body[24:].split(b"\0")[0].decode("latin-1")
114
+ out.append(ObjectRecord(handle, size, path, fmt))
115
+ return out
116
+
117
+
118
+ def _string(data: bytes, pos: int) -> tuple[str, int]:
119
+ """A u8 length (in UTF-16 code units) followed by UTF-16LE text."""
120
+ if pos >= len(data):
121
+ raise ValueError("truncated")
122
+ end = pos + 1 + 2 * data[pos]
123
+ if end > len(data):
124
+ raise ValueError("truncated")
125
+ return data[pos + 1 : end].decode("utf-16le", "replace").rstrip("\0"), end
126
+
127
+
128
+ def object_info(data: bytes) -> ObjectInfo | None:
129
+ """Decode OBJECT_INFO data: u32 storage, u32 format, u32 size, ..., strings from 0x38."""
130
+ if len(data) < 0x39:
131
+ return None
132
+ _, fmt, size = struct.unpack_from("<3I", data)
133
+ try:
134
+ name, pos = _string(data, 0x38)
135
+ times = []
136
+ for _ in range(2):
137
+ if pos < len(data):
138
+ text, pos = _string(data, pos)
139
+ times.append(text)
140
+ except ValueError:
141
+ return None
142
+ times += [""] * (2 - len(times))
143
+ return ObjectInfo(name, size, fmt, times[0], times[1])
144
+
145
+
146
+ def capture_time(stamp: str) -> datetime | None:
147
+ """The camera's timestamp, without its fraction."""
148
+ try:
149
+ return datetime.strptime(stamp[:TIMESTAMP_LENGTH], TIMESTAMP_FORMAT)
150
+ except ValueError:
151
+ return None
152
+
153
+
154
+ def file_name(handle: int, *candidates: str | None) -> str:
155
+ """A safe local file name for an image: the last component of the first
156
+ candidate that is a plain file name, else one made from the handle.
157
+
158
+ The candidates come from the camera, which is untrusted: a name with a
159
+ directory part, a leading dot or dash, characters other than letters,
160
+ digits, '.', '_' and '-', or an extension outside MEDIA_EXTENSIONS is never used.
161
+ """
162
+ for raw in candidates:
163
+ name = PureWindowsPath(raw or "").name # splits on / and \, and drops a B: drive
164
+ if FILE_NAME.fullmatch(name) and PureWindowsPath(name).suffix.lower() in MEDIA_EXTENSIONS:
165
+ return name
166
+ return FALLBACK_NAME.format(handle=handle)