o2sync 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
o2sync/__init__.py ADDED
@@ -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
+ ]
o2sync/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
o2sync/cli.py ADDED
@@ -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())
o2sync/client.py ADDED
@@ -0,0 +1,126 @@
1
+ """High-level async client for the Oxy protocol, independent of the BLE backend."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import datetime as dt
6
+ import json
7
+ import logging
8
+ import struct
9
+ from typing import Callable, Optional
10
+
11
+ from .protocol import NOTIFY_UUID, WRITE_UUID, Cmd, Reassembler, Response, build_frame
12
+ from .transport import Transport
13
+
14
+ log = logging.getLogger(__name__)
15
+
16
+ ProgressFn = Callable[[int, int], None] # (bytes_done, bytes_total)
17
+
18
+
19
+ class O2Error(Exception):
20
+ pass
21
+
22
+
23
+ class DeviceStatusError(O2Error):
24
+ def __init__(self, cmd: int, status: int):
25
+ super().__init__(f"device returned status 0x{status:02X} for command 0x{cmd:02X}")
26
+ self.cmd, self.status = cmd, status
27
+
28
+
29
+ class O2Client:
30
+ """Talks to one connected oximeter. Use as ``async with O2Client(transport) as c: await c.connect(addr)``."""
31
+
32
+ WRITE_CHUNK = 20 # stays within the default ATT MTU of 23
33
+
34
+ def __init__(self, transport: Transport, *, timeout: float = 5.0, retries: int = 2):
35
+ self.transport = transport
36
+ self.timeout = timeout
37
+ self.retries = retries
38
+ self._rx = Reassembler()
39
+ self._responses: asyncio.Queue[Response] = asyncio.Queue()
40
+ self._lock = asyncio.Lock()
41
+
42
+ async def __aenter__(self) -> "O2Client":
43
+ return self
44
+
45
+ async def __aexit__(self, *exc) -> None:
46
+ await self.disconnect()
47
+
48
+ # ---- connection ----
49
+ async def connect(self, address: str) -> None:
50
+ await self.transport.connect(address)
51
+ await self.transport.start_notify(NOTIFY_UUID, self._on_notify)
52
+ await asyncio.sleep(0.5) # the official app waits before the first command
53
+
54
+ async def disconnect(self) -> None:
55
+ await self.transport.disconnect()
56
+
57
+ def _on_notify(self, data: bytes) -> None:
58
+ for resp in self._rx.feed(data):
59
+ self._responses.put_nowait(resp)
60
+
61
+ # ---- raw request ----
62
+ async def request(self, cmd: int, block: int = 0, payload: bytes = b"") -> bytes:
63
+ frame = build_frame(cmd, block, payload)
64
+ async with self._lock:
65
+ last_err: Exception | None = None
66
+ for attempt in range(self.retries + 1):
67
+ self._rx.reset()
68
+ while not self._responses.empty():
69
+ self._responses.get_nowait()
70
+ for i in range(0, len(frame), self.WRITE_CHUNK):
71
+ await self.transport.write(WRITE_UUID, frame[i:i + self.WRITE_CHUNK])
72
+ try:
73
+ resp = await asyncio.wait_for(self._responses.get(), self.timeout)
74
+ except asyncio.TimeoutError:
75
+ last_err = O2Error(f"timeout waiting for response to command 0x{cmd:02X}")
76
+ log.debug("%s (attempt %d)", last_err, attempt + 1)
77
+ continue
78
+ if not resp.ok:
79
+ raise DeviceStatusError(cmd, resp.status)
80
+ return resp.payload
81
+ raise last_err # type: ignore[misc]
82
+
83
+ # ---- commands ----
84
+ async def info(self) -> dict:
85
+ raw = await self.request(Cmd.INFO)
86
+ return json.loads(raw.rstrip(b"\0").decode("utf-8", "replace"))
87
+
88
+ async def configure(self, **settings: str) -> None:
89
+ """Send a CONFIG command, e.g. ``configure(SetOxiThr="90")``."""
90
+ await self.request(Cmd.CONFIG, payload=json.dumps(settings, separators=(",", ":")).encode())
91
+
92
+ async def set_time(self, when: Optional[dt.datetime] = None) -> None:
93
+ when = when or dt.datetime.now()
94
+ await self.configure(SetTIME=when.strftime("%Y-%m-%d,%H:%M:%S"))
95
+
96
+ async def device_time(self) -> dt.datetime:
97
+ return parse_device_time((await self.info())["CurTIME"])
98
+
99
+ async def list_files(self) -> list[str]:
100
+ info = await self.info()
101
+ return [f for f in info.get("FileList", "").split(",") if f]
102
+
103
+ async def read_file(self, name: str, progress: Optional[ProgressFn] = None) -> bytes:
104
+ size_raw = await self.request(Cmd.READ_START, payload=name.encode("ascii") + b"\0")
105
+ size = struct.unpack_from("<I", size_raw)[0]
106
+ data = bytearray()
107
+ try:
108
+ block = 0
109
+ while len(data) < size:
110
+ chunk = await self.request(Cmd.READ_CONTENT, block=block)
111
+ if not chunk:
112
+ raise O2Error(f"empty chunk {block} while reading {name}")
113
+ data += chunk
114
+ block += 1
115
+ if progress:
116
+ progress(min(len(data), size), size)
117
+ finally:
118
+ try:
119
+ await self.request(Cmd.READ_END)
120
+ except O2Error as e:
121
+ log.warning("READ_END failed: %s", e)
122
+ return bytes(data[:size])
123
+
124
+
125
+ def parse_device_time(s: str) -> dt.datetime:
126
+ return dt.datetime.strptime(s, "%Y-%m-%d,%H:%M:%S")
o2sync/plot.py ADDED
@@ -0,0 +1,220 @@
1
+ """Plotting: a dependency-free HTML/SVG report, and an optional matplotlib PNG renderer."""
2
+ from __future__ import annotations
3
+
4
+ import datetime as dt
5
+ import html
6
+ import math
7
+ import os
8
+ from typing import Iterable, Optional, Sequence
9
+
10
+ from .recording import Recording, Sample
11
+
12
+ # ---------------------------------------------------------------- SVG
13
+
14
+ _W = 960
15
+ _LEFT, _RIGHT = 46, 14
16
+ _PANELS = ( # (key, title, height)
17
+ ("spo2", "SpO₂ (%)", 200),
18
+ ("pulse", "Pulse (bpm)", 160),
19
+ ("motion", "Motion", 50),
20
+ )
21
+ _GAP = 30
22
+ _TOP = 22
23
+ _BOTTOM = 26
24
+
25
+
26
+ def _nice_ticks(lo: float, hi: float, target: int = 5) -> list[float]:
27
+ span = max(hi - lo, 1e-9)
28
+ raw = span / target
29
+ mag = 10 ** math.floor(math.log10(raw))
30
+ step = min((m * mag for m in (1, 2, 5, 10)), key=lambda s: abs(span / s - target))
31
+ first = math.ceil(lo / step) * step
32
+ out, v = [], first
33
+ while v <= hi + 1e-9:
34
+ out.append(round(v, 6))
35
+ v += step
36
+ return out
37
+
38
+
39
+ def _time_ticks(rec: Recording) -> list[float]:
40
+ """Seconds from start for ticks on round clock times."""
41
+ dur = max(rec.duration, 1)
42
+ for step in (60, 120, 300, 600, 900, 1800, 3600, 7200, 10800):
43
+ if dur / step <= 9:
44
+ break
45
+ first = step - (rec.start.minute * 60 + rec.start.second) % step
46
+ if first == step:
47
+ first = 0
48
+ return [t for t in range(int(first), int(dur) + 1, step)]
49
+
50
+
51
+ def _segments(samples: Sequence[Sample], attr: str) -> list[list[tuple[float, int]]]:
52
+ segs: list[list[tuple[float, int]]] = []
53
+ cur: list[tuple[float, int]] = []
54
+ t0 = samples[0].time if samples else None
55
+ for s in samples:
56
+ v = getattr(s, attr)
57
+ if v is None:
58
+ if cur:
59
+ segs.append(cur)
60
+ cur = []
61
+ continue
62
+ cur.append(((s.time - t0).total_seconds(), v))
63
+ if cur:
64
+ segs.append(cur)
65
+ return segs
66
+
67
+
68
+ def recording_svg(rec: Recording) -> str:
69
+ plot_w = _W - _LEFT - _RIGHT
70
+ height = _TOP + sum(h for _, _, h in _PANELS) + _GAP * (len(_PANELS) - 1) + _BOTTOM
71
+ dur = max(rec.duration, 1)
72
+
73
+ def x(t: float) -> float:
74
+ return _LEFT + t / dur * plot_w
75
+
76
+ valid = rec.valid_samples
77
+ spo2_vals = [s.spo2 for s in valid] or [95]
78
+ pulse_vals = [s.pulse for s in valid] or [60]
79
+ ranges = {
80
+ "spo2": (min(85, 5 * math.floor((min(spo2_vals) - 1) / 5)), 100),
81
+ "pulse": (10 * math.floor((min(pulse_vals) - 5) / 10), 10 * math.ceil((max(pulse_vals) + 5) / 10)),
82
+ "motion": (0, max(10, max((s.motion for s in rec.samples), default=0))),
83
+ }
84
+
85
+ parts = [f'<svg class="o2plot" viewBox="0 0 {_W} {height}" xmlns="http://www.w3.org/2000/svg" '
86
+ f'role="img" aria-label="SpO2 and pulse for recording starting {rec.start:%Y-%m-%d %H:%M}">']
87
+ ticks_t = _time_ticks(rec)
88
+ y0 = _TOP
89
+ for key, title, h in _PANELS:
90
+ lo, hi = ranges[key]
91
+
92
+ def y(v: float, lo=lo, hi=hi, y0=y0, h=h) -> float:
93
+ return y0 + h - (v - lo) / (hi - lo) * h
94
+
95
+ parts.append(f'<text class="title" x="{_LEFT}" y="{y0 - 7}">{html.escape(title)}</text>')
96
+ parts.append(f'<rect class="frame" x="{_LEFT}" y="{y0}" width="{plot_w}" height="{h}"/>')
97
+ for t in ticks_t:
98
+ parts.append(f'<line class="grid" x1="{x(t):.1f}" x2="{x(t):.1f}" y1="{y0}" y2="{y0 + h}"/>')
99
+ if key != "motion":
100
+ for v in _nice_ticks(lo, hi, 4 if key == "pulse" else 5):
101
+ if lo <= v <= hi:
102
+ parts.append(f'<line class="grid" x1="{_LEFT}" x2="{_LEFT + plot_w}" y1="{y(v):.1f}" y2="{y(v):.1f}"/>')
103
+ parts.append(f'<text class="axis" x="{_LEFT - 6}" y="{y(v) + 4:.1f}" text-anchor="end">{v:g}</text>')
104
+ if key == "spo2" and lo < 90:
105
+ parts.append(f'<line class="thr" x1="{_LEFT}" x2="{_LEFT + plot_w}" y1="{y(90):.1f}" y2="{y(90):.1f}"/>')
106
+ if key == "motion":
107
+ t0 = rec.samples[0].time if rec.samples else rec.start
108
+ bars = "".join(
109
+ f"M{x((s.time - t0).total_seconds()):.1f},{y0 + h}V{y(min(s.motion, hi)):.1f}"
110
+ for s in rec.samples if s.motion)
111
+ if bars:
112
+ parts.append(f'<path class="motion" d="{bars}"/>')
113
+ else:
114
+ for seg in _segments(rec.samples, key):
115
+ if len(seg) == 1:
116
+ t, v = seg[0]
117
+ parts.append(f'<circle class="{key}" cx="{x(t):.1f}" cy="{y(v):.1f}" r="1.5"/>')
118
+ continue
119
+ pts = " ".join(f"{x(t):.1f},{y(v):.1f}" for t, v in seg)
120
+ parts.append(f'<polyline class="{key}" points="{pts}"/>')
121
+ y0 += h + _GAP
122
+ axis_y = y0 - _GAP + 16
123
+ for t in ticks_t:
124
+ label = (rec.start + dt.timedelta(seconds=t)).strftime("%H:%M")
125
+ parts.append(f'<text class="axis" x="{x(t):.1f}" y="{axis_y}" text-anchor="middle">{label}</text>')
126
+ parts.append("</svg>")
127
+ return "".join(parts)
128
+
129
+
130
+ _CSS = """
131
+ :root { --bg:#ffffff; --fg:#1d2330; --muted:#667085; --grid:#e6e8ec; --frame:#c9ced6;
132
+ --spo2:#2563eb; --pulse:#d9480f; --motion:#94a3b8; --thr:#dc2626; --card:#f6f7f9; }
133
+ @media (prefers-color-scheme: dark) { :root { --bg:#14171c; --fg:#e6e9ee; --muted:#9aa3b2; --grid:#262b33;
134
+ --frame:#3a414c; --spo2:#6ea2ff; --pulse:#ff8a50; --motion:#64748b; --thr:#f87171; --card:#1c2027; } }
135
+ body { background:var(--bg); color:var(--fg); font:15px/1.45 system-ui,-apple-system,"Segoe UI",sans-serif;
136
+ margin:0 auto; max-width:1000px; padding:24px 16px 48px; }
137
+ h1 { font-size:22px; margin:0 0 4px; } .sub { color:var(--muted); margin:0 0 24px; }
138
+ section { margin:0 0 36px; } h2 { font-size:17px; margin:0 0 8px; }
139
+ .stats { display:flex; flex-wrap:wrap; gap:8px; margin:0 0 12px; padding:0; list-style:none; }
140
+ .stats li { background:var(--card); border-radius:8px; padding:6px 10px; }
141
+ .stats b { font-variant-numeric:tabular-nums; } .stats span { color:var(--muted); font-size:13px; margin-right:6px; }
142
+ svg.o2plot { width:100%; height:auto; display:block; }
143
+ svg.o2plot text { font:12px system-ui,sans-serif; fill:var(--muted); font-variant-numeric:tabular-nums; }
144
+ svg.o2plot text.title { fill:var(--fg); font-weight:600; }
145
+ svg.o2plot .frame { fill:none; stroke:var(--frame); } svg.o2plot .grid { stroke:var(--grid); }
146
+ svg.o2plot .thr { stroke:var(--thr); stroke-dasharray:4 4; }
147
+ svg.o2plot polyline { fill:none; stroke-width:1.4; stroke-linejoin:round; }
148
+ svg.o2plot .spo2 { stroke:var(--spo2); fill:var(--spo2); } svg.o2plot polyline.spo2 { fill:none; }
149
+ svg.o2plot .pulse { stroke:var(--pulse); fill:var(--pulse); } svg.o2plot polyline.pulse { fill:none; }
150
+ svg.o2plot .motion { stroke:var(--motion); stroke-width:1.5; }
151
+ """
152
+
153
+
154
+ def _stats_html(rec: Recording) -> str:
155
+ avg, lo, hi = rec.pulse_stats()
156
+ h, m = divmod(rec.duration // 60, 60)
157
+ items = [
158
+ ("Duration", f"{h}h {m:02d}m"),
159
+ ("SpO₂ avg", f"{rec.spo2_avg}%"),
160
+ ("SpO₂ min", f"{rec.spo2_min}%"),
161
+ ("Time <90%", f"{rec.seconds_below_90 // 60}m {rec.seconds_below_90 % 60:02d}s"),
162
+ ("Drops ≥4%", str(rec.drops_4pct)),
163
+ ("Drops ≥3%", str(rec.drops_3pct)),
164
+ ("Pulse", f"{avg:.0f} bpm ({lo}–{hi})" if avg is not None else "—"),
165
+ ("Interval", f"{rec.interval:g}s"),
166
+ ]
167
+ if rec.o2_score is not None:
168
+ items.append(("O₂ score", f"{rec.o2_score:g}"))
169
+ return '<ul class="stats">' + "".join(f"<li><span>{k}</span><b>{v}</b></li>" for k, v in items) + "</ul>"
170
+
171
+
172
+ def html_report(recordings: Iterable[Recording], title: str = "Oximetry report") -> str:
173
+ recs = sorted(recordings, key=lambda r: r.start, reverse=True)
174
+ body = []
175
+ for rec in recs:
176
+ body.append(f"<section><h2>{rec.start:%A %d %B %Y, %H:%M} – {rec.end:%H:%M}</h2>"
177
+ f"{_stats_html(rec)}{recording_svg(rec)}</section>")
178
+ gen = dt.datetime.now().strftime("%Y-%m-%d %H:%M")
179
+ return (f'<!doctype html><html lang="en"><head><meta charset="utf-8">'
180
+ f'<meta name="viewport" content="width=device-width,initial-scale=1"><title>{html.escape(title)}</title>'
181
+ f"<style>{_CSS}</style></head><body><h1>{html.escape(title)}</h1>"
182
+ f'<p class="sub">{len(recs)} recording(s) · generated {gen}</p>{"".join(body)}</body></html>')
183
+
184
+
185
+ def save_html_report(recordings: Iterable[Recording], path: str | os.PathLike, title: str = "Oximetry report") -> None:
186
+ with open(path, "w", encoding="utf-8") as f:
187
+ f.write(html_report(recordings, title))
188
+
189
+
190
+ # ---------------------------------------------------------------- matplotlib (optional)
191
+
192
+ def plot_matplotlib(rec: Recording, path: Optional[str | os.PathLike] = None, show: bool = False):
193
+ """Render a recording with matplotlib (``pip install o2sync[plot]``). Returns the Figure."""
194
+ import matplotlib.pyplot as plt
195
+ import matplotlib.dates as mdates
196
+
197
+ t = [s.time for s in rec.samples]
198
+ spo2 = [s.spo2 if s.spo2 is not None else float("nan") for s in rec.samples]
199
+ pulse = [s.pulse if s.pulse is not None else float("nan") for s in rec.samples]
200
+ motion = [s.motion for s in rec.samples]
201
+ fig, (a1, a2, a3) = plt.subplots(3, 1, sharex=True, figsize=(12, 6.5),
202
+ gridspec_kw={"height_ratios": [4, 3, 1]})
203
+ a1.plot(t, spo2, color="#2563eb", lw=1)
204
+ a1.axhline(90, color="#dc2626", ls="--", lw=0.8)
205
+ a1.set_ylabel("SpO₂ %")
206
+ a1.set_ylim(min(85, min((v for v in spo2 if v == v), default=90) - 1), 100.5)
207
+ a2.plot(t, pulse, color="#d9480f", lw=1)
208
+ a2.set_ylabel("Pulse bpm")
209
+ a3.bar(t, motion, width=rec.interval / 86400, color="#94a3b8")
210
+ a3.set_ylabel("Motion")
211
+ a3.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M"))
212
+ for a in (a1, a2, a3):
213
+ a.grid(alpha=0.3)
214
+ fig.suptitle(rec.summary(), fontsize=10)
215
+ fig.tight_layout()
216
+ if path:
217
+ fig.savefig(path, dpi=130)
218
+ if show:
219
+ plt.show()
220
+ return fig
o2sync/protocol.py ADDED
@@ -0,0 +1,106 @@
1
+ """Viatom/Wellue "Oxy" BLE protocol: framing, CRC and command codes.
2
+
3
+ Request: AA | cmd | cmd^FF | block u16 | len u16 | payload | crc8
4
+ Response: 55 | status | status^FF | block u16 | len u16 | payload | crc8 (status 0 = OK)
5
+ All integers little-endian. CRC-8: poly 0x07, init 0, no reflection, no final xor.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import struct
10
+ from dataclasses import dataclass
11
+ from enum import IntEnum
12
+
13
+ SERVICE_UUID = "14839ac4-7d7e-415c-9a42-167340cf2339"
14
+ WRITE_UUID = "8b00ace7-eb0b-49b0-bbe9-9aee0a26e1a3"
15
+ NOTIFY_UUID = "0734594a-a8e7-4b1a-a6b1-cd5243059a57"
16
+
17
+ REQUEST_HEADER = 0xAA
18
+ RESPONSE_HEADER = 0x55
19
+ FRAME_OVERHEAD = 8 # header(7) + crc(1)
20
+
21
+
22
+ class Cmd(IntEnum):
23
+ READ_START = 0x03
24
+ READ_CONTENT = 0x04
25
+ READ_END = 0x05
26
+ INFO = 0x14
27
+ PING = 0x15
28
+ CONFIG = 0x16
29
+ READ_SENSORS = 0x17
30
+ RT_DATA = 0x1B
31
+ # 0x18 is FACTORY RESET. Deliberately not exposed.
32
+
33
+
34
+ def _make_table() -> list[int]:
35
+ table = []
36
+ for i in range(256):
37
+ c = i
38
+ for _ in range(8):
39
+ c = ((c << 1) ^ 0x07) & 0xFF if c & 0x80 else (c << 1) & 0xFF
40
+ table.append(c)
41
+ return table
42
+
43
+
44
+ _CRC_TABLE = _make_table()
45
+
46
+
47
+ def crc8(data: bytes) -> int:
48
+ c = 0
49
+ for b in data:
50
+ c = _CRC_TABLE[c ^ b]
51
+ return c
52
+
53
+
54
+ def build_frame(cmd: int, block: int = 0, payload: bytes = b"", header: int = REQUEST_HEADER) -> bytes:
55
+ body = struct.pack("<BBBHH", header, cmd, cmd ^ 0xFF, block, len(payload)) + payload
56
+ return body + bytes([crc8(body)])
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class Response:
61
+ status: int
62
+ block: int
63
+ payload: bytes
64
+
65
+ @property
66
+ def ok(self) -> bool:
67
+ return self.status == 0
68
+
69
+
70
+ class Reassembler:
71
+ """Turns a stream of BLE notification fragments into complete response frames."""
72
+
73
+ def __init__(self) -> None:
74
+ self._buf = bytearray()
75
+ self.dropped_bytes = 0
76
+
77
+ def reset(self) -> None:
78
+ self._buf.clear()
79
+
80
+ def feed(self, data: bytes) -> list[Response]:
81
+ self._buf += data
82
+ out: list[Response] = []
83
+ buf = self._buf
84
+ while True:
85
+ # Find a plausible header: 0x55 followed by status and its complement.
86
+ # Positions before i are known not to start a frame; i onwards may (or may be incomplete).
87
+ i = 0
88
+ while i + 2 < len(buf) and not (buf[i] == RESPONSE_HEADER and buf[i + 1] ^ buf[i + 2] == 0xFF):
89
+ i += 1
90
+ if i:
91
+ self.dropped_bytes += i
92
+ del buf[:i]
93
+ if len(buf) < 7:
94
+ return out
95
+ length = buf[5] | (buf[6] << 8)
96
+ total = length + FRAME_OVERHEAD
97
+ if len(buf) < total:
98
+ return out
99
+ frame = bytes(buf[:total])
100
+ if crc8(frame[:-1]) != frame[-1]:
101
+ # false header match or corruption: skip one byte and resync
102
+ self.dropped_bytes += 1
103
+ del buf[:1]
104
+ continue
105
+ del buf[:total]
106
+ out.append(Response(status=frame[1], block=frame[3] | (frame[4] << 8), payload=frame[7:-1]))
o2sync/recording.py ADDED
@@ -0,0 +1,136 @@
1
+ """Parser for O2 recording files as stored on the device (file format versions 3 and 5).
2
+
3
+ Layout (little-endian), verified on a Checkme O2 Max (FileVer 5):
4
+ 0 version u8 1 mode u8 (0 = sleep)
5
+ 2 year u16, month, day, hour, minute, second (u8 each)
6
+ 9 file size u32 13 duration in seconds u16
7
+ 17 SpO2 average 18 SpO2 minimum
8
+ 19 3% drops 20 4% drops
9
+ 21 seconds < 90% u16 23 events < 90% 24 percent of time < 90%
10
+ 25 O2 score x10 (0xFF = not computed) 26 steps u32
11
+ 40.. records of 5 bytes: spo2 u8, pulse u16, motion u8, vibration u8
12
+ Invalid samples have spo2 0xFF / pulse 0xFFFF.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import csv
17
+ import datetime as dt
18
+ import os
19
+ import struct
20
+ from dataclasses import dataclass, field
21
+ from typing import Optional
22
+
23
+ HEADER_SIZE = 40
24
+ RECORD_SIZE = 5
25
+ SUPPORTED_VERSIONS = (3, 5)
26
+
27
+
28
+ class UnsupportedFormat(ValueError):
29
+ pass
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Sample:
34
+ time: dt.datetime
35
+ spo2: Optional[int] # None = invalid / no finger
36
+ pulse: Optional[int]
37
+ motion: int
38
+ vibration: int
39
+
40
+ @property
41
+ def valid(self) -> bool:
42
+ return self.spo2 is not None and self.pulse is not None
43
+
44
+
45
+ @dataclass
46
+ class Recording:
47
+ name: str
48
+ version: int
49
+ mode: int
50
+ start: dt.datetime
51
+ duration: int # seconds
52
+ interval: float # seconds between samples
53
+ spo2_avg: int
54
+ spo2_min: int
55
+ drops_3pct: int
56
+ drops_4pct: int
57
+ seconds_below_90: int
58
+ events_below_90: int
59
+ percent_below_90: int
60
+ o2_score: Optional[float]
61
+ steps: int
62
+ samples: list[Sample] = field(repr=False)
63
+ raw: bytes = field(repr=False)
64
+
65
+ # ---- construction ----
66
+ @classmethod
67
+ def from_bytes(cls, raw: bytes, name: str = "") -> "Recording":
68
+ if len(raw) < HEADER_SIZE:
69
+ raise UnsupportedFormat(f"{name or 'file'}: too short for an O2 recording ({len(raw)} bytes)")
70
+ version = raw[0]
71
+ if version not in SUPPORTED_VERSIONS:
72
+ raise UnsupportedFormat(f"{name or 'file'}: unsupported file version {version}")
73
+ year, mon, day, hh, mi, ss = struct.unpack_from("<HBBBBB", raw, 2)
74
+ try:
75
+ start = dt.datetime(year, mon, day, hh, mi, ss)
76
+ except ValueError as e:
77
+ raise UnsupportedFormat(f"{name or 'file'}: bad start time in header ({e})") from None
78
+ duration = struct.unpack_from("<H", raw, 13)[0]
79
+ body = raw[HEADER_SIZE:]
80
+ n = len(body) // RECORD_SIZE
81
+ interval = duration / n if n else 0.0
82
+ if interval and abs(interval - round(interval)) < 0.05:
83
+ interval = float(round(interval))
84
+ samples = []
85
+ for i in range(n):
86
+ spo2, pulse, motion, vib = struct.unpack_from("<BHBB", body, i * RECORD_SIZE)
87
+ samples.append(Sample(
88
+ time=start + dt.timedelta(seconds=i * interval),
89
+ spo2=None if spo2 == 0xFF else spo2,
90
+ pulse=None if pulse >= 0xFF else pulse,
91
+ motion=motion,
92
+ vibration=vib,
93
+ ))
94
+ return cls(
95
+ name=name, version=version, mode=raw[1], start=start, duration=duration, interval=interval,
96
+ spo2_avg=raw[17], spo2_min=raw[18], drops_3pct=raw[19], drops_4pct=raw[20],
97
+ seconds_below_90=struct.unpack_from("<H", raw, 21)[0], events_below_90=raw[23],
98
+ percent_below_90=raw[24], o2_score=None if raw[25] == 0xFF else raw[25] / 10,
99
+ steps=struct.unpack_from("<I", raw, 26)[0], samples=samples, raw=bytes(raw),
100
+ )
101
+
102
+ @classmethod
103
+ def from_file(cls, path: str | os.PathLike) -> "Recording":
104
+ with open(path, "rb") as f:
105
+ return cls.from_bytes(f.read(), name=os.path.basename(path))
106
+
107
+ # ---- derived ----
108
+ @property
109
+ def end(self) -> dt.datetime:
110
+ return self.start + dt.timedelta(seconds=self.duration)
111
+
112
+ @property
113
+ def valid_samples(self) -> list[Sample]:
114
+ return [s for s in self.samples if s.valid]
115
+
116
+ def pulse_stats(self) -> tuple[Optional[float], Optional[int], Optional[int]]:
117
+ p = [s.pulse for s in self.valid_samples]
118
+ if not p:
119
+ return None, None, None
120
+ return sum(p) / len(p), min(p), max(p)
121
+
122
+ def summary(self) -> str:
123
+ avg, lo, hi = self.pulse_stats()
124
+ h, m = divmod(self.duration // 60, 60)
125
+ pulse = f"pulse {avg:.0f} bpm ({lo}-{hi})" if avg is not None else "no valid pulse"
126
+ return (f"{self.start:%Y-%m-%d %H:%M} {h}h{m:02d}m SpO2 avg {self.spo2_avg}% min {self.spo2_min}% "
127
+ f"<90%: {self.seconds_below_90}s drops(4%): {self.drops_4pct} {pulse}")
128
+
129
+ # ---- export ----
130
+ def to_csv(self, path: str | os.PathLike) -> None:
131
+ with open(path, "w", newline="") as f:
132
+ w = csv.writer(f)
133
+ w.writerow(["time", "spo2", "pulse", "motion", "vibration"])
134
+ for s in self.samples:
135
+ w.writerow([s.time.isoformat(), "" if s.spo2 is None else s.spo2,
136
+ "" if s.pulse is None else s.pulse, s.motion, s.vibration])
o2sync/sync.py ADDED
@@ -0,0 +1,136 @@
1
+ """One-call download of new recordings from a Wellue/Viatom O2 oximeter."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import datetime as dt
6
+ import logging
7
+ import os
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+ from typing import Callable, Optional
11
+
12
+ from .client import O2Client, parse_device_time
13
+ from .recording import Recording, UnsupportedFormat
14
+ from .transport import Advertisement, Transport, make_transport
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+ # Device-name prefixes of oximeters that speak the "Oxy" protocol. "O2M" = Checkme O2 Max.
19
+ OXY_NAME_PREFIXES = ("O2M", "O2Ring", "O2 ", "Checkme_O2", "CheckO2", "SleepU", "SleepO2", "WearO2",
20
+ "KidsO2", "BabyO2", "Oxylink")
21
+
22
+ Reporter = Callable[[str], None]
23
+
24
+
25
+ class DeviceNotFound(RuntimeError):
26
+ pass
27
+
28
+
29
+ @dataclass
30
+ class SyncResult:
31
+ address: str
32
+ device_info: dict
33
+ clock_offset: Optional[dt.timedelta] # device clock minus host clock, before any correction
34
+ clock_set: bool
35
+ downloaded: list[Recording] = field(default_factory=list)
36
+ skipped: list[str] = field(default_factory=list) # already present locally
37
+ paths: list[Path] = field(default_factory=list)
38
+
39
+ @property
40
+ def recordings(self) -> list[Recording]:
41
+ return self.downloaded
42
+
43
+
44
+ def is_oxy_name(name: str) -> bool:
45
+ return any(name.startswith(p) for p in OXY_NAME_PREFIXES)
46
+
47
+
48
+ async def find_device(transport: Transport, timeout: float = 15.0, name: Optional[str] = None) -> Advertisement:
49
+ ads = await transport.scan(timeout)
50
+ for ad in ads:
51
+ if (name and ad.name == name) or (not name and is_oxy_name(ad.name)):
52
+ return ad
53
+ want = f"named {name!r}" if name else "with an O2 oximeter name"
54
+ raise DeviceNotFound(f"no BLE device {want} found in {timeout:g}s. Wake the oximeter (press its button), "
55
+ "keep it close, and close the ViHealth app on your phone (only one connection is allowed).")
56
+
57
+
58
+ async def async_sync(
59
+ out_dir: str | os.PathLike = "recordings",
60
+ *,
61
+ address: Optional[str] = None,
62
+ set_time: bool = True,
63
+ skip_existing: bool = True,
64
+ scan_timeout: float = 15.0,
65
+ transport: Optional[Transport] = None,
66
+ report: Optional[Reporter] = None,
67
+ ) -> SyncResult:
68
+ """Connect to the oximeter, optionally set its clock, and download recordings not yet in ``out_dir``.
69
+
70
+ Files are saved under their device name (``yyyyMMddHHmmss``, no extension), the raw format that tools such
71
+ as OSCAR import. Nothing is ever deleted from the device.
72
+ """
73
+ say = report or (lambda msg: log.info("%s", msg))
74
+ out = Path(out_dir)
75
+ out.mkdir(parents=True, exist_ok=True)
76
+ transport = transport or make_transport()
77
+ try:
78
+ if address is None:
79
+ say(f"scanning for {scan_timeout:g}s ...")
80
+ ad = await find_device(transport, scan_timeout)
81
+ address = ad.address
82
+ say(f"found {ad.name} at {ad.address} (rssi {ad.rssi})")
83
+ client = O2Client(transport)
84
+ await client.connect(address)
85
+ try:
86
+ info = await client.info()
87
+ offset = None
88
+ if "CurTIME" in info:
89
+ offset = parse_device_time(info["CurTIME"]) - dt.datetime.now().replace(microsecond=0)
90
+ say(f"connected: model {info.get('Model')} fw {info.get('SoftwareVer')} battery {info.get('CurBAT')}")
91
+ clock_set = False
92
+ if set_time and offset is not None and abs(offset) > dt.timedelta(seconds=2):
93
+ await client.set_time()
94
+ clock_set = True
95
+ say(f"device clock was off by {_fmt_offset(offset)}; set to host time")
96
+ result = SyncResult(address, info, offset, clock_set)
97
+
98
+ names = [f for f in info.get("FileList", "").split(",") if f]
99
+ say(f"{len(names)} file(s) on device")
100
+ for name in names:
101
+ path = out / _safe_name(name)
102
+ if skip_existing and path.exists():
103
+ result.skipped.append(name)
104
+ continue
105
+ data = await client.read_file(name)
106
+ tmp = path.with_suffix(path.suffix + ".part")
107
+ tmp.write_bytes(data)
108
+ tmp.replace(path)
109
+ result.paths.append(path)
110
+ try:
111
+ rec = Recording.from_bytes(data, name=name)
112
+ result.downloaded.append(rec)
113
+ say(f"downloaded {name}: {rec.summary()}")
114
+ except UnsupportedFormat as e:
115
+ say(f"downloaded {name} ({len(data)} bytes) but could not parse it: {e}")
116
+ return result
117
+ finally:
118
+ await client.disconnect()
119
+ finally:
120
+ await transport.close()
121
+
122
+
123
+ def sync(out_dir: str | os.PathLike = "recordings", **kwargs) -> SyncResult:
124
+ """Blocking wrapper around :func:`async_sync`."""
125
+ return asyncio.run(async_sync(out_dir, **kwargs))
126
+
127
+
128
+ def _safe_name(name: str) -> str:
129
+ return "".join(c if c.isalnum() or c in "._-" else "_" for c in name) or "unnamed"
130
+
131
+
132
+ def _fmt_offset(td: dt.timedelta) -> str:
133
+ s = int(td.total_seconds())
134
+ sign = "+" if s >= 0 else "-"
135
+ s = abs(s)
136
+ return f"{sign}{s // 3600}h{s % 3600 // 60:02d}m{s % 60:02d}s"
@@ -0,0 +1,56 @@
1
+ """BLE transport. The client only needs this small async interface (see :class:`Transport`), which keeps it
2
+ testable against a simulated device; the real implementation is bleak (Linux/BlueZ, Windows/WinRT, macOS)."""
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from dataclasses import dataclass
7
+ from typing import Callable, Protocol
8
+
9
+ NotifyCallback = Callable[[bytes], None]
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class Advertisement:
14
+ address: str
15
+ name: str
16
+ rssi: int
17
+
18
+
19
+ class Transport(Protocol):
20
+ async def scan(self, timeout: float) -> list[Advertisement]: ...
21
+ async def connect(self, address: str) -> None: ...
22
+ async def start_notify(self, char_uuid: str, callback: NotifyCallback) -> None: ...
23
+ async def write(self, char_uuid: str, data: bytes) -> None: ...
24
+ async def disconnect(self) -> None: ...
25
+ async def close(self) -> None: ...
26
+
27
+
28
+ class BackendUnavailable(RuntimeError):
29
+ pass
30
+
31
+
32
+ _WINDOWS_BLOCKED_HINT = (
33
+ "bleak's Windows backend could not load its native 'winrt' module ({err}). If the message mentions an "
34
+ "Application Control policy, Windows Smart App Control or WDAC blocked the unsigned file. Smart App Control "
35
+ "usually allows it after its cloud reputation check, so retry later, or install the versions known to work "
36
+ "with: pip install -c constraints.txt -e ."
37
+ )
38
+
39
+
40
+ def check_backend() -> None:
41
+ """Raise :class:`BackendUnavailable` with an actionable message if bleak cannot load here."""
42
+ try:
43
+ import bleak # noqa: F401
44
+ if sys.platform == "win32":
45
+ # bleak loads its WinRT backend lazily; import it now so failures surface with a clear message.
46
+ import bleak.backends.winrt.scanner # noqa: F401
47
+ except ImportError as e:
48
+ if sys.platform == "win32" and "bleak" in sys.modules:
49
+ raise BackendUnavailable(_WINDOWS_BLOCKED_HINT.format(err=e)) from e
50
+ raise BackendUnavailable(f"bleak is not installed or cannot load: {e}. Install it with: pip install bleak") from e
51
+
52
+
53
+ def make_transport() -> Transport:
54
+ check_backend()
55
+ from .bleak_transport import BleakTransport
56
+ return BleakTransport()
@@ -0,0 +1,65 @@
1
+ """Transport on top of bleak (Linux/BlueZ, macOS, Windows when its WinRT module may load)."""
2
+ from __future__ import annotations
3
+
4
+ from . import Advertisement, NotifyCallback
5
+
6
+
7
+ class BleakTransport:
8
+ def __init__(self, connect_timeout: float = 20.0):
9
+ self.connect_timeout = connect_timeout
10
+ self._client = None
11
+ self._devices: dict = {}
12
+
13
+ async def scan(self, timeout: float) -> list[Advertisement]:
14
+ from bleak import BleakScanner
15
+
16
+ found = await BleakScanner.discover(timeout=timeout, return_adv=True)
17
+ out = []
18
+ for dev, adv in found.values():
19
+ self._devices[dev.address.upper()] = dev
20
+ out.append(Advertisement(dev.address.upper(), adv.local_name or dev.name or "", adv.rssi))
21
+ return sorted(out, key=lambda a: -a.rssi)
22
+
23
+ async def connect(self, address: str) -> None:
24
+ from bleak import BleakClient
25
+
26
+ # Reuse the BLEDevice from a previous scan when we have it (faster, required on some BlueZ setups).
27
+ target = self._devices.get(address.upper(), address)
28
+ self._client = BleakClient(target, timeout=self.connect_timeout)
29
+ await self._client.connect()
30
+
31
+ async def start_notify(self, char_uuid: str, callback: NotifyCallback) -> None:
32
+ await self._require().start_notify(char_uuid, lambda _c, data: callback(bytes(data)))
33
+
34
+ async def write(self, char_uuid: str, data: bytes) -> None:
35
+ await self._require().write_gatt_char(char_uuid, data, response=False)
36
+
37
+ async def disconnect(self) -> None:
38
+ client, self._client = self._client, None
39
+ if client is not None and client.is_connected:
40
+ await client.disconnect()
41
+
42
+ async def close(self) -> None:
43
+ await self.disconnect()
44
+
45
+ def _require(self):
46
+ if self._client is None:
47
+ raise RuntimeError("not connected")
48
+ return self._client
49
+
50
+ async def gatt_dump(self, address: str) -> str:
51
+ if self._client is None or not self._client.is_connected:
52
+ await self.connect(address)
53
+ client = self._require()
54
+ lines = [f"Address: {client.address}"]
55
+ for svc in client.services:
56
+ lines.append(f"[Service] {svc.uuid}")
57
+ for ch in svc.characteristics:
58
+ line = f" [Char] {ch.uuid} ({','.join(ch.properties)})"
59
+ if "read" in ch.properties:
60
+ try:
61
+ line += f" value={(await client.read_gatt_char(ch)).hex()}"
62
+ except Exception as e: # noqa: BLE001
63
+ line += f" read failed: {e}"
64
+ lines.append(line)
65
+ return "\n".join(lines)
@@ -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,16 @@
1
+ o2sync/__init__.py,sha256=8RDKoNhDUHqe5r1-JNWBzGHB3hCAVBKuTJG6Ay8w_Vk,978
2
+ o2sync/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
+ o2sync/cli.py,sha256=e-g9K5ddxEiO3Y8KsDTERimPWDgNgBtH8NpmiEvlIxw,6848
4
+ o2sync/client.py,sha256=p7PvY8iQW2thoGfmFBnB9WeRSVTovyhpIlref9uErGE,4813
5
+ o2sync/plot.py,sha256=ndZfq2KQ-dM998h-E6YWix70J1veDq9n8f-WoIttABo,9888
6
+ o2sync/protocol.py,sha256=bMbXoSVVpKud3Rik9ijMWYCK4z0RvqZG-5A-yl_S72k,3095
7
+ o2sync/recording.py,sha256=ZlHkZy--o_lnvLyOwu8Khet9_WnvoxXxYZQl4DsEHuY,5068
8
+ o2sync/sync.py,sha256=RJZeqNUDy4f6TZ6L2C-ChzBt7-Cz0pKK3UMESNaHaWM,5239
9
+ o2sync/transport/__init__.py,sha256=f0pg2O1FL3n0n-mN0sYtNYJrQ5O2vhz5uzLxheZYAHY,2135
10
+ o2sync/transport/bleak_transport.py,sha256=JeT5WFgWAGOtHPdquYhq8AQzbzY4wEl6RhleYaOUI30,2663
11
+ o2sync-0.1.0.dist-info/licenses/LICENSE,sha256=8sejkPzScPAZVZtkHl0PWrsElhy5lhMa4aElhQIgEH0,1068
12
+ o2sync-0.1.0.dist-info/METADATA,sha256=q3SpFl6BxtfDqx--Ktfi72_zAgm1Z20ujMAPlCAKTuw,5605
13
+ o2sync-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
14
+ o2sync-0.1.0.dist-info/entry_points.txt,sha256=Bs9Pa2eia17JGDGp_VmH8qcQo845N7wyKmQ4lpwJsSA,43
15
+ o2sync-0.1.0.dist-info/top_level.txt,sha256=GDTvapKJ4x7fqwzCC0BmBQYytXxKtQTaZnkaJQDP7zU,7
16
+ o2sync-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ o2sync = o2sync.cli:main
@@ -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 @@
1
+ o2sync