cannonball-eos 0.1.0__tar.gz
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_eos-0.1.0/.gitignore +6 -0
- cannonball_eos-0.1.0/LICENSE +21 -0
- cannonball_eos-0.1.0/PKG-INFO +114 -0
- cannonball_eos-0.1.0/README.md +98 -0
- cannonball_eos-0.1.0/cannonball/__init__.py +1 -0
- cannonball_eos-0.1.0/cannonball/__main__.py +304 -0
- cannonball_eos-0.1.0/cannonball/app.py +19 -0
- cannonball_eos-0.1.0/cannonball/cannonball.service +13 -0
- cannonball_eos-0.1.0/cannonball/canon.py +166 -0
- cannonball_eos-0.1.0/cannonball/config.py +249 -0
- cannonball_eos-0.1.0/cannonball/consts.py +69 -0
- cannonball_eos-0.1.0/cannonball/defaults.toml +63 -0
- cannonball_eos-0.1.0/cannonball/discovery.py +290 -0
- cannonball_eos-0.1.0/cannonball/dnssd.py +303 -0
- cannonball_eos-0.1.0/cannonball/drawing.py +34 -0
- cannonball_eos-0.1.0/cannonball/localnet.py +22 -0
- cannonball_eos-0.1.0/cannonball/menubar.py +296 -0
- cannonball_eos-0.1.0/cannonball/ptpip.py +231 -0
- cannonball_eos-0.1.0/cannonball/services.py +31 -0
- cannonball_eos-0.1.0/cannonball/status.py +84 -0
- cannonball_eos-0.1.0/cannonball/systemd.py +31 -0
- cannonball_eos-0.1.0/cannonball/worker.py +340 -0
- cannonball_eos-0.1.0/pyproject.toml +35 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Thomer Gil
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: cannonball-eos
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Saves the photos a Canon EOS camera sends with Auto send images to computer
|
|
5
|
+
Project-URL: Homepage, https://github.com/thomergil/cannonball
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Classifier: Environment :: No Input/Output (Daemon)
|
|
9
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Topic :: Multimedia :: Graphics :: Capture :: Digital Camera
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
|
+
Requires-Dist: ifaddr==0.2.0
|
|
14
|
+
Requires-Dist: zeroconf==0.154.0
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
<img src="https://raw.githubusercontent.com/thomergil/cannonball/main/packaging/macos/icon.png" width="96" alt="">
|
|
18
|
+
|
|
19
|
+
# Cannonball
|
|
20
|
+
|
|
21
|
+
Saves the photos a Canon EOS camera sends with **Auto send images to computer**.
|
|
22
|
+
A replacement for Canon Image Transfer Utility 2, for macOS and Linux. Tested
|
|
23
|
+
with an EOS 90D.
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
**macOS 13+, Apple Silicon:** download
|
|
28
|
+
[Cannonball.dmg](https://github.com/thomergil/cannonball/releases/latest/download/Cannonball.dmg)
|
|
29
|
+
([SHA-256](https://github.com/thomergil/cannonball/releases/latest/download/Cannonball.dmg.sha256)), drag
|
|
30
|
+
Cannonball to Applications, open it, and allow local network access. It lives
|
|
31
|
+
in the menu bar and opens at login. Or with Homebrew:
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
brew tap thomergil/tap
|
|
35
|
+
brew trust --cask thomergil/tap/cannonball # Homebrew asks before loading a cask from a tap
|
|
36
|
+
brew install --cask thomergil/tap/cannonball
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
**Linux** (Python 3.11+, systemd; uses avahi-daemon if it is running, otherwise python-zeroconf):
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
uv tool install cannonball-eos # or: pipx install cannonball-eos
|
|
43
|
+
cannonball --install-service # runs it now and at login
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Pair the camera
|
|
47
|
+
|
|
48
|
+
With Cannonball running, on the camera: **Wireless settings > Wi-Fi function >
|
|
49
|
+
Auto send images to computer > Auto send: Enable**, then pick your network and
|
|
50
|
+
this computer. Switch the camera off and on; from then on it sends new photos
|
|
51
|
+
each time it is switched on. A pairing made with Canon's utility on this Mac
|
|
52
|
+
works as is.
|
|
53
|
+
|
|
54
|
+
## Configure
|
|
55
|
+
|
|
56
|
+
Optional, in `~/.config/cannonball/config.toml`:
|
|
57
|
+
|
|
58
|
+
```toml
|
|
59
|
+
hosts = ["192.168.1.50"] # the camera's address, if fixed; Cannonball then finds it faster
|
|
60
|
+
networks = ["192.168.1.0/24"] # where Cannonball works; default: private and link-local ranges
|
|
61
|
+
|
|
62
|
+
[download]
|
|
63
|
+
destination = "~/Pictures"
|
|
64
|
+
subfolder = "{date:%Y_%m_%d}" # by capture date; "" for none
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Every setting is in [`cannonball/defaults.toml`](https://github.com/thomergil/cannonball/blob/main/cannonball/defaults.toml).
|
|
68
|
+
Restart Cannonball after a change (Linux: `systemctl --user restart cannonball`). Logs: `~/Library/Logs/cannonball.log` (macOS),
|
|
69
|
+
`~/.local/state/cannonball/cannonball.log` (Linux).
|
|
70
|
+
|
|
71
|
+
## Notes
|
|
72
|
+
|
|
73
|
+
- A photo is confirmed to the camera only once it is on disk; an interrupted one
|
|
74
|
+
is sent again, from the start.
|
|
75
|
+
- The camera's Wi-Fi is fickle: a transfer can take two or three tries. If it
|
|
76
|
+
fails, switch the camera off, wait a few seconds, switch it on, and wait 30
|
|
77
|
+
seconds; the first photo can take that long to start.
|
|
78
|
+
- While photos are coming in, the menu bar camera shimmers and the red camera
|
|
79
|
+
icon on the camera flickers.
|
|
80
|
+
- The camera decides which photos to send (Image sending options).
|
|
81
|
+
- Any device on `networks` can pose as the camera. Cannonball writes only plain
|
|
82
|
+
files inside the download folder, and on macOS opens no listening sockets.
|
|
83
|
+
|
|
84
|
+
## Development
|
|
85
|
+
|
|
86
|
+
```sh
|
|
87
|
+
python3 -m venv env
|
|
88
|
+
env/bin/pip install --require-hashes --only-binary :all: -r requirements.txt -r requirements-dev.txt
|
|
89
|
+
env/bin/python -m cannonball -v # run in the foreground
|
|
90
|
+
env/bin/python -m pytest # tests, against a simulated camera
|
|
91
|
+
scripts/build-macos.sh # dist/Cannonball-<version>.dmg
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Sources
|
|
95
|
+
|
|
96
|
+
- Protocol: Canon's auto-send session as documented from packet captures by
|
|
97
|
+
[epsimatic/canon-wifi-downloader](https://github.com/epsimatic/canon-wifi-downloader/blob/85b60cd468af20db3940dec9d1ba7d2a7a229afe/PROTOCOL.md).
|
|
98
|
+
The tests check that Cannonball's own client sends exactly the same bytes as
|
|
99
|
+
that project's, which they download at a pinned commit and verify by SHA-256.
|
|
100
|
+
- PTP/IP: CIPA DC-X005; Canon opcodes and session ID from
|
|
101
|
+
[libgphoto2](https://github.com/gphoto/libgphoto2) and its
|
|
102
|
+
[issue #333](https://github.com/gphoto/libgphoto2/issues/333).
|
|
103
|
+
- Libraries: [python-zeroconf](https://github.com/python-zeroconf/python-zeroconf) (LGPL-2.1),
|
|
104
|
+
[ifaddr](https://github.com/ifaddr/ifaddr) (MIT), [PyObjC](https://github.com/ronaldoussoren/pyobjc) (MIT).
|
|
105
|
+
The app is built with [PyInstaller](https://github.com/pyinstaller/pyinstaller) on
|
|
106
|
+
[python-build-standalone](https://github.com/astral-sh/python-build-standalone).
|
|
107
|
+
- Supply chain: the Mac app and the tests use dependency wheels pinned by
|
|
108
|
+
SHA-256 (matching PyPI), and the PyPI package pins the same versions. The
|
|
109
|
+
bundled Python is checksum-verified by [uv](https://github.com/astral-sh/uv),
|
|
110
|
+
and CI actions are pinned by commit.
|
|
111
|
+
|
|
112
|
+
## License
|
|
113
|
+
|
|
114
|
+
MIT. Not affiliated with Canon. Canon and EOS are trademarks of Canon Inc.
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
<img src="https://raw.githubusercontent.com/thomergil/cannonball/main/packaging/macos/icon.png" width="96" alt="">
|
|
2
|
+
|
|
3
|
+
# Cannonball
|
|
4
|
+
|
|
5
|
+
Saves the photos a Canon EOS camera sends with **Auto send images to computer**.
|
|
6
|
+
A replacement for Canon Image Transfer Utility 2, for macOS and Linux. Tested
|
|
7
|
+
with an EOS 90D.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
**macOS 13+, Apple Silicon:** download
|
|
12
|
+
[Cannonball.dmg](https://github.com/thomergil/cannonball/releases/latest/download/Cannonball.dmg)
|
|
13
|
+
([SHA-256](https://github.com/thomergil/cannonball/releases/latest/download/Cannonball.dmg.sha256)), drag
|
|
14
|
+
Cannonball to Applications, open it, and allow local network access. It lives
|
|
15
|
+
in the menu bar and opens at login. Or with Homebrew:
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
brew tap thomergil/tap
|
|
19
|
+
brew trust --cask thomergil/tap/cannonball # Homebrew asks before loading a cask from a tap
|
|
20
|
+
brew install --cask thomergil/tap/cannonball
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
**Linux** (Python 3.11+, systemd; uses avahi-daemon if it is running, otherwise python-zeroconf):
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
uv tool install cannonball-eos # or: pipx install cannonball-eos
|
|
27
|
+
cannonball --install-service # runs it now and at login
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Pair the camera
|
|
31
|
+
|
|
32
|
+
With Cannonball running, on the camera: **Wireless settings > Wi-Fi function >
|
|
33
|
+
Auto send images to computer > Auto send: Enable**, then pick your network and
|
|
34
|
+
this computer. Switch the camera off and on; from then on it sends new photos
|
|
35
|
+
each time it is switched on. A pairing made with Canon's utility on this Mac
|
|
36
|
+
works as is.
|
|
37
|
+
|
|
38
|
+
## Configure
|
|
39
|
+
|
|
40
|
+
Optional, in `~/.config/cannonball/config.toml`:
|
|
41
|
+
|
|
42
|
+
```toml
|
|
43
|
+
hosts = ["192.168.1.50"] # the camera's address, if fixed; Cannonball then finds it faster
|
|
44
|
+
networks = ["192.168.1.0/24"] # where Cannonball works; default: private and link-local ranges
|
|
45
|
+
|
|
46
|
+
[download]
|
|
47
|
+
destination = "~/Pictures"
|
|
48
|
+
subfolder = "{date:%Y_%m_%d}" # by capture date; "" for none
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Every setting is in [`cannonball/defaults.toml`](https://github.com/thomergil/cannonball/blob/main/cannonball/defaults.toml).
|
|
52
|
+
Restart Cannonball after a change (Linux: `systemctl --user restart cannonball`). Logs: `~/Library/Logs/cannonball.log` (macOS),
|
|
53
|
+
`~/.local/state/cannonball/cannonball.log` (Linux).
|
|
54
|
+
|
|
55
|
+
## Notes
|
|
56
|
+
|
|
57
|
+
- A photo is confirmed to the camera only once it is on disk; an interrupted one
|
|
58
|
+
is sent again, from the start.
|
|
59
|
+
- The camera's Wi-Fi is fickle: a transfer can take two or three tries. If it
|
|
60
|
+
fails, switch the camera off, wait a few seconds, switch it on, and wait 30
|
|
61
|
+
seconds; the first photo can take that long to start.
|
|
62
|
+
- While photos are coming in, the menu bar camera shimmers and the red camera
|
|
63
|
+
icon on the camera flickers.
|
|
64
|
+
- The camera decides which photos to send (Image sending options).
|
|
65
|
+
- Any device on `networks` can pose as the camera. Cannonball writes only plain
|
|
66
|
+
files inside the download folder, and on macOS opens no listening sockets.
|
|
67
|
+
|
|
68
|
+
## Development
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
python3 -m venv env
|
|
72
|
+
env/bin/pip install --require-hashes --only-binary :all: -r requirements.txt -r requirements-dev.txt
|
|
73
|
+
env/bin/python -m cannonball -v # run in the foreground
|
|
74
|
+
env/bin/python -m pytest # tests, against a simulated camera
|
|
75
|
+
scripts/build-macos.sh # dist/Cannonball-<version>.dmg
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Sources
|
|
79
|
+
|
|
80
|
+
- Protocol: Canon's auto-send session as documented from packet captures by
|
|
81
|
+
[epsimatic/canon-wifi-downloader](https://github.com/epsimatic/canon-wifi-downloader/blob/85b60cd468af20db3940dec9d1ba7d2a7a229afe/PROTOCOL.md).
|
|
82
|
+
The tests check that Cannonball's own client sends exactly the same bytes as
|
|
83
|
+
that project's, which they download at a pinned commit and verify by SHA-256.
|
|
84
|
+
- PTP/IP: CIPA DC-X005; Canon opcodes and session ID from
|
|
85
|
+
[libgphoto2](https://github.com/gphoto/libgphoto2) and its
|
|
86
|
+
[issue #333](https://github.com/gphoto/libgphoto2/issues/333).
|
|
87
|
+
- Libraries: [python-zeroconf](https://github.com/python-zeroconf/python-zeroconf) (LGPL-2.1),
|
|
88
|
+
[ifaddr](https://github.com/ifaddr/ifaddr) (MIT), [PyObjC](https://github.com/ronaldoussoren/pyobjc) (MIT).
|
|
89
|
+
The app is built with [PyInstaller](https://github.com/pyinstaller/pyinstaller) on
|
|
90
|
+
[python-build-standalone](https://github.com/astral-sh/python-build-standalone).
|
|
91
|
+
- Supply chain: the Mac app and the tests use dependency wheels pinned by
|
|
92
|
+
SHA-256 (matching PyPI), and the PyPI package pins the same versions. The
|
|
93
|
+
bundled Python is checksum-verified by [uv](https://github.com/astral-sh/uv),
|
|
94
|
+
and CI actions are pinned by commit.
|
|
95
|
+
|
|
96
|
+
## License
|
|
97
|
+
|
|
98
|
+
MIT. Not affiliated with Canon. Canon and EOS are trademarks of Canon Inc.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -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()
|
|
@@ -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
|