o2sync 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.
o2sync-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pedrorivera
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,2 @@
1
+ include LICENSE README.md PROTOCOL.md constraints.txt
2
+ recursive-include tests *.py
o2sync-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.4
2
+ Name: o2sync
3
+ Version: 0.1.0
4
+ Summary: Download and plot recordings from Wellue/Viatom O2 oximeters (Checkme O2 Max, O2Ring, ...) over Bluetooth LE
5
+ Author: pedrorivera
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/pedrorivera/o2sync
8
+ Project-URL: Source, https://github.com/pedrorivera/o2sync
9
+ Project-URL: Issues, https://github.com/pedrorivera/o2sync/issues
10
+ Project-URL: Protocol notes, https://github.com/pedrorivera/o2sync/blob/main/PROTOCOL.md
11
+ Keywords: pulse oximeter,spo2,bluetooth low energy,ble,bleak,wellue,viatom,checkme o2,o2ring,sleep apnea,oscar,quantified self
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: End Users/Desktop
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Operating System :: Microsoft :: Windows
18
+ Classifier: Operating System :: MacOS
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
21
+ Classifier: Topic :: System :: Hardware
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: bleak>=0.22
26
+ Provides-Extra: plot
27
+ Requires-Dist: matplotlib>=3.5; extra == "plot"
28
+ Provides-Extra: test
29
+ Requires-Dist: pytest>=7; extra == "test"
30
+ Dynamic: license-file
31
+
32
+ # o2sync
33
+
34
+ Download and plot recordings from Wellue / Viatom "O2" pulse oximeters over Bluetooth LE — no cable, no vendor app.
35
+ Built and verified against a **Checkme O2 Max** (advertises as `O2M xxxxxx`); other devices speaking the same
36
+ "Oxy" protocol (O2Ring, Checkme O2, SleepU, WearO2, KidsO2, BabyO2, Oxylink) are matched by name but untested.
37
+
38
+ Uses [bleak](https://github.com/hbldh/bleak), so it runs on **Linux** (BlueZ) and **Windows** (WinRT), and should
39
+ work on macOS.
40
+
41
+ ## Install
42
+
43
+ ```sh
44
+ pip install o2sync # or "o2sync[plot]" for matplotlib PNG output
45
+ ```
46
+
47
+ From a checkout, for development: `pip install -e ".[test]"`.
48
+
49
+ **Linux:** needs BlueZ (`bluetoothctl` should work) and a user allowed to use D-Bus Bluetooth (default on desktop
50
+ distros). **Windows:** Windows 10/11 with Bluetooth LE. Smart App Control can block bleak's unsigned `winrt` module
51
+ ("An Application Control policy has blocked this file") until it has vetted that version; it usually clears after a
52
+ while. Installing with [constraints.txt](https://github.com/pedrorivera/o2sync/blob/main/constraints.txt)
53
+ (`pip install -c constraints.txt o2sync`) pins the versions verified to work.
54
+
55
+ ## Use
56
+
57
+ Wake the oximeter (press its button), keep it close, and close the ViHealth app on your phone — the device accepts
58
+ only one connection and only advertises for a short while after waking. It must not be recording.
59
+
60
+ ```sh
61
+ o2sync sync # scan, fix the device clock, download new files to ./recordings
62
+ o2sync sync --csv --report # ...and write CSVs + recordings/report.html
63
+ o2sync plot recordings # HTML report of everything downloaded so far
64
+ o2sync plot recordings --png pngs # matplotlib PNGs (pip install "o2sync[plot]")
65
+ o2sync csv recordings/20261202053700
66
+ o2sync scan | info | gatt # exploration helpers; o2sync raw 14 sends a raw command
67
+ ```
68
+
69
+ ### Plotting
70
+
71
+ `o2sync plot` (or `o2sync sync --report`) writes a self-contained HTML report — no plotting libraries needed — with
72
+ summary statistics and SpO₂, pulse and motion charts per recording. Gaps mark samples where the finger was off,
73
+ the dashed line marks 90 % SpO₂, and the page follows the system's light/dark theme:
74
+
75
+ ![Example o2sync report: a 30-minute recording with SpO₂ around 96–98 %, pulse 59–96 bpm and motion bars](https://raw.githubusercontent.com/pedrorivera/o2sync/main/docs/report.png)
76
+
77
+ From Python:
78
+
79
+ ```python
80
+ import o2sync
81
+
82
+ result = o2sync.sync("recordings") # -> SyncResult
83
+ for rec in result.recordings: # newly downloaded o2sync.Recording objects
84
+ print(rec.summary())
85
+ print(rec.samples[0]) # Sample(time, spo2, pulse, motion, vibration); None = invalid
86
+
87
+ rec = o2sync.Recording.from_file("recordings/20261202053700")
88
+ o2sync.save_html_report([rec], "report.html")
89
+ ```
90
+
91
+ `sync()` never deletes anything from the device and skips files already present in the output folder. Files are
92
+ saved unchanged under their device name (`yyyyMMddHHmmss`), the raw format other tools such as OSCAR import.
93
+ The device keeps a rolling buffer and drops its oldest recordings by itself, so sync regularly.
94
+ Pass `set_time=False` to leave the device clock alone or `address=` to skip scanning. An async variant, `o2sync.async_sync()`, and a lower-level `o2sync.O2Client` are available.
95
+
96
+ ## How it works
97
+
98
+ See [PROTOCOL.md](https://github.com/pedrorivera/o2sync/blob/main/PROTOCOL.md) for the BLE protocol and file format. Code layout:
99
+
100
+ | Module | Purpose |
101
+ |---|---|
102
+ | `protocol.py` | framing, CRC-8, response reassembly |
103
+ | `client.py` | `O2Client`: info, set time, list/read files |
104
+ | `recording.py` | parser for file versions 3/5, CSV export |
105
+ | `sync.py` | `sync()` / `async_sync()` |
106
+ | `plot.py` | dependency-free HTML/SVG report; optional matplotlib |
107
+ | `transport/` | minimal BLE interface + bleak implementation |
108
+
109
+ Tests run without hardware against a simulated device: `pytest`.
110
+
111
+ Not medical software. Readings are whatever the device recorded; don't use this for diagnosis.
112
+ Not affiliated with Wellue or Viatom. MIT licensed — see [LICENSE](https://github.com/pedrorivera/o2sync/blob/main/LICENSE).
@@ -0,0 +1,70 @@
1
+ # Checkme O2 Max — BLE protocol notes
2
+
3
+ Status: **verified** = tested on a real Checkme O2 Max · **unverified** = from other sources, not yet tested.
4
+
5
+ ## Device (verified)
6
+ - Advertises as `O2M <last 6 of SN>`, e.g. `O2M 804332` @ `ED:6C:6C:1A:D7:15`. No pairing/bonding needed.
7
+ - INFO: Model `1642`, SW `1.7.1`, HW `AA`, bootloader `0.1.0.0`, **FileVer `5`**, SPCPVer `1.10`.
8
+ - Only one central at a time — close ViHealth on the phone. Advertises briefly after waking.
9
+
10
+ ## GATT (verified)
11
+ | Service | Characteristic | Props | Use |
12
+ |---|---|---|---|
13
+ | `14839ac4-7d7e-415c-9a42-167340cf2339` | `8b00ace7-eb0b-49b0-bbe9-9aee0a26e1a3` | WriteWithoutResponse | **Oxy command write** |
14
+ | | `0734594a-a8e7-4b1a-a6b1-cd5243059a57` | Notify | **Oxy responses** |
15
+ | `e8fb0001-a14b-98f9-831b-4e2941d01248` | `e8fb0002…` / `e8fb0003…` | WriteNoResp / Notify | "OxyII" protocol (other models); unexplored |
16
+ | `0000fe59` (Nordic DFU) | `8ec90003-…` | Write, Indicate | **Firmware update — never write** |
17
+ | `180d` Heart Rate, `180f` Battery, `180a` Device Info, `1800`/`1801` | standard | | |
18
+
19
+ ## Framing (verified, request and response)
20
+ Request, little-endian: `AA | cmd | cmd^FF | block u16 | len u16 | payload | crc8`
21
+ Response: `55 | status | status^FF | block u16 | len u16 | payload | crc8` (status 0 = OK).
22
+ Responses span multiple notifications (INFO = 2 notifications, 468 bytes total); reassemble until `len + 8` bytes.
23
+ CRC-8: poly 0x07, init 0, no reflection, no xorout, over all preceding bytes. See `src/o2sync/protocol.py`.
24
+
25
+ ## Commands
26
+ | Op | Name | Status |
27
+ |---|---|---|
28
+ | 0x14 | INFO → JSON (incl. `FileList`, comma-separated) | verified |
29
+ | 0x16 | CONFIG, JSON payload e.g. `{"SetTIME":"YYYY-MM-DD,HH:MM:SS"}` (local time) — frame is 41 bytes, sent in 20-byte writes | verified |
30
+ | 0x03 | READ_START, payload = filename + `\0` → u32 file size | verified |
31
+ | 0x04 | READ_CONTENT, header `block` = chunk index 0,1,2… → 512-byte chunks (last one shorter) | verified |
32
+ | 0x05 | READ_END | verified |
33
+ | 0x17 / 0x1B | live sensors / live data + waveform | unverified |
34
+ | 0x15 | PING | unverified |
35
+ | 0x18 | FACTORY RESET — **do not send** | unverified |
36
+
37
+ ## Recording file format — FileVer 5 (verified on one 30-min recording; parser: `src/o2sync/recording.py`)
38
+ - Filenames in `FileList` are `yyyyMMddHHmmss` (start time in **device clock**), no prefix, no extension.
39
+ - 40-byte little-endian header:
40
+
41
+ | Off | Field | Example |
42
+ |---|---|---|
43
+ | 0 | version u8 (=5) | `05` |
44
+ | 1 | mode u8 (0 = sleep) | `00` |
45
+ | 2 | year u16, then month, day, hour, min, sec u8 | 2026-12-02 05:37:00 |
46
+ | 9 | file size u32 — equals the real size in v5 | 4600 |
47
+ | 13 | duration s u16 | 1824 |
48
+ | 17/18 | SpO2 avg / min | 97 / 95 (matches samples) |
49
+ | 19/20 | 3 % / 4 % drop events | 0 / 0 |
50
+ | 21 | seconds < 90 % u16; 23 events < 90 %; 24 % < 90 % | 0 |
51
+ | 25 | "O2 score" ×10 — `0xFF` here, likely "not computed" for a short recording | — |
52
+ | 26 | steps u32 | 0 |
53
+ | 30 | probably average pulse (unverified, OSCAR hint) | 0x47 = 71 |
54
+
55
+ - Records: 5 bytes from offset 40: `spo2 u8, pulse u16, motion u8, vibration u8`. Invalid = spo2 `0xFF`, pulse `0xFFFF`
56
+ (the last 5 records, after the finger came off). Interval = duration / records = **2.0 s**, no duplicate pairs.
57
+
58
+ ## Windows note
59
+ Smart App Control initially blocked bleak's unsigned `winrt` extension on this PC and allowed it later, presumably
60
+ after a reputation lookup. Working versions are pinned in `constraints.txt`. (An earlier in-memory-compiled C# WinRT
61
+ fallback was removed in favour of bleak only.)
62
+
63
+ ## Open items
64
+ - Device clock was ~7 h ahead; set to PC local time on 2026-12-01 23:08. Recording `20261202053700` was made
65
+ before that, so its real start is ≈ 2026-12-01 22:38 local (device was +6:59 ahead). Future files should be correct.
66
+ - Files remain on the device after download (verified: downloaded the same file 3×, byte-identical, via bleak and the former C# bridge).
67
+ - Storage is a rolling buffer: the device drops the oldest recordings itself (per the user). No delete command
68
+ is known or needed, but recordings must be synced before they roll out.
69
+ - Unverified: 4 s interval mode,
70
+ live data (0x1B), behaviour with many/long files, OxyII service `e8fb0001`.
o2sync-0.1.0/README.md ADDED
@@ -0,0 +1,81 @@
1
+ # o2sync
2
+
3
+ Download and plot recordings from Wellue / Viatom "O2" pulse oximeters over Bluetooth LE — no cable, no vendor app.
4
+ Built and verified against a **Checkme O2 Max** (advertises as `O2M xxxxxx`); other devices speaking the same
5
+ "Oxy" protocol (O2Ring, Checkme O2, SleepU, WearO2, KidsO2, BabyO2, Oxylink) are matched by name but untested.
6
+
7
+ Uses [bleak](https://github.com/hbldh/bleak), so it runs on **Linux** (BlueZ) and **Windows** (WinRT), and should
8
+ work on macOS.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ pip install o2sync # or "o2sync[plot]" for matplotlib PNG output
14
+ ```
15
+
16
+ From a checkout, for development: `pip install -e ".[test]"`.
17
+
18
+ **Linux:** needs BlueZ (`bluetoothctl` should work) and a user allowed to use D-Bus Bluetooth (default on desktop
19
+ distros). **Windows:** Windows 10/11 with Bluetooth LE. Smart App Control can block bleak's unsigned `winrt` module
20
+ ("An Application Control policy has blocked this file") until it has vetted that version; it usually clears after a
21
+ while. Installing with [constraints.txt](https://github.com/pedrorivera/o2sync/blob/main/constraints.txt)
22
+ (`pip install -c constraints.txt o2sync`) pins the versions verified to work.
23
+
24
+ ## Use
25
+
26
+ Wake the oximeter (press its button), keep it close, and close the ViHealth app on your phone — the device accepts
27
+ only one connection and only advertises for a short while after waking. It must not be recording.
28
+
29
+ ```sh
30
+ o2sync sync # scan, fix the device clock, download new files to ./recordings
31
+ o2sync sync --csv --report # ...and write CSVs + recordings/report.html
32
+ o2sync plot recordings # HTML report of everything downloaded so far
33
+ o2sync plot recordings --png pngs # matplotlib PNGs (pip install "o2sync[plot]")
34
+ o2sync csv recordings/20261202053700
35
+ o2sync scan | info | gatt # exploration helpers; o2sync raw 14 sends a raw command
36
+ ```
37
+
38
+ ### Plotting
39
+
40
+ `o2sync plot` (or `o2sync sync --report`) writes a self-contained HTML report — no plotting libraries needed — with
41
+ summary statistics and SpO₂, pulse and motion charts per recording. Gaps mark samples where the finger was off,
42
+ the dashed line marks 90 % SpO₂, and the page follows the system's light/dark theme:
43
+
44
+ ![Example o2sync report: a 30-minute recording with SpO₂ around 96–98 %, pulse 59–96 bpm and motion bars](https://raw.githubusercontent.com/pedrorivera/o2sync/main/docs/report.png)
45
+
46
+ From Python:
47
+
48
+ ```python
49
+ import o2sync
50
+
51
+ result = o2sync.sync("recordings") # -> SyncResult
52
+ for rec in result.recordings: # newly downloaded o2sync.Recording objects
53
+ print(rec.summary())
54
+ print(rec.samples[0]) # Sample(time, spo2, pulse, motion, vibration); None = invalid
55
+
56
+ rec = o2sync.Recording.from_file("recordings/20261202053700")
57
+ o2sync.save_html_report([rec], "report.html")
58
+ ```
59
+
60
+ `sync()` never deletes anything from the device and skips files already present in the output folder. Files are
61
+ saved unchanged under their device name (`yyyyMMddHHmmss`), the raw format other tools such as OSCAR import.
62
+ The device keeps a rolling buffer and drops its oldest recordings by itself, so sync regularly.
63
+ Pass `set_time=False` to leave the device clock alone or `address=` to skip scanning. An async variant, `o2sync.async_sync()`, and a lower-level `o2sync.O2Client` are available.
64
+
65
+ ## How it works
66
+
67
+ See [PROTOCOL.md](https://github.com/pedrorivera/o2sync/blob/main/PROTOCOL.md) for the BLE protocol and file format. Code layout:
68
+
69
+ | Module | Purpose |
70
+ |---|---|
71
+ | `protocol.py` | framing, CRC-8, response reassembly |
72
+ | `client.py` | `O2Client`: info, set time, list/read files |
73
+ | `recording.py` | parser for file versions 3/5, CSV export |
74
+ | `sync.py` | `sync()` / `async_sync()` |
75
+ | `plot.py` | dependency-free HTML/SVG report; optional matplotlib |
76
+ | `transport/` | minimal BLE interface + bleak implementation |
77
+
78
+ Tests run without hardware against a simulated device: `pytest`.
79
+
80
+ Not medical software. Readings are whatever the device recorded; don't use this for diagnosis.
81
+ Not affiliated with Wellue or Viatom. MIT licensed — see [LICENSE](https://github.com/pedrorivera/o2sync/blob/main/LICENSE).
@@ -0,0 +1,13 @@
1
+ # Versions verified against a real Checkme O2 Max on Windows 11 (2026-12-01).
2
+ # On Windows, Smart App Control judges the unsigned winrt-runtime module by reputation; a new version can be
3
+ # blocked until it is vetted. Install with: pip install -c constraints.txt -e .
4
+ bleak==3.1.0
5
+ winrt-runtime==4.2.1; sys_platform == "win32"
6
+ winrt-Windows.Devices.Bluetooth==4!10.0.28000.2957; sys_platform == "win32"
7
+ winrt-Windows.Devices.Bluetooth.Advertisement==4!10.0.28000.2957; sys_platform == "win32"
8
+ winrt-Windows.Devices.Bluetooth.GenericAttributeProfile==4!10.0.28000.2957; sys_platform == "win32"
9
+ winrt-Windows.Devices.Enumeration==4!10.0.28000.2957; sys_platform == "win32"
10
+ winrt-Windows.Devices.Radios==4!10.0.28000.2957; sys_platform == "win32"
11
+ winrt-Windows.Foundation==4!10.0.28000.2957; sys_platform == "win32"
12
+ winrt-Windows.Foundation.Collections==4!10.0.28000.2957; sys_platform == "win32"
13
+ winrt-Windows.Storage.Streams==4!10.0.28000.2957; sys_platform == "win32"
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "o2sync"
7
+ dynamic = ["version"]
8
+ description = "Download and plot recordings from Wellue/Viatom O2 oximeters (Checkme O2 Max, O2Ring, ...) over Bluetooth LE"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "pedrorivera" }]
14
+ keywords = ["pulse oximeter", "spo2", "bluetooth low energy", "ble", "bleak", "wellue", "viatom",
15
+ "checkme o2", "o2ring", "sleep apnea", "oscar", "quantified self"]
16
+ dependencies = ["bleak>=0.22"]
17
+ classifiers = [
18
+ "Development Status :: 3 - Alpha",
19
+ "Environment :: Console",
20
+ "Intended Audience :: Developers",
21
+ "Intended Audience :: End Users/Desktop",
22
+ "Operating System :: POSIX :: Linux",
23
+ "Operating System :: Microsoft :: Windows",
24
+ "Operating System :: MacOS",
25
+ "Programming Language :: Python :: 3",
26
+ "Topic :: Scientific/Engineering :: Medical Science Apps.",
27
+ "Topic :: System :: Hardware",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/pedrorivera/o2sync"
32
+ Source = "https://github.com/pedrorivera/o2sync"
33
+ Issues = "https://github.com/pedrorivera/o2sync/issues"
34
+ "Protocol notes" = "https://github.com/pedrorivera/o2sync/blob/main/PROTOCOL.md"
35
+
36
+ [project.optional-dependencies]
37
+ plot = ["matplotlib>=3.5"]
38
+ test = ["pytest>=7"]
39
+
40
+ [project.scripts]
41
+ o2sync = "o2sync.cli:main"
42
+
43
+ [tool.setuptools.dynamic]
44
+ version = { attr = "o2sync.__version__" }
45
+
46
+ [tool.setuptools.packages.find]
47
+ where = ["src"]
48
+
49
+ [tool.pytest.ini_options]
50
+ testpaths = ["tests"]
o2sync-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,22 @@
1
+ """o2sync — download and plot recordings from Wellue/Viatom O2 oximeters (Checkme O2 Max, O2Ring, ...) over BLE.
2
+
3
+ >>> import o2sync
4
+ >>> result = o2sync.sync("recordings") # scan, set clock, download new files
5
+ >>> for rec in result.recordings:
6
+ ... print(rec.summary())
7
+ >>> o2sync.save_html_report(result.recordings, "report.html")
8
+ """
9
+ from .client import DeviceStatusError, O2Client, O2Error
10
+ from .plot import html_report, plot_matplotlib, recording_svg, save_html_report
11
+ from .recording import Recording, Sample, UnsupportedFormat
12
+ from .sync import DeviceNotFound, SyncResult, async_sync, find_device, sync
13
+ from .transport import make_transport
14
+
15
+ __version__ = "0.1.0"
16
+
17
+ __all__ = [
18
+ "sync", "async_sync", "SyncResult", "find_device", "DeviceNotFound",
19
+ "O2Client", "O2Error", "DeviceStatusError", "make_transport",
20
+ "Recording", "Sample", "UnsupportedFormat",
21
+ "html_report", "save_html_report", "recording_svg", "plot_matplotlib",
22
+ ]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,190 @@
1
+ """Command line interface: ``o2sync scan | info | sync | plot | csv | raw | gatt``."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import asyncio
6
+ import json
7
+ import logging
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from . import __version__
12
+ from .client import O2Client
13
+ from .plot import plot_matplotlib, save_html_report
14
+ from .protocol import Cmd
15
+ from .recording import Recording, UnsupportedFormat
16
+ from .sync import DeviceNotFound, async_sync, find_device, is_oxy_name
17
+ from .transport import BackendUnavailable, make_transport
18
+
19
+
20
+ def _load_recordings(paths: list[str]) -> list[Recording]:
21
+ files: list[Path] = []
22
+ for p in map(Path, paths):
23
+ files.extend(sorted(f for f in p.iterdir() if f.is_file()) if p.is_dir() else [p])
24
+ recs = []
25
+ for f in files:
26
+ if f.suffix.lower() in (".csv", ".html", ".png", ".part", ".md", ".json"):
27
+ continue
28
+ try:
29
+ recs.append(Recording.from_file(f))
30
+ except UnsupportedFormat as e:
31
+ print(f"skipping {f}: {e}", file=sys.stderr)
32
+ return recs
33
+
34
+
35
+ async def _resolve(transport, args) -> str:
36
+ if args.address:
37
+ return args.address
38
+ ad = await find_device(transport, args.scan_timeout)
39
+ print(f"found {ad.name} at {ad.address}")
40
+ return ad.address
41
+
42
+
43
+ async def _cmd_scan(args) -> int:
44
+ t = make_transport()
45
+ try:
46
+ for ad in await t.scan(args.scan_timeout):
47
+ if args.all or is_oxy_name(ad.name):
48
+ print(f"{ad.address} rssi={ad.rssi:>4} {ad.name}")
49
+ finally:
50
+ await t.close()
51
+ return 0
52
+
53
+
54
+ async def _with_client(args, fn) -> int:
55
+ t = make_transport()
56
+ try:
57
+ address = await _resolve(t, args)
58
+ c = O2Client(t)
59
+ await c.connect(address)
60
+ try:
61
+ await fn(c)
62
+ finally:
63
+ await c.disconnect()
64
+ finally:
65
+ await t.close()
66
+ return 0
67
+
68
+
69
+ async def _cmd_info(args) -> int:
70
+ async def go(c: O2Client):
71
+ print(json.dumps(await c.info(), indent=2))
72
+ return await _with_client(args, go)
73
+
74
+
75
+ async def _cmd_raw(args) -> int:
76
+ async def go(c: O2Client):
77
+ payload = bytes.fromhex(args.payload) if args.payload else b""
78
+ resp = await c.request(int(args.cmd, 16), args.block, payload)
79
+ print(resp.hex())
80
+ try:
81
+ print(resp.rstrip(b"\0").decode("ascii"))
82
+ except UnicodeDecodeError:
83
+ pass
84
+ if int(args.cmd, 16) == 0x18:
85
+ print("refusing to send 0x18 (factory reset)", file=sys.stderr)
86
+ return 2
87
+ return await _with_client(args, go)
88
+
89
+
90
+ async def _cmd_gatt(args) -> int:
91
+ t = make_transport()
92
+ try:
93
+ print(await t.gatt_dump(await _resolve(t, args)))
94
+ finally:
95
+ await t.close()
96
+ return 0
97
+
98
+
99
+ async def _cmd_sync(args) -> int:
100
+ res = await async_sync(
101
+ args.out, address=args.address, set_time=not args.no_set_time, skip_existing=not args.force,
102
+ scan_timeout=args.scan_timeout, report=print)
103
+ print(f"{len(res.downloaded)} new, {len(res.skipped)} already present -> {Path(args.out).resolve()}")
104
+ if args.csv:
105
+ for rec, path in zip(res.downloaded, res.paths):
106
+ rec.to_csv(path.with_suffix(".csv"))
107
+ if args.report:
108
+ recs = _load_recordings([args.out])
109
+ out = Path(args.out) / "report.html"
110
+ save_html_report(recs, out)
111
+ print(f"report: {out.resolve()}")
112
+ return 0
113
+
114
+
115
+ def _cmd_plot(args) -> int:
116
+ recs = _load_recordings(args.files)
117
+ if not recs:
118
+ print("no recordings found", file=sys.stderr)
119
+ return 1
120
+ if args.png:
121
+ for rec in recs:
122
+ out = Path(args.png) / f"{rec.start:%Y%m%d_%H%M%S}.png"
123
+ out.parent.mkdir(parents=True, exist_ok=True)
124
+ plot_matplotlib(rec, out)
125
+ print(out)
126
+ else:
127
+ save_html_report(recs, args.output)
128
+ print(Path(args.output).resolve())
129
+ return 0
130
+
131
+
132
+ def _cmd_csv(args) -> int:
133
+ for rec in _load_recordings(args.files):
134
+ out = Path(args.outdir or ".") / f"{rec.name or rec.start.strftime('%Y%m%d%H%M%S')}.csv"
135
+ rec.to_csv(out)
136
+ print(f"{out} ({rec.summary()})")
137
+ return 0
138
+
139
+
140
+ def main(argv: list[str] | None = None) -> int:
141
+ ap = argparse.ArgumentParser(prog="o2sync", description="Sync and plot Wellue/Viatom O2 oximeter recordings over BLE")
142
+ ap.add_argument("--version", action="version", version=__version__)
143
+ ap.add_argument("-v", "--verbose", action="store_true")
144
+ sub = ap.add_subparsers(dest="cmd", required=True)
145
+
146
+ def ble(p):
147
+ p.add_argument("--address", "-a", help="device BLE address (default: scan for an O2 device)")
148
+ p.add_argument("--scan-timeout", type=float, default=15.0)
149
+ return p
150
+
151
+ p = ble(sub.add_parser("scan", help="list nearby oximeters"))
152
+ p.add_argument("--all", action="store_true", help="show every BLE device")
153
+ ble(sub.add_parser("info", help="print device info JSON"))
154
+ ble(sub.add_parser("gatt", help="dump the GATT table"))
155
+ p = ble(sub.add_parser("raw", help="send a raw protocol command (exploration)"))
156
+ p.add_argument("cmd", help="command byte in hex, e.g. 14")
157
+ p.add_argument("--block", type=int, default=0)
158
+ p.add_argument("--payload", help="payload hex")
159
+ p = ble(sub.add_parser("sync", help="download new recordings"))
160
+ p.add_argument("--out", "-o", default="recordings")
161
+ p.add_argument("--no-set-time", action="store_true", help="do not correct the device clock")
162
+ p.add_argument("--force", action="store_true", help="re-download files that already exist")
163
+ p.add_argument("--csv", action="store_true", help="also write a .csv next to each new file")
164
+ p.add_argument("--report", action="store_true", help="write recordings/report.html afterwards")
165
+ p = sub.add_parser("plot", help="HTML report (default) or PNGs of recordings")
166
+ p.add_argument("files", nargs="+", help="recording files or directories")
167
+ p.add_argument("--output", "-o", default="report.html")
168
+ p.add_argument("--png", metavar="DIR", help="write one PNG per recording with matplotlib instead")
169
+ p = sub.add_parser("csv", help="convert recordings to CSV")
170
+ p.add_argument("files", nargs="+")
171
+ p.add_argument("--outdir")
172
+
173
+ args = ap.parse_args(argv)
174
+ logging.basicConfig(level=logging.DEBUG if args.verbose else logging.WARNING, format="%(levelname)s %(name)s: %(message)s")
175
+ try:
176
+ if args.cmd == "plot":
177
+ return _cmd_plot(args)
178
+ if args.cmd == "csv":
179
+ return _cmd_csv(args)
180
+ return asyncio.run({"scan": _cmd_scan, "info": _cmd_info, "gatt": _cmd_gatt,
181
+ "raw": _cmd_raw, "sync": _cmd_sync}[args.cmd](args))
182
+ except (DeviceNotFound, BackendUnavailable) as e:
183
+ print(e, file=sys.stderr)
184
+ return 1
185
+ except KeyboardInterrupt:
186
+ return 130
187
+
188
+
189
+ if __name__ == "__main__":
190
+ sys.exit(main())