fujistuff 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.
- fujistuff-0.1.0/PKG-INFO +116 -0
- fujistuff-0.1.0/README.md +101 -0
- fujistuff-0.1.0/pyproject.toml +40 -0
- fujistuff-0.1.0/pyproject.toml.orig +31 -0
- fujistuff-0.1.0/src/fujistuff/__init__.py +0 -0
- fujistuff-0.1.0/src/fujistuff/ble.py +367 -0
- fujistuff-0.1.0/src/fujistuff/blob.py +55 -0
- fujistuff-0.1.0/src/fujistuff/cameras/gen3.yaml +155 -0
- fujistuff-0.1.0/src/fujistuff/cameras/xt3-menu.yaml +1411 -0
- fujistuff-0.1.0/src/fujistuff/cameras/xt3-tether.yaml +132 -0
- fujistuff-0.1.0/src/fujistuff/cameras/xt3.yaml +764 -0
- fujistuff-0.1.0/src/fujistuff/cameras/xt30.yaml +193 -0
- fujistuff-0.1.0/src/fujistuff/catalogue.py +268 -0
- fujistuff-0.1.0/src/fujistuff/cli.py +131 -0
- fujistuff-0.1.0/src/fujistuff/decode.py +121 -0
- fujistuff-0.1.0/src/fujistuff/measure.py +62 -0
- fujistuff-0.1.0/src/fujistuff/menu.py +122 -0
- fujistuff-0.1.0/src/fujistuff/models.py +146 -0
- fujistuff-0.1.0/src/fujistuff/ptp.py +424 -0
- fujistuff-0.1.0/src/fujistuff/recipes.py +176 -0
- fujistuff-0.1.0/src/fujistuff/rounds.py +269 -0
- fujistuff-0.1.0/src/fujistuff/settings.py +94 -0
- fujistuff-0.1.0/src/fujistuff/store.py +104 -0
- fujistuff-0.1.0/src/fujistuff/sync.py +353 -0
- fujistuff-0.1.0/src/fujistuff/ui.py +13 -0
- fujistuff-0.1.0/src/fujistuff/walk.py +502 -0
- fujistuff-0.1.0/src/fujistuff/walkplan.py +191 -0
fujistuff-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fujistuff
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Back up, version and edit Fujifilm custom settings (C1–C7) and film simulation recipes: X-T3 read and write, X100VI, X-T5, X-T2 and more read-only
|
|
5
|
+
Keywords: fujifilm,film-simulation,recipes,custom-settings,x-t3,x100vi,x-t5,ptp,bluetooth-le
|
|
6
|
+
Author: Fabian Baumgartner
|
|
7
|
+
Author-email: Fabian Baumgartner <25006255+gardenbaum@users.noreply.github.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
Requires-Dist: bleak>=3.0.2
|
|
10
|
+
Requires-Dist: pyusb>=1.3.1
|
|
11
|
+
Requires-Dist: pyyaml>=6.0.3
|
|
12
|
+
Requires-Python: >=3.12
|
|
13
|
+
Project-URL: Repository, https://github.com/gardenbaum/fujistuff
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# fujistuff
|
|
17
|
+
|
|
18
|
+
Back up, version and edit the custom settings (C1–C7) and film simulation recipes of a Fujifilm camera
|
|
19
|
+
from the Mac, over USB or Bluetooth. Made on an X-T3 (firmware 5.11), where it reads and writes; on [many other
|
|
20
|
+
X-series and GFX cameras](#supported-cameras) it reads your C1–C7 and saves them as recipes.
|
|
21
|
+
At your own risk; not affiliated with FUJIFILM, see [Warranty](#warranty).
|
|
22
|
+
|
|
23
|
+
`fuji pull` turns the camera's settings backup into a readable `camera/xt3/settings.yaml`:
|
|
24
|
+
|
|
25
|
+
```yaml
|
|
26
|
+
slots:
|
|
27
|
+
C2:
|
|
28
|
+
film_simulation: Classic Chrome
|
|
29
|
+
dynamic_range: Auto
|
|
30
|
+
color: -1
|
|
31
|
+
highlight: -1
|
|
32
|
+
shadow: 2
|
|
33
|
+
color_chrome: Strong
|
|
34
|
+
grain: Strong
|
|
35
|
+
name: PORTRA 400
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
On the X-T3: edit it, run `fuji push`, and the recipe is on the camera. Every pull and push keeps a backup in
|
|
39
|
+
`camera/xt3/backups/` and commits `settings.yaml`, so you can always go back with `fuji restore`.
|
|
40
|
+
`fuji recipe import` saves a slot as a recipe file in `recipes/`, `fuji recipe assign` writes a recipe into a slot.
|
|
41
|
+
|
|
42
|
+
## Supported cameras
|
|
43
|
+
|
|
44
|
+
| Camera | Read: `fuji pull`, `fuji recipe import` | Write: `fuji push`, `fuji restore` |
|
|
45
|
+
|---|---|---|
|
|
46
|
+
| X-T3 | yes, tested | yes, tested |
|
|
47
|
+
| X-T30 | yes, untested | no |
|
|
48
|
+
| X100F, X-Pro2, X-T2, X-T20, X-E3 | yes, untested | no |
|
|
49
|
+
| X-H2, X-H2S, X-T5, X-T50, X-S20, X-M5, X-E5, X-T30 III, X100VI, GFX100 II, GFX100S II, GFX100RF | yes, untested (USB) | no |
|
|
50
|
+
| X-T4, X-T30 II, X-S10, X-E4, X-Pro3, X100V, X-half and others | not yet | no |
|
|
51
|
+
|
|
52
|
+
"Untested" means the layout comes from what [grawji](https://github.com/p5k369/grawji) measured on other bodies,
|
|
53
|
+
and nobody has checked it with fujistuff on that camera yet. The newer cameras keep C1–C7 as separate settings:
|
|
54
|
+
reading them selects each slot in turn and then the one you had selected.
|
|
55
|
+
|
|
56
|
+
**Have one of these cameras?** Run `fuji pull`, compare `settings.yaml` with the camera menu and
|
|
57
|
+
[tell us what you found](https://github.com/gardenbaum/fujistuff/issues/new?template=camera-test.yml).
|
|
58
|
+
That is how a camera gets from "untested" to "tested", and from "not yet" to supported.
|
|
59
|
+
|
|
60
|
+
## Install
|
|
61
|
+
|
|
62
|
+
```sh
|
|
63
|
+
brew install libusb
|
|
64
|
+
uv tool install fujistuff # or: pipx install fujistuff
|
|
65
|
+
mkdir fuji-settings && cd fuji-settings && git init
|
|
66
|
+
fuji pull # camera on USB, set to USB RAW CONV./BACKUP RESTORE
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
fujistuff keeps your settings in that git repository: each pull and push is a commit, so you can see what
|
|
70
|
+
changed and go back. Settings land in `camera/<model>/settings.yaml`, e.g. `camera/x100vi/settings.yaml`.
|
|
71
|
+
|
|
72
|
+
## Two ways to connect (X-T3)
|
|
73
|
+
|
|
74
|
+
| | USB | Bluetooth |
|
|
75
|
+
|---|---|---|
|
|
76
|
+
| `fuji pull`, `fuji decode walk`, `fuji decode watch` | yes (default) | `--bluetooth` |
|
|
77
|
+
| `fuji push`, `fuji restore` | yes (default) | `--bluetooth`, after `fuji test-write` |
|
|
78
|
+
| `fuji decode rounds` | yes | no, needs USB tethering |
|
|
79
|
+
|
|
80
|
+
**USB:** camera in `USB RAW CONV./BACKUP RESTORE`, `brew install libusb`.
|
|
81
|
+
|
|
82
|
+
**Bluetooth:** the cable must be out. Pair once with `fuji pair` while the camera shows
|
|
83
|
+
`Bluetooth/SMARTPHONE SETTING > PAIRING REGISTRATION`. This adds a pairing entry on the camera; close the phone app.
|
|
84
|
+
The key stays in `.ble-key.json`, outside git.
|
|
85
|
+
|
|
86
|
+
`fuji decode walk --bluetooth` needs no cable. You set each menu item back yourself; the walk checks it and compares
|
|
87
|
+
everything at the end. It does not find out whether a restore brings a field back (`readonly`), the walk over USB does.
|
|
88
|
+
|
|
89
|
+
**Writing over Bluetooth is experimental** and locked. `fuji test-write` sends the settings back unchanged and unlocks it
|
|
90
|
+
if the same settings come back. Keep a USB backup. Pairing again locks it.
|
|
91
|
+
|
|
92
|
+
Backups contain the camera's serial number (and that of the attached lens). fujistuff commits them to your
|
|
93
|
+
repository so you can always go back; before you push that repository anywhere public, add `camera/*/backups/`
|
|
94
|
+
to its `.gitignore` and keep your own copy of those folders (e.g. Time Machine).
|
|
95
|
+
|
|
96
|
+
## Warranty
|
|
97
|
+
|
|
98
|
+
Fujifilm's [Camera Control SDK page](https://www.fujifilm-x.com/global/camera-control-sdk/) states that using
|
|
99
|
+
the SDK to connect to or control a compatible camera voids the camera's limited product warranty. fujistuff does
|
|
100
|
+
not use that SDK, but it talks to the camera over the same USB protocol and is not licensed by Fujifilm.
|
|
101
|
+
[Fuji X Weekly reports](https://fujixweekly.com/2026/06/08/your-cameras-warranty-might-be-voided/) that Fujifilm
|
|
102
|
+
applies this to any non-licensed program, and quotes an unnamed Fujifilm contact saying the camera records each
|
|
103
|
+
such connection; Fujifilm's own page does not say that. Laws in your country may limit such terms.
|
|
104
|
+
**Use fujistuff at your own risk.**
|
|
105
|
+
|
|
106
|
+
## Credits
|
|
107
|
+
|
|
108
|
+
fujistuff contains no third-party code. It builds on facts others found and published:
|
|
109
|
+
|
|
110
|
+
- [grawji](https://github.com/p5k369/grawji) (GPL-3.0): the X-T3 backup layout of the C1–C7 slots, the checksum
|
|
111
|
+
formula, the restore sequence over PTP and the read-back classification. Fields from it carry
|
|
112
|
+
`source: grawji` in `src/fujistuff/cameras/`. The read-only camera layouts and codes are theirs, too.
|
|
113
|
+
- [maam00/dialin-tools](https://github.com/maam00/dialin-tools) (MIT): the Bluetooth backup protocol.
|
|
114
|
+
- [rawji](https://github.com/pinpox/rawji) (GPL-3.0-or-later): the film simulation, white balance, grain and noise
|
|
115
|
+
reduction codes of the newer cameras.
|
|
116
|
+
- [tiredboffin/fffw](https://github.com/tiredboffin/fffw) (MIT): the X-T3 Bluetooth GATT table.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# fujistuff
|
|
2
|
+
|
|
3
|
+
Back up, version and edit the custom settings (C1–C7) and film simulation recipes of a Fujifilm camera
|
|
4
|
+
from the Mac, over USB or Bluetooth. Made on an X-T3 (firmware 5.11), where it reads and writes; on [many other
|
|
5
|
+
X-series and GFX cameras](#supported-cameras) it reads your C1–C7 and saves them as recipes.
|
|
6
|
+
At your own risk; not affiliated with FUJIFILM, see [Warranty](#warranty).
|
|
7
|
+
|
|
8
|
+
`fuji pull` turns the camera's settings backup into a readable `camera/xt3/settings.yaml`:
|
|
9
|
+
|
|
10
|
+
```yaml
|
|
11
|
+
slots:
|
|
12
|
+
C2:
|
|
13
|
+
film_simulation: Classic Chrome
|
|
14
|
+
dynamic_range: Auto
|
|
15
|
+
color: -1
|
|
16
|
+
highlight: -1
|
|
17
|
+
shadow: 2
|
|
18
|
+
color_chrome: Strong
|
|
19
|
+
grain: Strong
|
|
20
|
+
name: PORTRA 400
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
On the X-T3: edit it, run `fuji push`, and the recipe is on the camera. Every pull and push keeps a backup in
|
|
24
|
+
`camera/xt3/backups/` and commits `settings.yaml`, so you can always go back with `fuji restore`.
|
|
25
|
+
`fuji recipe import` saves a slot as a recipe file in `recipes/`, `fuji recipe assign` writes a recipe into a slot.
|
|
26
|
+
|
|
27
|
+
## Supported cameras
|
|
28
|
+
|
|
29
|
+
| Camera | Read: `fuji pull`, `fuji recipe import` | Write: `fuji push`, `fuji restore` |
|
|
30
|
+
|---|---|---|
|
|
31
|
+
| X-T3 | yes, tested | yes, tested |
|
|
32
|
+
| X-T30 | yes, untested | no |
|
|
33
|
+
| X100F, X-Pro2, X-T2, X-T20, X-E3 | yes, untested | no |
|
|
34
|
+
| X-H2, X-H2S, X-T5, X-T50, X-S20, X-M5, X-E5, X-T30 III, X100VI, GFX100 II, GFX100S II, GFX100RF | yes, untested (USB) | no |
|
|
35
|
+
| X-T4, X-T30 II, X-S10, X-E4, X-Pro3, X100V, X-half and others | not yet | no |
|
|
36
|
+
|
|
37
|
+
"Untested" means the layout comes from what [grawji](https://github.com/p5k369/grawji) measured on other bodies,
|
|
38
|
+
and nobody has checked it with fujistuff on that camera yet. The newer cameras keep C1–C7 as separate settings:
|
|
39
|
+
reading them selects each slot in turn and then the one you had selected.
|
|
40
|
+
|
|
41
|
+
**Have one of these cameras?** Run `fuji pull`, compare `settings.yaml` with the camera menu and
|
|
42
|
+
[tell us what you found](https://github.com/gardenbaum/fujistuff/issues/new?template=camera-test.yml).
|
|
43
|
+
That is how a camera gets from "untested" to "tested", and from "not yet" to supported.
|
|
44
|
+
|
|
45
|
+
## Install
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
brew install libusb
|
|
49
|
+
uv tool install fujistuff # or: pipx install fujistuff
|
|
50
|
+
mkdir fuji-settings && cd fuji-settings && git init
|
|
51
|
+
fuji pull # camera on USB, set to USB RAW CONV./BACKUP RESTORE
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
fujistuff keeps your settings in that git repository: each pull and push is a commit, so you can see what
|
|
55
|
+
changed and go back. Settings land in `camera/<model>/settings.yaml`, e.g. `camera/x100vi/settings.yaml`.
|
|
56
|
+
|
|
57
|
+
## Two ways to connect (X-T3)
|
|
58
|
+
|
|
59
|
+
| | USB | Bluetooth |
|
|
60
|
+
|---|---|---|
|
|
61
|
+
| `fuji pull`, `fuji decode walk`, `fuji decode watch` | yes (default) | `--bluetooth` |
|
|
62
|
+
| `fuji push`, `fuji restore` | yes (default) | `--bluetooth`, after `fuji test-write` |
|
|
63
|
+
| `fuji decode rounds` | yes | no, needs USB tethering |
|
|
64
|
+
|
|
65
|
+
**USB:** camera in `USB RAW CONV./BACKUP RESTORE`, `brew install libusb`.
|
|
66
|
+
|
|
67
|
+
**Bluetooth:** the cable must be out. Pair once with `fuji pair` while the camera shows
|
|
68
|
+
`Bluetooth/SMARTPHONE SETTING > PAIRING REGISTRATION`. This adds a pairing entry on the camera; close the phone app.
|
|
69
|
+
The key stays in `.ble-key.json`, outside git.
|
|
70
|
+
|
|
71
|
+
`fuji decode walk --bluetooth` needs no cable. You set each menu item back yourself; the walk checks it and compares
|
|
72
|
+
everything at the end. It does not find out whether a restore brings a field back (`readonly`), the walk over USB does.
|
|
73
|
+
|
|
74
|
+
**Writing over Bluetooth is experimental** and locked. `fuji test-write` sends the settings back unchanged and unlocks it
|
|
75
|
+
if the same settings come back. Keep a USB backup. Pairing again locks it.
|
|
76
|
+
|
|
77
|
+
Backups contain the camera's serial number (and that of the attached lens). fujistuff commits them to your
|
|
78
|
+
repository so you can always go back; before you push that repository anywhere public, add `camera/*/backups/`
|
|
79
|
+
to its `.gitignore` and keep your own copy of those folders (e.g. Time Machine).
|
|
80
|
+
|
|
81
|
+
## Warranty
|
|
82
|
+
|
|
83
|
+
Fujifilm's [Camera Control SDK page](https://www.fujifilm-x.com/global/camera-control-sdk/) states that using
|
|
84
|
+
the SDK to connect to or control a compatible camera voids the camera's limited product warranty. fujistuff does
|
|
85
|
+
not use that SDK, but it talks to the camera over the same USB protocol and is not licensed by Fujifilm.
|
|
86
|
+
[Fuji X Weekly reports](https://fujixweekly.com/2026/06/08/your-cameras-warranty-might-be-voided/) that Fujifilm
|
|
87
|
+
applies this to any non-licensed program, and quotes an unnamed Fujifilm contact saying the camera records each
|
|
88
|
+
such connection; Fujifilm's own page does not say that. Laws in your country may limit such terms.
|
|
89
|
+
**Use fujistuff at your own risk.**
|
|
90
|
+
|
|
91
|
+
## Credits
|
|
92
|
+
|
|
93
|
+
fujistuff contains no third-party code. It builds on facts others found and published:
|
|
94
|
+
|
|
95
|
+
- [grawji](https://github.com/p5k369/grawji) (GPL-3.0): the X-T3 backup layout of the C1–C7 slots, the checksum
|
|
96
|
+
formula, the restore sequence over PTP and the read-back classification. Fields from it carry
|
|
97
|
+
`source: grawji` in `src/fujistuff/cameras/`. The read-only camera layouts and codes are theirs, too.
|
|
98
|
+
- [maam00/dialin-tools](https://github.com/maam00/dialin-tools) (MIT): the Bluetooth backup protocol.
|
|
99
|
+
- [rawji](https://github.com/pinpox/rawji) (GPL-3.0-or-later): the film simulation, white balance, grain and noise
|
|
100
|
+
reduction codes of the newer cameras.
|
|
101
|
+
- [tiredboffin/fffw](https://github.com/tiredboffin/fffw) (MIT): the X-T3 Bluetooth GATT table.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "fujistuff"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Back up, version and edit Fujifilm custom settings (C1–C7) and film simulation recipes: X-T3 read and write, X100VI, X-T5, X-T2 and more read-only"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
keywords = [
|
|
8
|
+
"fujifilm",
|
|
9
|
+
"film-simulation",
|
|
10
|
+
"recipes",
|
|
11
|
+
"custom-settings",
|
|
12
|
+
"x-t3",
|
|
13
|
+
"x100vi",
|
|
14
|
+
"x-t5",
|
|
15
|
+
"ptp",
|
|
16
|
+
"bluetooth-le",
|
|
17
|
+
]
|
|
18
|
+
requires-python = ">=3.12"
|
|
19
|
+
dependencies = [
|
|
20
|
+
"bleak>=3.0.2",
|
|
21
|
+
"pyusb>=1.3.1",
|
|
22
|
+
"pyyaml>=6.0.3",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[[project.authors]]
|
|
26
|
+
name = "Fabian Baumgartner"
|
|
27
|
+
email = "25006255+gardenbaum@users.noreply.github.com"
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Repository = "https://github.com/gardenbaum/fujistuff"
|
|
31
|
+
|
|
32
|
+
[project.scripts]
|
|
33
|
+
fuji = "fujistuff.cli:main"
|
|
34
|
+
|
|
35
|
+
[build-system]
|
|
36
|
+
requires = ["uv_build>=0.13.8,<0.14.0"]
|
|
37
|
+
build-backend = "uv_build"
|
|
38
|
+
|
|
39
|
+
[dependency-groups]
|
|
40
|
+
dev = ["pytest>=9.2.0"]
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "fujistuff"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Back up, version and edit Fujifilm custom settings (C1–C7) and film simulation recipes: X-T3 read and write, X100VI, X-T5, X-T2 and more read-only"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
keywords = ["fujifilm", "film-simulation", "recipes", "custom-settings", "x-t3", "x100vi", "x-t5", "ptp", "bluetooth-le"]
|
|
8
|
+
authors = [
|
|
9
|
+
{ name = "Fabian Baumgartner", email = "25006255+gardenbaum@users.noreply.github.com" }
|
|
10
|
+
]
|
|
11
|
+
requires-python = ">=3.12"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"bleak>=3.0.2",
|
|
14
|
+
"pyusb>=1.3.1",
|
|
15
|
+
"pyyaml>=6.0.3",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.urls]
|
|
19
|
+
Repository = "https://github.com/gardenbaum/fujistuff"
|
|
20
|
+
|
|
21
|
+
[project.scripts]
|
|
22
|
+
fuji = "fujistuff.cli:main"
|
|
23
|
+
|
|
24
|
+
[build-system]
|
|
25
|
+
requires = ["uv_build>=0.13.8,<0.14.0"]
|
|
26
|
+
build-backend = "uv_build"
|
|
27
|
+
|
|
28
|
+
[dependency-groups]
|
|
29
|
+
dev = [
|
|
30
|
+
"pytest>=9.2.0",
|
|
31
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
"""Bluetooth LE as a second way to the X-T3 settings backup. Writing is locked until `fuji test-write` passed.
|
|
2
|
+
|
|
3
|
+
Protocol after maam00/dialin-tools docs/FUJIFILM-PROTOCOL.md 3.4, 3.6 and 3.7 (MIT, tested there on an X100VI) and
|
|
4
|
+
the X-T3 GATT table efaafa of tiredboffin/fffw (MIT). Results: docs/research/2026-11-23-wireless-route.md
|
|
5
|
+
"""
|
|
6
|
+
import asyncio
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import threading
|
|
11
|
+
import zlib
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from . import blob
|
|
15
|
+
from .ptp import NotConnected, PtpError
|
|
16
|
+
|
|
17
|
+
COMPANY = 0x04D8
|
|
18
|
+
FILES = "af854c2e-b214-458e-97e2-912c4ecf2cb8" # service, also the XApp advert; Camera Remote has another key
|
|
19
|
+
CAMERA_REMOTE = "117c4142-edd4-4c77-8696-dd18eebb770a"
|
|
20
|
+
KEY = "aba356eb-9633-4e60-b73f-f52516dbd671"
|
|
21
|
+
NAME = "85b9163e-62d1-49ff-a6f5-054b4630d4a1"
|
|
22
|
+
SERIAL = "00002a25-0000-1000-8000-00805f9b34fb"
|
|
23
|
+
BACKUP_REQUEST = "f14e7a88-6f57-4872-a69b-b47ef3295c9b"
|
|
24
|
+
BACKUP_STATE = "11438c83-cfb0-4511-841b-759e0d2321c8"
|
|
25
|
+
CHUNK_SIZE = "7f3400fe-17e7-4b80-8a0e-81b0343c1b49"
|
|
26
|
+
FILE_INDEX = "051dd980-df9d-4472-a2e1-35811dd24ee1"
|
|
27
|
+
CHUNK = "ac0c799a-fa6c-4df5-bbc5-bb95cce7e6ea"
|
|
28
|
+
RESULT = "68052e8a-fb91-404f-8847-0eb4be24308c"
|
|
29
|
+
TRANSFER = "2e27ed9f-5506-41cd-ba48-dac06669ad95"
|
|
30
|
+
CLIENT = b"fujistuff\0"
|
|
31
|
+
RESTORE_REQUEST = "f1897eb9-a9aa-40f0-8ce6-2fa7915bc459"
|
|
32
|
+
RESTORE_STATE = "4b3a413c-230f-42bc-b3ed-b1db2eadee82"
|
|
33
|
+
FILE_INFO = "c922ac69-9480-4348-8f4b-9ee29bc30d1d"
|
|
34
|
+
# The only writes this module can make. The uploading ones are used by upload() alone.
|
|
35
|
+
WRITABLE = {KEY, NAME, BACKUP_REQUEST, CHUNK_SIZE, FILE_INDEX, RESULT}
|
|
36
|
+
UPLOADING = {RESTORE_REQUEST, FILE_INFO, CHUNK}
|
|
37
|
+
PART = 120 # data bytes per frame, both directions
|
|
38
|
+
MTU = 133 # the last frame has up to 130 bytes plus 3 for ATT
|
|
39
|
+
SETTLE = 3 # s after a restore: the camera's screen goes dark for a moment
|
|
40
|
+
LIMIT = 1 << 20
|
|
41
|
+
GAP = 1.5 # s between two reads: without it the X-T3 answers «not ready»
|
|
42
|
+
LOOP_TIMEOUT = 120 # s, above the sum of all waits of one read
|
|
43
|
+
READY = 10 # s to wait for «ready»; a «not ready» before that is not final
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class BleError(PtpError):
|
|
47
|
+
via = "Bluetooth"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class NotFound(BleError, NotConnected):
|
|
51
|
+
"""Camera off, asleep, out of reach, or connected to the phone."""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def is_xt3(name: str | None) -> bool:
|
|
55
|
+
"""The X-T3 advertises <tag>X-T3-<tag> (seen on 5.11), fffw notes it without the hyphen; X-T30 must not match."""
|
|
56
|
+
return bool(re.fullmatch(r"(\w{4})X-T3-?\1", name or ""))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def pairing_key(name: str | None, uuids, manufacturer: dict[int, bytes]) -> bytes | None:
|
|
60
|
+
"""Key of an X-T3 in pairing mode for XApp-style clients. Adverts for Camera Remote carry a different key."""
|
|
61
|
+
data, uuids = manufacturer.get(COMPANY, b""), {u.lower() for u in uuids}
|
|
62
|
+
if is_xt3(name) and FILES in uuids and CAMERA_REMOTE not in uuids and len(data) == 5 and data[0] == 2:
|
|
63
|
+
return data[1:]
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class Assembler:
|
|
68
|
+
"""Chunks are u16 sequence, u32 length, data. The last one (0xFFFF) ends with a u16 sum of all data bytes."""
|
|
69
|
+
|
|
70
|
+
def __init__(self):
|
|
71
|
+
self.data, self.next, self.done = b"", 0, False
|
|
72
|
+
|
|
73
|
+
def add(self, raw: bytes) -> None:
|
|
74
|
+
if self.done:
|
|
75
|
+
raise BleError("chunk after the last one")
|
|
76
|
+
seq, size, part = int.from_bytes(raw[:2], "little"), int.from_bytes(raw[2:6], "little"), raw[6:]
|
|
77
|
+
if len(raw) < 6 or size > len(part):
|
|
78
|
+
raise BleError(f"malformed chunk of {len(raw)} bytes")
|
|
79
|
+
part = part[:size]
|
|
80
|
+
if seq == 0xFFFF:
|
|
81
|
+
if size < 2:
|
|
82
|
+
raise BleError("last chunk without a sum")
|
|
83
|
+
part, want = part[:-2], int.from_bytes(part[-2:], "little")
|
|
84
|
+
self.done = True
|
|
85
|
+
elif seq != self.next:
|
|
86
|
+
raise BleError(f"chunk {seq} instead of {self.next}")
|
|
87
|
+
self.next += 1
|
|
88
|
+
self.data += part
|
|
89
|
+
if len(self.data) > LIMIT:
|
|
90
|
+
raise BleError("backup is too big")
|
|
91
|
+
if self.done and sum(self.data) & 0xFFFF != want:
|
|
92
|
+
raise BleError("sum does not match, the backup arrived damaged")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def unpack(data: bytes) -> bytes:
|
|
96
|
+
if data.startswith(blob.MAGIC):
|
|
97
|
+
return data
|
|
98
|
+
z = zlib.decompressobj()
|
|
99
|
+
try:
|
|
100
|
+
out = z.decompress(data, LIMIT)
|
|
101
|
+
except zlib.error as e:
|
|
102
|
+
raise BleError(f"neither a backup nor zlib: {e}") from e
|
|
103
|
+
if not z.eof:
|
|
104
|
+
raise BleError("compressed backup is incomplete")
|
|
105
|
+
return out
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def frames(wire: bytes) -> list[bytes]:
|
|
109
|
+
"""Frames are u16 sequence, u32 length, data, u16. The last one (0xFFFF) carries the sum in the data and behind it."""
|
|
110
|
+
total, parts = (sum(wire) & 0xFFFF).to_bytes(2, "little"), [wire[i:i + PART] for i in range(0, len(wire), PART)]
|
|
111
|
+
return [(0xFFFF).to_bytes(2, "little") + (len(p) + 2).to_bytes(4, "little") + p + total + total
|
|
112
|
+
if i == len(parts) - 1 else i.to_bytes(2, "little") + len(p).to_bytes(4, "little") + p + bytes(2)
|
|
113
|
+
for i, p in enumerate(parts)]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
async def write(client, uuid: str, data: bytes, allowed=WRITABLE) -> None:
|
|
117
|
+
if uuid not in allowed:
|
|
118
|
+
raise BleError(f"write to {uuid} is not allowed")
|
|
119
|
+
await asyncio.wait_for(client.write_gatt_char(uuid, data, response=True), 10)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
async def state(queues: dict[str, asyncio.Queue], uuid: str) -> int:
|
|
123
|
+
try:
|
|
124
|
+
return int.from_bytes((await asyncio.wait_for(queues[uuid].get(), 10))[:2], "little")
|
|
125
|
+
except TimeoutError:
|
|
126
|
+
raise BleError(f"no answer from the camera ({uuid[:8]})") from None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
async def ready(queues: dict[str, asyncio.Queue], uuid: str) -> None:
|
|
130
|
+
try:
|
|
131
|
+
async with asyncio.timeout(READY):
|
|
132
|
+
while int.from_bytes((await queues[uuid].get())[:2], "little") != 1:
|
|
133
|
+
pass # «not ready» before «ready» is not final
|
|
134
|
+
except TimeoutError:
|
|
135
|
+
raise BleError("the camera is busy (cable unplugged?)") from None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
async def upload(client, queues: dict[str, asyncio.Queue], wire: bytes) -> None:
|
|
139
|
+
"""Send a restore, one acknowledged frame at a time. Only «file received» after the last frame is a success."""
|
|
140
|
+
if client.mtu_size < MTU:
|
|
141
|
+
raise BleError(f"the link carries only {client.mtu_size} bytes per packet, {MTU} are needed")
|
|
142
|
+
allowed, result, fs = WRITABLE | UPLOADING, b"\2\0", frames(wire) # 2 = cancel
|
|
143
|
+
await write(client, RESTORE_REQUEST, b"\1\0", allowed)
|
|
144
|
+
try:
|
|
145
|
+
await ready(queues, RESTORE_STATE)
|
|
146
|
+
await write(client, CHUNK_SIZE, PART.to_bytes(4, "little"))
|
|
147
|
+
await write(client, FILE_INDEX, bytes(4))
|
|
148
|
+
await write(client, FILE_INFO, b"backup.dat".ljust(40, b"\0") + len(wire).to_bytes(4, "little"), allowed)
|
|
149
|
+
if (s := await state(queues, TRANSFER)) != 1:
|
|
150
|
+
raise BleError(f"the camera did not start the restore (state {s})")
|
|
151
|
+
for i, frame in enumerate(fs, 1):
|
|
152
|
+
await write(client, CHUNK, frame, allowed)
|
|
153
|
+
s = await state(queues, TRANSFER)
|
|
154
|
+
if s != (3 if i == len(fs) else 2):
|
|
155
|
+
if s == 0:
|
|
156
|
+
result = b"\0\0"
|
|
157
|
+
raise BleError(f"the camera refused the restore (state {s} after frame {i} of {len(fs)})")
|
|
158
|
+
result = b"\3\0"
|
|
159
|
+
finally:
|
|
160
|
+
try:
|
|
161
|
+
await write(client, RESULT, result)
|
|
162
|
+
except Exception:
|
|
163
|
+
if result == b"\3\0":
|
|
164
|
+
raise # whether it was taken is open: the caller reads back
|
|
165
|
+
await asyncio.sleep(SETTLE)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
async def download(client, queues: dict[str, asyncio.Queue]) -> bytes:
|
|
169
|
+
asm, ok = Assembler(), False
|
|
170
|
+
await write(client, BACKUP_REQUEST, b"\1\0")
|
|
171
|
+
try:
|
|
172
|
+
await ready(queues, BACKUP_STATE)
|
|
173
|
+
await write(client, CHUNK_SIZE, PART.to_bytes(4, "little"))
|
|
174
|
+
await write(client, FILE_INDEX, bytes(4))
|
|
175
|
+
while (s := await state(queues, TRANSFER)) in (1, 2):
|
|
176
|
+
asm.add(bytes(await asyncio.wait_for(client.read_gatt_char(CHUNK), 10)))
|
|
177
|
+
if s != 3 or not asm.done:
|
|
178
|
+
raise BleError(f"transfer ended in state {s}, last chunk seen: {asm.done}")
|
|
179
|
+
ok = True
|
|
180
|
+
return asm.data
|
|
181
|
+
finally:
|
|
182
|
+
try:
|
|
183
|
+
await write(client, RESULT, b"\3\0" if ok else b"\0\0") # tell the camera the transfer is over
|
|
184
|
+
except Exception:
|
|
185
|
+
pass # the link is gone or will be dropped; the first error counts
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
async def find(seconds: float, match):
|
|
189
|
+
from bleak import BleakScanner
|
|
190
|
+
|
|
191
|
+
seen = {}
|
|
192
|
+
async with BleakScanner() as scanner:
|
|
193
|
+
try:
|
|
194
|
+
async with asyncio.timeout(seconds):
|
|
195
|
+
async for dev, adv in scanner.advertisement_data():
|
|
196
|
+
name = adv.local_name or dev.name
|
|
197
|
+
if COMPANY in adv.manufacturer_data or is_xt3(name):
|
|
198
|
+
seen[dev.address] = f"{name} {adv.service_uuids}"
|
|
199
|
+
if (hit := match(dev, adv, name)) is not None:
|
|
200
|
+
return dev, hit
|
|
201
|
+
except TimeoutError:
|
|
202
|
+
pass
|
|
203
|
+
raise NotFound("Camera not found over Bluetooth. Fujifilm devices seen: " + ("; ".join(seen.values()) or "none"))
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
async def register(client, key: bytes) -> dict[str, asyncio.Queue]:
|
|
207
|
+
"""Present the key and subscribe. Returns a queue of state messages per characteristic."""
|
|
208
|
+
have = {c.uuid.lower() for s in client.services for c in s.characteristics}
|
|
209
|
+
if missing := (WRITABLE | UPLOADING | {TRANSFER, BACKUP_STATE, RESTORE_STATE}) - have:
|
|
210
|
+
raise BleError(f"not the expected GATT table, missing: {sorted(missing)}")
|
|
211
|
+
await asyncio.wait_for(client.read_gatt_char(SERIAL), 10)
|
|
212
|
+
await write(client, KEY, key)
|
|
213
|
+
await write(client, NAME, CLIENT)
|
|
214
|
+
queues = {u: asyncio.Queue() for u in (BACKUP_STATE, RESTORE_STATE, TRANSFER)}
|
|
215
|
+
for s in client.services:
|
|
216
|
+
for c in s.characteristics:
|
|
217
|
+
if not {"notify", "indicate"} & set(c.properties):
|
|
218
|
+
continue
|
|
219
|
+
uuid = c.uuid.lower()
|
|
220
|
+
handler = (lambda _, d, q=queues.get(uuid): q.put_nowait(bytes(d)) if q else None)
|
|
221
|
+
try:
|
|
222
|
+
await asyncio.wait_for(client.start_notify(c, handler), 10)
|
|
223
|
+
except Exception as e:
|
|
224
|
+
if uuid in queues:
|
|
225
|
+
raise BleError(f"cannot subscribe to {uuid}: {e!r}") from e
|
|
226
|
+
await asyncio.sleep(3) # dialin-tools waits before a request; whether the X-T3 needs it is unknown
|
|
227
|
+
if not client.is_connected:
|
|
228
|
+
raise BleError("the camera closed the connection")
|
|
229
|
+
return queues
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _save(path: Path, data: dict) -> None:
|
|
233
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
234
|
+
os.fchmod(fd, 0o600) # an existing file keeps its mode otherwise
|
|
235
|
+
with os.fdopen(fd, "w") as f:
|
|
236
|
+
json.dump(data, f)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class BleCameraLink:
|
|
240
|
+
"""Reads over one connection that stays open; reconnects by itself after an error."""
|
|
241
|
+
|
|
242
|
+
connect_hint = "Unplug the cable, switch the camera on, Bluetooth ON, phone app closed …"
|
|
243
|
+
|
|
244
|
+
def __init__(self, key_path: Path, find=find, make_client=None):
|
|
245
|
+
self._key_path, self._find, self._make_client = key_path, find, make_client
|
|
246
|
+
self._client = self._queues = self._loop = None
|
|
247
|
+
self._last = float("-inf") # loop time of the last read
|
|
248
|
+
self._read_data: bytes | None = None
|
|
249
|
+
self._written = False # the next read may meet a camera that is still busy with the restore
|
|
250
|
+
|
|
251
|
+
def _run(self, coro):
|
|
252
|
+
if self._loop is None: # own thread: notifications keep coming while Fabian is asked something
|
|
253
|
+
self._loop = asyncio.new_event_loop()
|
|
254
|
+
threading.Thread(target=self._loop.run_forever, daemon=True).start()
|
|
255
|
+
fut = asyncio.run_coroutine_threadsafe(asyncio.wait_for(coro, LOOP_TIMEOUT), self._loop)
|
|
256
|
+
try:
|
|
257
|
+
return fut.result()
|
|
258
|
+
except PtpError:
|
|
259
|
+
raise
|
|
260
|
+
except KeyboardInterrupt:
|
|
261
|
+
fut.cancel()
|
|
262
|
+
raise
|
|
263
|
+
except Exception as e: # bleak has its own error per platform
|
|
264
|
+
raise BleError(f"{type(e).__name__}: {e}") from e
|
|
265
|
+
|
|
266
|
+
async def _drop(self) -> None:
|
|
267
|
+
client, self._client, self._queues = self._client, None, None
|
|
268
|
+
if client is not None:
|
|
269
|
+
try:
|
|
270
|
+
await asyncio.wait_for(client.disconnect(), 10)
|
|
271
|
+
except Exception:
|
|
272
|
+
pass # already gone
|
|
273
|
+
|
|
274
|
+
async def _connect(self, dev, key: bytes) -> None:
|
|
275
|
+
await self._drop()
|
|
276
|
+
if self._make_client is None:
|
|
277
|
+
from bleak import BleakClient
|
|
278
|
+
|
|
279
|
+
self._make_client = lambda d: BleakClient(d, timeout=20)
|
|
280
|
+
self._client = self._make_client(dev)
|
|
281
|
+
await self._client.connect()
|
|
282
|
+
self._queues = await register(self._client, key)
|
|
283
|
+
|
|
284
|
+
async def _transfer(self, saved: dict, work) -> bytes | None:
|
|
285
|
+
try:
|
|
286
|
+
if self._client is None or not self._client.is_connected:
|
|
287
|
+
dev, _ = await self._find(30, lambda d, a, name: True if d.address == saved["address"] else None)
|
|
288
|
+
await self._connect(dev, bytes.fromhex(saved["key"]))
|
|
289
|
+
loop = asyncio.get_running_loop()
|
|
290
|
+
await asyncio.sleep(max(0, self._last + GAP - loop.time()))
|
|
291
|
+
for q in self._queues.values():
|
|
292
|
+
while not q.empty():
|
|
293
|
+
q.get_nowait()
|
|
294
|
+
try:
|
|
295
|
+
return await work(self._client, self._queues)
|
|
296
|
+
finally:
|
|
297
|
+
self._last = loop.time()
|
|
298
|
+
except BaseException: # also a cancelled read: the state of the transfer is unknown, start afresh
|
|
299
|
+
await self._drop()
|
|
300
|
+
raise
|
|
301
|
+
|
|
302
|
+
def _saved(self) -> dict:
|
|
303
|
+
return json.loads(self._key_path.read_text())
|
|
304
|
+
|
|
305
|
+
def read(self) -> bytes:
|
|
306
|
+
for tries in range(3 if self._written else 1, 0, -1):
|
|
307
|
+
try:
|
|
308
|
+
self._read_data = unpack(self._run(self._transfer(self._saved(), download)))
|
|
309
|
+
break
|
|
310
|
+
except PtpError:
|
|
311
|
+
if tries == 1:
|
|
312
|
+
raise
|
|
313
|
+
self._written = False
|
|
314
|
+
return self._read_data
|
|
315
|
+
|
|
316
|
+
@property
|
|
317
|
+
def can_write(self) -> bool:
|
|
318
|
+
"""Set by the write test. Pairing again takes it back."""
|
|
319
|
+
return self._saved().get("write_tested") is True
|
|
320
|
+
|
|
321
|
+
def allow_writes(self) -> None:
|
|
322
|
+
_save(self._key_path, {**self._saved(), "write_tested": True})
|
|
323
|
+
|
|
324
|
+
def write(self, data: bytes) -> None:
|
|
325
|
+
if not self.can_write:
|
|
326
|
+
raise BleError("Writing over Bluetooth is locked, run `fuji test-write` first or use the cable")
|
|
327
|
+
self._send(data)
|
|
328
|
+
|
|
329
|
+
def write_unchanged(self, data: bytes) -> None:
|
|
330
|
+
"""For the write test: sends nothing but the backup that was just read."""
|
|
331
|
+
if data != self._read_data:
|
|
332
|
+
raise BleError("not the backup that was just read")
|
|
333
|
+
self._send(data)
|
|
334
|
+
|
|
335
|
+
def _send(self, data: bytes) -> None:
|
|
336
|
+
blob.check_xt3(data)
|
|
337
|
+
if blob.with_checksum(data) != data:
|
|
338
|
+
raise BleError("wrong checksum, nothing sent")
|
|
339
|
+
if data[blob.HEADER_AT]:
|
|
340
|
+
raise BleError("header of a USB backup, nothing sent")
|
|
341
|
+
wire = zlib.compress(data, 6) # level 6 gives the camera's own bytes, checked on five X-T3 backups
|
|
342
|
+
self._written = True # also after an error: the state of the camera is unknown then
|
|
343
|
+
try:
|
|
344
|
+
self._run(self._transfer(self._saved(), lambda c, q: upload(c, q, wire)))
|
|
345
|
+
finally:
|
|
346
|
+
self.close()
|
|
347
|
+
|
|
348
|
+
def pair(self) -> str:
|
|
349
|
+
async def go():
|
|
350
|
+
try:
|
|
351
|
+
dev, key = await self._find(
|
|
352
|
+
60, lambda d, a, name: pairing_key(name, a.service_uuids, a.manufacturer_data))
|
|
353
|
+
await self._connect(dev, key)
|
|
354
|
+
return dev, key
|
|
355
|
+
finally:
|
|
356
|
+
await self._drop()
|
|
357
|
+
|
|
358
|
+
dev, key = self._run(go())
|
|
359
|
+
_save(self._key_path, {"address": dev.address, "key": key.hex()})
|
|
360
|
+
return dev.name
|
|
361
|
+
|
|
362
|
+
def close(self) -> None:
|
|
363
|
+
if self._loop is not None:
|
|
364
|
+
try:
|
|
365
|
+
self._run(self._drop())
|
|
366
|
+
except PtpError:
|
|
367
|
+
pass # nothing left to close
|