From 10756983214b4c8bf5a922c36f40f3746ce4f151 Mon Sep 17 00:00:00 2001 From: Riaan Doorduin Date: Sat, 17 Oct 2026 12:35:08 +0200 Subject: [PATCH] =?UTF-8?q?Phase=200:=20mygarmin=20package=20=E2=80=94=20l?= =?UTF-8?q?ibrary,=20importers,=20dedupe,=20dashboard,=20exports,=20CLI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Generalised from personal scripts: SQLite library with untouched originals, importers for FIT, TCX, GPX, AlpineQuest .trk, Strava and Garmin Connect exports, the Garmin Connect API and a USB watch; cross-source de-duplication; time zones from GPS; data-driven dashboard and GPX/.trk exports. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 28 ++++++ README.md | 56 +++++++++++ docs/PLAN.md | 57 +++++++++++ pyproject.toml | 27 ++++++ src/mygarmin/__init__.py | 2 + src/mygarmin/cli.py | 79 ++++++++++++++++ src/mygarmin/dedupe.py | 32 +++++++ src/mygarmin/export.py | 52 +++++++++++ src/mygarmin/formats/__init__.py | 0 src/mygarmin/formats/aqtrk.py | 130 ++++++++++++++++++++++++++ src/mygarmin/formats/fit.py | 46 +++++++++ src/mygarmin/formats/geo.py | 29 ++++++ src/mygarmin/formats/gpx.py | 34 +++++++ src/mygarmin/formats/tcx.py | 45 +++++++++ src/mygarmin/library.py | 97 +++++++++++++++++++ src/mygarmin/report/__init__.py | 59 ++++++++++++ src/mygarmin/sources/__init__.py | 60 ++++++++++++ src/mygarmin/sources/files.py | 123 ++++++++++++++++++++++++ src/mygarmin/sources/garmin_api.py | 108 +++++++++++++++++++++ src/mygarmin/sources/garmin_export.py | 113 ++++++++++++++++++++++ src/mygarmin/sources/strava.py | 60 ++++++++++++ src/mygarmin/sources/watch.py | 46 +++++++++ src/mygarmin/timeutil.py | 29 ++++++ tests/test_pipeline.py | 84 +++++++++++++++++ tools/compare_csv.py | 32 +++++++ 25 files changed, 1428 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 docs/PLAN.md create mode 100644 pyproject.toml create mode 100644 src/mygarmin/__init__.py create mode 100644 src/mygarmin/cli.py create mode 100644 src/mygarmin/dedupe.py create mode 100644 src/mygarmin/export.py create mode 100644 src/mygarmin/formats/__init__.py create mode 100644 src/mygarmin/formats/aqtrk.py create mode 100644 src/mygarmin/formats/fit.py create mode 100644 src/mygarmin/formats/geo.py create mode 100644 src/mygarmin/formats/gpx.py create mode 100644 src/mygarmin/formats/tcx.py create mode 100644 src/mygarmin/library.py create mode 100644 src/mygarmin/report/__init__.py create mode 100644 src/mygarmin/sources/__init__.py create mode 100644 src/mygarmin/sources/files.py create mode 100644 src/mygarmin/sources/garmin_api.py create mode 100644 src/mygarmin/sources/garmin_export.py create mode 100644 src/mygarmin/sources/strava.py create mode 100644 src/mygarmin/sources/watch.py create mode 100644 src/mygarmin/timeutil.py create mode 100644 tests/test_pipeline.py create mode 100644 tools/compare_csv.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..52828de --- /dev/null +++ b/.gitignore @@ -0,0 +1,28 @@ +# Personal data must never be committed: libraries, databases, originals, tokens, generated output. +*.db +*.db-journal +*.fit +*.FIT +*.fit.gz +*.tcx +*.trk +*.ldk +*.zip +dashboard*.html +settings.json +.garminconnect/ +garmin_tokens.json +library/ +originals/ +exports/ +inbox/ +# synthetic test fixtures are allowed +!tests/data/** + +__pycache__/ +*.pyc +.pytest_cache/ +build/ +dist/ +*.egg-info/ +.venv/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..5ae7a8b --- /dev/null +++ b/README.md @@ -0,0 +1,56 @@ +# myGarmin + +A local-first logbook for your activity and health history. It collects data from Garmin (watch over USB, Connect +account export, Connect API), Strava (account export) and AlpineQuest (.trk), keeps the original files in one library +folder, and builds a self-contained HTML dashboard plus GPX and AlpineQuest exports. + +Everything stays on your PC: there is no server and no account, and nothing is uploaded anywhere. + +> Status: early (phase 0/1 of [docs/PLAN.md](docs/PLAN.md)), command line only. A desktop window and installer come next. + +## Install +Python 3.12 or newer: +``` +pip install -e . # from a checkout of this repo +pip install -e ".[api]" # also the Garmin Connect API (optional) +``` + +## Use +``` +mygarmin init D:\myGarmin --name Sam --birth-year 1985 --sex F --tz Europe/London +mygarmin import D:\myGarmin +mygarmin build D:\myGarmin # -> D:\myGarmin\dashboard.html and all_activities.csv +mygarmin export D:\myGarmin # -> exports\tracks_gpx.zip and tracks_trk.zip (one track per outing, by year) +``` +Keeping it up to date: +``` +mygarmin watch D:\myGarmin # Windows: read a Garmin watch connected by USB +mygarmin login D:\myGarmin # once: log in to Garmin Connect (password + MFA code) +mygarmin sync D:\myGarmin # new activities and daily health from Garmin Connect +mygarmin update D:\myGarmin # all of the above + build + export +``` + +### Where to get your data +| Source | How | +|---|---| +| Garmin Connect | garmin.com → Account → Data Management → Export Your Data. Arrives by e-mail as a zip; import the zip as is. | +| Strava | strava.com → Settings → My Account → Download or Delete Your Account → Request your archive. Import the zip as is. | +| AlpineQuest | Copy the `.trk` files from the phone (AlpineQuest folder, `Landmarks`/`Tracks`). | +| Garmin watch | Connect by USB and run `mygarmin watch`, or copy the watch's `GARMIN` folder and import it. | +| Races | Optional `races.csv` in the library: `date,event,time[,km,age_grade,position,pb]` (km defaults to 5). | + +## How it works +- Originals are copied unchanged into `/originals/`; the SQLite database `myGarmin.db` and everything else can + be rebuilt from them. Importing the same file twice does nothing. +- One outing recorded by several sources (watch, phone, Strava) is kept once, preferring the watch. + Car/plane/train/boat trips and very short tracks are flagged and left out of the dashboard. +- Local times come from the file itself or the GPS position (offline time zone lookup). +- **The Garmin Connect API is unofficial** (python-garminconnect). Garmin has no personal API; this logs in the way the + Connect app does and can break when Garmin changes its login. Your login token is stored on your PC only. The export + zip and the watch over USB always work. + +## Privacy +This repository never contains personal data. Your library folder holds your health data: keep it private. + +## Development +`pip install -e ".[dev]"` then `pytest`. Tests use synthetic files only. diff --git a/docs/PLAN.md b/docs/PLAN.md new file mode 100644 index 0000000..fd827e0 --- /dev/null +++ b/docs/PLAN.md @@ -0,0 +1,57 @@ +# myGarmin app — plan + +A local-first desktop app that collects a person's activity and health history from Garmin (watch, Connect export, Connect API), +Strava (bulk export) and AlpineQuest (.trk), keeps the originals in one library folder, and builds a self-contained HTML +dashboard plus GPX / AlpineQuest exports. Nothing leaves the user's PC; there is no server. + +Grown out of a set of personal scripts (2026-10); this repo is the general, shareable version. + +## Principles +- **Local only.** Each user's data, settings and Garmin token stay on their machine. The repo never contains personal data. +- **Originals are kept unchanged** in `originals/`; everything else (database, dashboard, exports) can be rebuilt from them. +- **Import is idempotent.** Files are identified by content (md5); importing the same thing twice does nothing. +- **Every source is optional.** The dashboard shows only the sections that have data. +- **The unofficial Garmin API is optional** and may break when Garmin changes its login; export zips and the watch over USB always work. + +## Library folder (one per user) +``` +/ + settings.json name, birth year, home time zone, units + myGarmin.db SQLite: activities, tracks, daily health, series, imported files + inbox/ drop zone (optional) + originals/ garmin_fit/ garmin_export/ strava/ alpinequest/ tcx/ gpx/ + exports/ gpx/ trk/ + dashboard.html +``` + +## Phases +| Phase | Scope | Done when | +|---|---|---| +| 0 | Generalise the scripts into the `mygarmin` package: settings, SQLite, one importer per source with auto-detection, time zone from GPS/FIT, cross-source de-duplication, data-driven findings, exports. | Rebuilding the author's library from the original files reproduces the existing dashboard numbers. | +| 1 | CLI: `mygarmin init / import / sync / build / export`. | A library can be built from scratch with the CLI only. | +| 2 | UI: local web UI in its own window (pywebview): setup wizard, import (drag and drop), sync, dashboard, export. | Used for a week instead of the CLI. | +| 3 | Windows installer (PyInstaller + Inno Setup), releases on Gitea. | Installs on a clean PC. | +| 4 | Trial with 2–3 users on other devices. | Their data imports without code changes. | +| later | Scheduled sync, macOS, Strava API, Apple Health / COROS / Polar exports. | | + +## Sources +| Source | Input | Gives | +|---|---|---| +| Garmin watch (USB, Windows MTP) | `GARMIN\Activity`, `Monitor`, … | activity FITs, health FITs | +| Garmin Connect export | account export zip (`DI_CONNECT\…`, uploaded FIT zips) | daily health, VO2max, fitness age, BP, all activity FITs | +| Garmin Connect API (unofficial, python-garminconnect) | login once, token kept locally | new activities (original FIT) and daily health | +| Strava export | account export zip (`activities.csv`, `activities/*.fit.gz|gpx`) | activities with name, moving time | +| AlpineQuest | `.trk` (and `.gpx`) | phone-recorded tracks; transport and very short tracks are flagged, not deleted | +| Older Garmin / other | `.tcx`, `.gpx`, `.fit` | activities | + +## De-duplication +One outing is often recorded by several sources. All are imported; a later pass marks the lower-priority copies +`dup_of` the best one. Priority: FIT > TCX > AlpineQuest > Strava > GPX. Two activities are the same outing when they start +within 15 min of each other, or their time ranges overlap by more than half of the shorter one. + +## Time zones +Local time comes from the FIT `local_timestamp` where present, otherwise from the first GPS point (`timezonefinder`, offline), +otherwise the home time zone in `settings.json`. + +## Not in the repo +Personal data, `*.db`, tokens, original files, generated dashboards. Tests use small synthetic files in `tests/data/`. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..5484d1f --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,27 @@ +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +[project] +name = "mygarmin" +version = "0.1.0" +description = "Local-first activity and health logbook for Garmin, Strava and AlpineQuest data" +readme = "README.md" +requires-python = ">=3.12" +dependencies = ["fitparse>=1.2", "timezonefinder>=6"] + +[project.optional-dependencies] +api = ["garminconnect>=0.3.19", "curl_cffi"] +dev = ["pytest"] + +[project.scripts] +mygarmin = "mygarmin.cli:main" + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.setuptools.package-data] +mygarmin = ["report/*.html"] + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/src/mygarmin/__init__.py b/src/mygarmin/__init__.py new file mode 100644 index 0000000..18cd4db --- /dev/null +++ b/src/mygarmin/__init__.py @@ -0,0 +1,2 @@ +"""myGarmin: local-first activity and health logbook for Garmin, Strava and AlpineQuest data.""" +__version__ = '0.1.0' diff --git a/src/mygarmin/cli.py b/src/mygarmin/cli.py new file mode 100644 index 0000000..ccf2643 --- /dev/null +++ b/src/mygarmin/cli.py @@ -0,0 +1,79 @@ +"""mygarmin command line. + mygarmin init [--name N] [--birth-year Y] [--sex M|F] [--tz Area/City] + mygarmin settings [same options] change settings + mygarmin import ... anything: watch folder, Garmin/Strava export zip, .fit .tcx .gpx .trk + mygarmin watch read a USB-connected Garmin watch (Windows) and import it + mygarmin login log in to Garmin Connect once (asks for password and MFA code) + mygarmin sync fetch new activities and daily health from Garmin Connect + mygarmin update watch (if connected) + sync + build + export + mygarmin build dashboard.html + all_activities.csv + mygarmin export exports/tracks_gpx.zip + tracks_trk.zip (AlpineQuest) + mygarmin status +""" +import argparse, collections, sys, time +from .library import Library + +def main(argv=None): + ap = argparse.ArgumentParser(prog='mygarmin', description='Local activity and health logbook') + sub = ap.add_subparsers(dest='cmd', required=True) + for c in ('init', 'settings'): + p = sub.add_parser(c); p.add_argument('library'); p.add_argument('--name'); p.add_argument('--birth-year', type=int) + p.add_argument('--sex', choices=['M', 'F']); p.add_argument('--tz', help='home time zone, e.g. Africa/Johannesburg') + p = sub.add_parser('import'); p.add_argument('library'); p.add_argument('paths', nargs='+') + for c in ('dedupe', 'build', 'export', 'status', 'watch', 'login', 'sync'): sub.add_parser(c).add_argument('library') + p = sub.add_parser('update'); p.add_argument('library'); p.add_argument('--no-watch', action='store_true'); p.add_argument('--no-api', action='store_true') + a = ap.parse_args(argv) + + if a.cmd in ('init', 'settings'): + if a.tz: + from zoneinfo import ZoneInfo + ZoneInfo(a.tz) # fails early on a misspelt zone + lib = Library.create(a.library, name=a.name, birth_year=a.birth_year, sex=a.sex, home_tz=a.tz) + print('library ready:', lib.root, lib.settings); return + lib = Library(a.library) + if a.cmd == 'import': + from . import dedupe, sources + for p in a.paths: + t = time.time(); print('importing', p, flush=True) + st = sources.import_path(lib, p) + for k, v in sorted(st.items()): print(f' {v:6d} {k}') + print(f' ({time.time() - t:.0f} s)') + print(dedupe.run(lib), 'activities marked as duplicates of another source') + elif a.cmd == 'dedupe': + from . import dedupe + print(dedupe.run(lib), 'activities marked as duplicates of another source') + elif a.cmd == 'login': + import getpass + from .sources import garmin_api + name = garmin_api.login(lib, input('Garmin email: ').strip(), getpass.getpass('Garmin password (not shown): '), + lambda: input('MFA code: ').strip()) + print('Logged in as', name, '- token kept on this PC only') + elif a.cmd in ('watch', 'sync', 'update'): + import shutil + from . import dedupe, export, report, sources + from .sources import garmin_api, watch + if a.cmd == 'watch' or (a.cmd == 'update' and not a.no_watch): + d = watch.pull() + if d: + for k, v in sorted(sources.import_path(lib, d).items()): print(f' {v:6d} {k}') + shutil.rmtree(d, ignore_errors=True) + if a.cmd == 'sync' or (a.cmd == 'update' and not a.no_api): + garmin_api.sync(lib) + print(dedupe.run(lib), 'activities marked as duplicates of another source') + if a.cmd == 'update': + report.build(lib); export.run(lib) + elif a.cmd == 'build': + from . import report + report.build(lib) + elif a.cmd == 'export': + from . import export + export.run(lib) + elif a.cmd == 'status': + acts = lib.activities() + print(len(acts), 'activities;', sum(1 for r in acts if r['dup_of']), 'duplicates;', sum(1 for r in acts if r['flag']), 'flagged') + c = collections.Counter((r['source'], 'duplicate' if r['dup_of'] else (r['flag'] or 'ok')) for r in acts) + for k, v in sorted(c.items()): print(f' {v:6d} {k[0]:12s} {k[1]}') + d = lib.days(); print(len(d), 'health days', d[0]['d'] if d else '', '..', d[-1]['d'] if d else '') + +if __name__ == '__main__': + sys.exit(main()) diff --git a/src/mygarmin/dedupe.py b/src/mygarmin/dedupe.py new file mode 100644 index 0000000..b53da88 --- /dev/null +++ b/src/mygarmin/dedupe.py @@ -0,0 +1,32 @@ +"""Mark activities that are another source's recording of the same outing (dup_of = the one kept). +Same outing: starts within 15 min, or more than half of the lower-priority recording lies inside the kept one +(so a short run recorded during a long phone-tracked ride does not swallow the ride). +Within one source only near-identical starts (< 60 s) count, e.g. the same FIT saved twice with different bytes.""" +import bisect +from .timeutil import parse_utc + +PRIORITY = {'fit': 0, 'tcx': 1, 'alpinequest': 2, 'strava': 3, 'gpx': 4} +IGNORED_FLAGS = ('transport', 'too short', 'no time') # never kept as the reference, never marked + +def run(lib): + rows = [r for r in lib.activities() if r['flag'] not in IGNORED_FLAGS] + for r in rows: + r['t0'] = parse_utc(r['start_utc']).timestamp(); r['t1'] = r['t0'] + (r['elapsed_s'] or r['moving_s'] or 0) + rows.sort(key=lambda r: (PRIORITY.get(r['source'], 9), r['t0'])) + kept, starts, dup = [], [], {} + for r in rows: + i = bisect.bisect_left(starts, r['t0'] - 24 * 3600) # nothing lasts a day; only look at nearby starts + match = None + for k in sorted(kept[i:], key=lambda k: abs(k['t0'] - r['t0'])): + if k['t0'] > r['t1'] + 900: continue + same = k['source'] == r['source'] + near = abs(k['t0'] - r['t0']) < (60 if same else 900) + ov = min(k['t1'], r['t1']) - max(k['t0'], r['t0']) + if near or (not same and ov > 0.5 * max(1, r['t1'] - r['t0'])): match = k; break # r mostly inside k + if match: dup[r['id']] = match['id'] + else: + j = bisect.bisect(starts, r['t0']); starts.insert(j, r['t0']); kept.insert(j, r) + lib.db.execute('UPDATE activities SET dup_of=NULL') + lib.db.executemany('UPDATE activities SET dup_of=? WHERE id=?', [(v, k) for k, v in dup.items()]) + lib.commit() + return len(dup) diff --git a/src/mygarmin/export.py b/src/mygarmin/export.py new file mode 100644 index 0000000..db296e9 --- /dev/null +++ b/src/mygarmin/export.py @@ -0,0 +1,52 @@ +"""GPX and AlpineQuest .trk exports at full resolution, read back from the original files. +One file per outing (duplicates from other sources are skipped); transport and very short tracks are left out.""" +import gzip, os, re, zipfile +from datetime import datetime, timezone +from .formats import aqtrk, fit, gpx, tcx + +AQ_ACTIVITY = {'running': 'run', 'cycling': 'bicycle', 'hiking': 'hike', 'mountaineering': 'hike', 'walking': 'walk'} + +def full_points(lib, a): + """[{lat, lon, ele, t (datetime UTC), hr}] from the activity's original file.""" + p = lib.path(a['file']) + if not os.path.exists(p): return [] + data = open(p, 'rb').read() + n = p.lower() + if n.endswith('.gz'): data, n = gzip.decompress(data), n[:-3] + if n.endswith('.fit'): return fit.read(data)['points'] + if n.endswith('.tcx'): return (tcx.read(data.lstrip()) or {}).get('points', []) + if n.endswith('.gpx'): return gpx.read(data)['points'] + if n.endswith('.trk'): + t = aqtrk.parse_any(data) + return [{'lat': q['lat'], 'lon': q['lon'], 'ele': q.get('ele'), 'hr': None, + 't': datetime.fromtimestamp(q['t'] / 1000, timezone.utc) if q.get('t') else None} for s in t['segments'] for q in s] + return [] + +def stem(a): + s = a['start_local'][:16].replace(' ', '-').replace(':', '-') + '_' + (a['sport'] or 'activity') + if a.get('name'): s += '_' + (re.sub(r'[^\w\- ]+', '', a['name']).strip().replace(' ', '-')[:40]) + return s + +def run(lib, out_dir=None, log=print): + out_dir = out_dir or lib.path('exports') + os.makedirs(out_dir, exist_ok=True) + acts = lib.activities("dup_of IS NULL AND npts > 1 AND (flag IS NULL OR flag IN ('suspect GPS', 'summary only'))") + gz, tz = os.path.join(out_dir, 'tracks_gpx.zip'), os.path.join(out_dir, 'tracks_trk.zip') + names, n = set(), 0 + with zipfile.ZipFile(gz + '.tmp', 'w', zipfile.ZIP_DEFLATED) as zg, zipfile.ZipFile(tz + '.tmp', 'w', zipfile.ZIP_DEFLATED) as zt: + for a in acts: + pts = [p for p in full_points(lib, a) if p.get('lat') is not None] + if len(pts) < 2: continue + s = stem(a); year = a['start_local'][:4] + while s in names: s += '_2' + names.add(s) + title = a['start_local'][:10] + ' ' + (a.get('name') or a['sport'] or '') + zg.writestr(f'{year}/{s}.gpx', gpx.write(pts, title, a['sport'] or '')) + tp = [(p['lat'], p['lon'], p.get('ele'), int(p['t'].timestamp() * 1000) if p.get('t') else None) for p in pts] + data = aqtrk.to_trk(tp, title, AQ_ACTIVITY.get(a['sport'], 'other'), f"{a['source']} activity {title}", 'myGarmin') + back = aqtrk.parse_any(data)['segments'][0] # every .trk is checked by reading it back + assert len(back) == len(tp) and abs(back[-1]['lat'] - tp[-1][0]) < 1e-6, s + zt.writestr(f'{year}/{s}.trk', data); n += 1 + os.replace(gz + '.tmp', gz); os.replace(tz + '.tmp', tz) + log(f'{n} tracks -> {gz}, {tz}') + return n diff --git a/src/mygarmin/formats/__init__.py b/src/mygarmin/formats/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/mygarmin/formats/aqtrk.py b/src/mygarmin/formats/aqtrk.py new file mode 100644 index 0000000..0ef7c64 --- /dev/null +++ b/src/mygarmin/formats/aqtrk.py @@ -0,0 +1,130 @@ +# AlpineQuest .trk files: parser and writer, per Psyberia "Landmarks files specs" (update 10, 2023-05-20). +import struct + +class R: + def __init__(s, b): s.b, s.i = b, 0 + def take(s, n): v = s.b[s.i:s.i + n]; s.i += n; return v + def byte(s): return struct.unpack('>b', s.take(1))[0] + def int(s): return struct.unpack('>i', s.take(4))[0] + def long(s): return struct.unpack('>q', s.take(8))[0] + def dbl(s): return struct.unpack('>d', s.take(8))[0] + def str(s): return s.take(s.int()).decode('utf-8', 'replace') + +def content(r): + n = r.int(); d = {} + if n == -1: return None + for _ in range(n): + name = r.str(); t = r.int() + if t == -1: v = bool(r.byte()) + elif t == -2: v = r.long() + elif t == -3: v = r.dbl() + elif t == -4: v = r.take(r.int()) + else: v = r.take(t).decode('utf-8', 'replace') + d[name] = v + r.int() # metadata version + return d + +def metadata(r): + d = content(r) + if d is None: return {} # -1 entries: no version, no extensions + for _ in range(max(r.int(), 0)): r.str(); content(r) + return d + +def location(r): + size = r.int(); end = r.i + size + p = {'lon': r.int() * 1e-7, 'lat': r.int() * 1e-7} + while r.i < end: + t = r.byte() + if t == 0x61: p['acc'] = r.int() / 100 + elif t == 0x62: r.take(1) + elif t == 0x65: p['ele'] = r.int() / 1000 + elif t == 0x6e: r.take(2) + elif t == 0x70: p['hpa'] = r.int() / 1000 + elif t == 0x73: r.take(8) + elif t == 0x74: p['t'] = r.long() + elif t == 0x76: p['vacc'] = r.int() / 100 + else: r.i = end # unknown value type: skip rest of this location + r.i = end + return p + +def _bytes(src): return src if isinstance(src, (bytes, bytearray)) else open(src, 'rb').read() + +def parse(src): + r = R(_bytes(src)) + head = r.int(); magic, ver = head >> 8, head & 0xff + if magic != 0x50500E: raise ValueError(f'not a track file (magic {magic:#x}, version {ver})') + hsize = r.int() + tech = metadata(r); user = metadata(r) + for _ in range(r.int()): metadata(r); location(r) # waypoints + segs = [] + for _ in range(r.int()): + metadata(r); segs.append([location(r) for _ in range(r.int())]) + return dict(version=ver, tech=tech, user=user, segments=segs) + +# Legacy format (files written before AQ 2.2.8): first int is the bare version (2 or 3), layout as in alp2gpx. +def _legacy_meta(r, ver): + d = {} + for _ in range(r.int()): + name = r.str(); t = r.int() + if t == -1: v = bool(r.byte()) + elif t == -2: v = r.long() + elif t == -3: v = r.dbl() + elif t == -4: v = r.take(r.int()) + else: v = r.take(t).decode('utf-8', 'replace') + d[name] = v + if ver == 3: r.int() + return d + +def _legacy_loc(r): + size = r.int(); end = r.i + size + p = {'lon': r.int() * 1e-7, 'lat': r.int() * 1e-7} + e = r.int() + if e != -999999999: p['ele'] = e / 1000 + p['t'] = r.long() + if size > 20: p['acc'] = r.int() / 100 + r.i = end + return p + +def parse_any(src): + """src = file path or bytes; handles the current format and the legacy (pre-2.2.8) one.""" + b = _bytes(src) + head = struct.unpack('>i', b[:4])[0] + if head >> 8 == 0x50500E: return parse(b) + if head not in (2, 3): raise ValueError(f'unknown header {head:#x}') + r = R(b); ver = r.int(); hsize = r.int(); r.i = 8 + hsize + user = _legacy_meta(r, ver) + for _ in range(r.int()): _legacy_meta(r, ver); _legacy_loc(r) # waypoints + segs = [] + for _ in range(r.int()): + if ver < 3: r.int() + else: _legacy_meta(r, ver) + segs.append([_legacy_loc(r) for _ in range(r.int())]) + return dict(version=f'legacy{ver}', tech={}, user=user, segments=segs) + +# Writer: MultiTrack file version 1, laid out like the .trk files AlpineQuest 2.3.x writes (as gpx2trk.py). +_i32 = lambda v: struct.pack('>i', v) +_i64 = lambda v: struct.pack('>q', v) +def _string(s): b = s.encode('utf-8'); return _i32(len(b)) + b + +def _metadata(entries): + out = _i32(len(entries)) + for name, v in entries: + out += _string(name) + if isinstance(v, int): out += _i32(-2) + _i64(v) + else: b = v.encode('utf-8'); out += _i32(len(b)) + b + return out + _i32(1) + _i32(-1) + +def _location(lat, lon, ele, t_ms): + body = _i32(round(lon * 1e7)) + _i32(round(lat * 1e7)) + if ele is not None: body += b'\x65' + _i32(round(ele * 1000)) + if t_ms is not None: body += b'\x74' + _i64(t_ms) + return _i32(len(body)) + body + +def to_trk(pts, name, activity, desc, creator): # pts = [(lat, lon, ele or None, t_ms or None)] + lat0, lon0, _, t0 = pts[0] + tech = _metadata([('lat', round(lat0 * 1e7)), ('lon', round(lon0 * 1e7))] + ([('dte', t0)] if t0 else [])) + user = _metadata([('name', name), ('file_desc', desc), ('creator', creator), ('activity', activity)]) + head = tech + user + body = _i32(0) + _i32(1) + _i32(0) + _i32(0) + _i32(-1) # no waypoints; 1 segment, empty segment metadata + body += _i32(len(pts)) + b''.join(_location(*p) for p in pts) + return _i32(0x50500E01) + _i32(len(head)) + head + body diff --git a/src/mygarmin/formats/fit.py b/src/mygarmin/formats/fit.py new file mode 100644 index 0000000..b640a5d --- /dev/null +++ b/src/mygarmin/formats/fit.py @@ -0,0 +1,46 @@ +"""Garmin FIT files: file type, and for activities the session summary plus track points.""" +import io +from datetime import timedelta +import fitparse + +SC = 180 / 2 ** 31 +ACTIVITY_TYPES = {'activity', 'activity_summary'} +HEALTH_TYPES = {'monitoring_a', 'monitoring_b', 'monitoring_daily', 'totals', '29', '44', '49', '68', '72', '74', '79'} +COURSE_TYPES = {'course'} + +def file_type(data): + try: + for m in fitparse.FitFile(io.BytesIO(data)).get_messages('file_id'): + return str(m.get_values().get('type')) + except Exception: + return None + +def read(data): + """-> {'type', 'summary': {...} or None, 'points': [{lat, lon, ele, t (datetime UTC), hr}], 'offset_min'}""" + f = fitparse.FitFile(io.BytesIO(data)) + ftype = s = up = act = None; m140 = {}; pts = [] + for m in f.get_messages(): + n = m.name + if n == 'file_id' and ftype is None: ftype = str(m.get_values().get('type')) + elif n == 'session' and s is None: s = m.get_values() + elif n == 'user_profile' and up is None: up = m.get_values() + elif n == 'activity' and act is None: act = m.get_values() + elif n == 'unknown_140' and not m140: m140 = m.get_values() + elif n == 'record': + v = m.get_values(); la, lo = v.get('position_lat'), v.get('position_long') + if la is not None and lo is not None and v.get('timestamp'): + e = v.get('enhanced_altitude') + pts.append({'lat': la * SC, 'lon': lo * SC, 'ele': e if e is not None else v.get('altitude'), + 't': v['timestamp'], 'hr': v.get('heart_rate')}) + out = {'type': ftype, 'summary': None, 'points': pts, 'offset_min': None} + if s is None or not s.get('start_time'): return out + if act and act.get('local_timestamp') and act.get('timestamp'): + out['offset_min'] = round((act['local_timestamp'] - act['timestamp']) / timedelta(minutes=15)) * 15 + vo2 = m140.get('unknown_7') # Garmin's undocumented VO2max message, value * 65536 / 3.5 + vo2 = round(vo2 * 3.5 / 65536, 1) if vo2 and 1 < vo2 * 3.5 / 65536 < 90 else None + out['summary'] = { + 'start': s['start_time'], 'sport': str(s.get('sport')), 'sub_sport': str(s.get('sub_sport')), + 'dist_m': s.get('total_distance') or 0, 'elapsed_s': s.get('total_elapsed_time') or 0, 'moving_s': s.get('total_timer_time') or 0, + 'ascent_m': s.get('total_ascent'), 'avg_hr': s.get('avg_heart_rate'), 'max_hr': s.get('max_heart_rate'), + 'kcal': s.get('total_calories'), 'te_aerobic': s.get('total_training_effect'), 'vo2max': vo2} + return out diff --git a/src/mygarmin/formats/geo.py b/src/mygarmin/formats/geo.py new file mode 100644 index 0000000..0dbc47e --- /dev/null +++ b/src/mygarmin/formats/geo.py @@ -0,0 +1,29 @@ +"""Distance, moving time and ascent from raw track points, for files without a summary (AlpineQuest, GPX).""" +import math + +def hav(la1, lo1, la2, lo2): + la1, lo1, la2, lo2 = map(math.radians, (la1, lo1, la2, lo2)) + h = math.sin((la2 - la1) / 2) ** 2 + math.cos(la1) * math.cos(la2) * math.sin((lo2 - lo1) / 2) ** 2 + return 12742000 * math.asin(math.sqrt(h)) + +def ascent(eles, hysteresis): + """Climb, counting only rises of more than `hysteresis` metres (filters GPS/barometer noise).""" + eles = [e for e in eles if e is not None] + if not eles: return None + asc, ref = 0.0, eles[0] + for e in eles: + if e > ref + hysteresis: asc += e - ref; ref = e + elif e < ref - hysteresis: ref = e + return asc + +def stats(pts, max_acc=50, hysteresis=5): + """pts: dicts with lat, lon, t (epoch s), optional ele, acc. -> dist_m, moving_s, ascent_m, p90 speed (m/s).""" + dist = mov = 0.0; speeds = []; eles = [pts[0].get('ele')] if pts else [] + for a, b in zip(pts, pts[1:]): + dt = b['t'] - a['t'] + if dt <= 0 or (a.get('acc') or 0) > max_acc or (b.get('acc') or 0) > max_acc: continue # poor fixes + d = hav(a['lat'], a['lon'], b['lat'], b['lon']); dist += d + if 0.3 < d / dt < 70 and dt < 300: mov += dt; speeds.append(d / dt) + eles.append(b.get('ele')) + speeds.sort() + return dist, mov, ascent(eles, hysteresis), speeds[int(len(speeds) * .9)] if speeds else 0 diff --git a/src/mygarmin/formats/gpx.py b/src/mygarmin/formats/gpx.py new file mode 100644 index 0000000..1c16007 --- /dev/null +++ b/src/mygarmin/formats/gpx.py @@ -0,0 +1,34 @@ +"""GPX 1.0/1.1 tracks: reading (any creator) and writing (with heart rate as Garmin TrackPointExtension).""" +import re +from datetime import datetime, timezone +from xml.sax.saxutils import escape + +def read(data): + """-> {'name', 'type', 'points': [{lat, lon, ele, t (datetime UTC or None), hr}]}; tolerant regex parse, any namespace.""" + txt = data.decode('utf-8', 'ignore') if isinstance(data, bytes) else data + trk = re.search(r'(.*)', txt, re.S) + body = trk.group(1) if trk else txt + name = re.search(r'([^<]*)', body); typ = re.search(r'([^<]*)', body) + pts = [] + for attrs, blk in re.findall(r']*?)(?:/>|>(.*?))', body, re.S): + la, lo = re.search(r'lat="([-\d.]+)"', attrs), re.search(r'lon="([-\d.]+)"', attrs) + if not (la and lo): continue + e = re.search(r'([-\d.]+)', blk); t = re.search(r'', blk); hr = re.search(r':hr>(\d+)<', blk) + pts.append({'lat': float(la.group(1)), 'lon': float(lo.group(1)), 'ele': float(e.group(1)) if e else None, + 't': datetime.strptime(t.group(1)[:19], '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) if t else None, + 'hr': int(hr.group(1)) if hr else None}) + return {'name': name.group(1).strip() if name else '', 'type': typ.group(1).strip() if typ else '', 'points': pts} + +def write(points, name, sport, creator='myGarmin'): + """points: dicts with lat, lon and optional ele, t (datetime), hr.""" + out = ['', + f'', + f'{escape(name)}', f'{escape(name)}{escape(sport)}'] + for p in points: + x = f'' + if p.get('ele') is not None: x += f'{p["ele"]:.1f}' + if p.get('t'): x += f'' + if p.get('hr'): x += f'{p["hr"]}' + out.append(x + '') + return '\n'.join(out + ['', '']) diff --git a/src/mygarmin/formats/tcx.py b/src/mygarmin/formats/tcx.py new file mode 100644 index 0000000..d114880 --- /dev/null +++ b/src/mygarmin/formats/tcx.py @@ -0,0 +1,45 @@ +"""Garmin Training Center (TCX) files from older watches.""" +from datetime import datetime +import xml.etree.ElementTree as ET +from .geo import ascent + +NS = {'t': 'http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2'} +NAMED = [('mtnbiking', 'cycling', 'mountain'), ('biking', 'cycling', 'generic'), ('cycling', 'cycling', 'generic'), + ('hiking', 'hiking', 'generic'), ('walking', 'walking', 'generic'), ('running', 'running', 'generic'), + ('rowing', 'rowing', 'generic'), ('swim', 'swimming', 'generic')] + +def sport_of(name, attr): + n = name.lower() # old Garmin software put the sport in the file name; the Sport attribute only knows Running/Biking/Other + for key, sp, sub in NAMED: + if key in n: return sp, sub + return {'Running': ('running', 'generic'), 'Biking': ('cycling', 'generic')}.get(attr, ('generic', 'generic')) + +def read(data, name=''): + """-> {'id', 'summary', 'points'} for the first activity in the file, or None.""" + act = ET.fromstring(data).find('t:Activities/t:Activity', NS) + if act is None: return None + sid = act.findtext('t:Id', namespaces=NS) + if not sid: return None + st = datetime.fromisoformat(sid.replace('Z', '+00:00')) + secs = dist = kcal = hrw = hrt = 0.0; hrmax = None; pts = []; alts = [] + for lap in act.findall('t:Lap', NS): + t = float(lap.findtext('t:TotalTimeSeconds', '0', NS)); secs += t + dist += float(lap.findtext('t:DistanceMeters', '0', NS)); kcal += float(lap.findtext('t:Calories', '0', NS)) + a = lap.findtext('t:AverageHeartRateBpm/t:Value', None, NS) + if a: hrw += float(a) * t; hrt += t + m = lap.findtext('t:MaximumHeartRateBpm/t:Value', None, NS) + if m: hrmax = max(hrmax or 0, int(m)) + for tp in lap.iter('{%s}Trackpoint' % NS['t']): + la = tp.findtext('t:Position/t:LatitudeDegrees', None, NS); lo = tp.findtext('t:Position/t:LongitudeDegrees', None, NS) + al = tp.findtext('t:AltitudeMeters', None, NS); tm = tp.findtext('t:Time', None, NS) + if al: alts.append(float(al)) + if la and lo: + hr = tp.findtext('t:HeartRateBpm/t:Value', None, NS) + pts.append({'lat': float(la), 'lon': float(lo), 'ele': float(al) if al else None, + 't': datetime.fromisoformat(tm.replace('Z', '+00:00')) if tm else None, 'hr': int(hr) if hr else None}) + sp, sub = sport_of(name, act.get('Sport')) + asc = ascent(alts, 3) + return {'id': sid, 'points': pts, 'summary': { + 'start': st, 'sport': sp, 'sub_sport': sub, 'dist_m': dist, 'elapsed_s': secs, 'moving_s': secs, + 'ascent_m': round(asc) if asc is not None else None, 'avg_hr': round(hrw / hrt) if hrt else None, 'max_hr': hrmax, + 'kcal': round(kcal) or None, 'te_aerobic': None, 'vo2max': None}} diff --git a/src/mygarmin/library.py b/src/mygarmin/library.py new file mode 100644 index 0000000..9ecde32 --- /dev/null +++ b/src/mygarmin/library.py @@ -0,0 +1,97 @@ +"""A user's library folder: settings, the SQLite database and the untouched original files.""" +import hashlib, json, os, sqlite3 +from datetime import datetime, timezone + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS files(md5 TEXT PRIMARY KEY, path TEXT, source TEXT, kind TEXT, imported TEXT); +CREATE TABLE IF NOT EXISTS activities( + id INTEGER PRIMARY KEY, source TEXT NOT NULL, file TEXT UNIQUE NOT NULL, + start_utc TEXT NOT NULL, utc_offset_min INTEGER, start_local TEXT, + elapsed_s REAL, moving_s REAL, sport TEXT, sub_sport TEXT, name TEXT, + dist_m REAL, ascent_m REAL, avg_hr INTEGER, max_hr INTEGER, kcal INTEGER, te_aerobic REAL, vo2max REAL, + npts INTEGER, lat REAL, lon REAL, + flag TEXT, -- why it is left out of the dashboard: transport, too short, suspect GPS, ... (NULL = fine) + dup_of INTEGER -- the activity of a higher-priority source that recorded the same outing +); +CREATE INDEX IF NOT EXISTS act_start ON activities(start_utc); +CREATE TABLE IF NOT EXISTS tracks(activity_id INTEGER PRIMARY KEY, pts TEXT); -- simplified [[lat, lon], ...] for maps +CREATE TABLE IF NOT EXISTS health_days(date TEXT PRIMARY KEY, data TEXT); -- {field: value} per calendar day +CREATE TABLE IF NOT EXISTS health_series(kind TEXT, date TEXT, key TEXT, data TEXT, PRIMARY KEY(kind, date, key)); +CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT); +""" +ACT_FIELDS = ['source', 'file', 'start_utc', 'utc_offset_min', 'start_local', 'elapsed_s', 'moving_s', 'sport', 'sub_sport', 'name', + 'dist_m', 'ascent_m', 'avg_hr', 'max_hr', 'kcal', 'te_aerobic', 'vo2max', 'npts', 'lat', 'lon', 'flag'] +DEFAULTS = {'name': '', 'birth_year': None, 'home_tz': 'UTC', 'units': 'metric'} + + +class Library: + def __init__(self, root): + self.root = os.path.abspath(root) + p = os.path.join(self.root, 'settings.json') + if not os.path.exists(p): raise FileNotFoundError(f'{self.root} is not a myGarmin library (no settings.json); run "mygarmin init" first') + self.settings = {**DEFAULTS, **json.load(open(p, encoding='utf-8'))} + self.db = sqlite3.connect(os.path.join(self.root, 'myGarmin.db')) + self.db.row_factory = sqlite3.Row + self.db.executescript(SCHEMA) + + @classmethod + def create(cls, root, **settings): + os.makedirs(root, exist_ok=True) + for d in ('inbox', 'originals', 'exports'): os.makedirs(os.path.join(root, d), exist_ok=True) + p = os.path.join(root, 'settings.json') + old = json.load(open(p, encoding='utf-8')) if os.path.exists(p) else {} + json.dump({**DEFAULTS, **old, **{k: v for k, v in settings.items() if v is not None}}, open(p, 'w', encoding='utf-8'), indent=1) + return cls(root) + + def path(self, *rel): return os.path.join(self.root, *rel) + + # ---- original files ---- + def known(self, data): return self.db.execute('SELECT path FROM files WHERE md5=?', (hashlib.md5(data).hexdigest(),)).fetchone() + + def store(self, data, source, name, kind='activity'): + """Keep an original file under originals//; returns (relative path, True if new) — same content is stored once.""" + h = hashlib.md5(data).hexdigest() + row = self.db.execute('SELECT path FROM files WHERE md5=?', (h,)).fetchone() + if row: return row['path'], False + rel = os.path.join('originals', source, name); stem, ext = os.path.splitext(rel); i = 0 + while os.path.exists(self.path(rel)): i += 1; rel = f'{stem}_{i}{ext}' # same name, different content: keep both + os.makedirs(os.path.dirname(self.path(rel)), exist_ok=True) + open(self.path(rel), 'wb').write(data) + rel = rel.replace(os.sep, '/') + self.db.execute('INSERT INTO files VALUES (?,?,?,?,?)', (h, rel, source, kind, datetime.now(timezone.utc).isoformat(timespec='seconds'))) + return rel, True + + # ---- activities ---- + def add_activity(self, a, track=None): + """Insert or replace the activity read from a.file; track = [[lat, lon], ...] (simplified here to ~400 points).""" + vals = [a.get(k) for k in ACT_FIELDS] + cur = self.db.execute(f"INSERT INTO activities({','.join(ACT_FIELDS)}) VALUES ({','.join('?' * len(ACT_FIELDS))}) " + f"ON CONFLICT(file) DO UPDATE SET {','.join(f'{k}=excluded.{k}' for k in ACT_FIELDS[2:])} RETURNING id", vals) + aid = cur.fetchone()[0] + if track and len(track) > 1: + step = max(1, len(track) // 400) + pts = [[round(p[0], 6), round(p[1], 6)] for p in track[::step] + track[-1:]] + self.db.execute('INSERT OR REPLACE INTO tracks VALUES (?,?)', (aid, json.dumps(pts, separators=(',', ':')))) + return aid + + def activities(self, where='1', *args): + return [dict(r) for r in self.db.execute(f'SELECT * FROM activities WHERE {where} ORDER BY start_utc', args)] + + # ---- health ---- + def upsert_day(self, date, fields): + """Merge fields (None values ignored) into the day's record; newer values win.""" + row = self.db.execute('SELECT data FROM health_days WHERE date=?', (date,)).fetchone() + d = json.loads(row['data']) if row else {} + d.update({k: v for k, v in fields.items() if v is not None}) + self.db.execute('INSERT OR REPLACE INTO health_days VALUES (?,?)', (date, json.dumps(d, separators=(',', ':')))) + + def days(self): + return [{'d': r['date'], **json.loads(r['data'])} for r in self.db.execute('SELECT * FROM health_days ORDER BY date')] + + def add_series(self, kind, date, key, data): + self.db.execute('INSERT OR REPLACE INTO health_series VALUES (?,?,?,?)', (kind, date, str(key), json.dumps(data, separators=(',', ':')))) + + def series(self, kind): + return [{'d': r['date'], **json.loads(r['data'])} for r in self.db.execute('SELECT * FROM health_series WHERE kind=? ORDER BY date, key', (kind,))] + + def commit(self): self.db.commit() diff --git a/src/mygarmin/report/__init__.py b/src/mygarmin/report/__init__.py new file mode 100644 index 0000000..c4b8bed --- /dev/null +++ b/src/mygarmin/report/__init__.py @@ -0,0 +1,59 @@ +"""Build the self-contained dashboard (dashboard.html) and an all_activities.csv from the library.""" +import csv, json, os +from datetime import datetime +from .. import __version__ + +SHOWN = "dup_of IS NULL AND (flag IS NULL OR flag IN ('suspect GPS', 'summary only'))" +CSV_COLS = ['start_local', 'start_utc', 'source', 'sport', 'sub_sport', 'name', 'dist_km', 'moving_min', 'elapsed_min', 'ascent_m', + 'avg_hr', 'max_hr', 'kcal', 'te_aerobic', 'vo2max', 'lat', 'lon', 'flag', 'file'] + +def races(lib): + """races.csv in the library: date, event, time (h:mm:ss or mm:ss); optional km (default 5), age_grade, position, pb.""" + p = lib.path('races.csv') + if not os.path.exists(p): return [] + out = [] + for r in csv.DictReader(open(p, encoding='utf-8')): + t = [int(x) for x in r['time'].split(':')] + sec = t[0] * 3600 + t[1] * 60 + t[2] if len(t) == 3 else t[0] * 60 + t[1] + ag = (r.get('age_grade') or '').rstrip('%') + out.append({'date': r['date'], 'event': r['event'], 'time': r['time'], 'sec': sec, 'km': float(r.get('km') or 5), + 'ag': float(ag) if ag else None, 'pos': int(r['position']) if (r.get('position') or '').isdigit() else None, + 'pb': (r.get('pb') or '').strip().upper() in ('PB', 'YES', 'Y', '1', 'TRUE')}) + return sorted(out, key=lambda r: r['date']) + +def data(lib): + acts, tracks = [], {} + for a in lib.activities(SHOWN): + acts.append({'file': a['file'], 'src': a['source'], 'start_utc': a['start_utc'], 'start_local': a['start_local'][:16], + 'sport': a['sport'], 'sub_sport': 'suspect GPS' if a['flag'] == 'suspect GPS' else a['sub_sport'], 'name': a['name'], + 'dist_km': round((a['dist_m'] or 0) / 1000, 2), 'moving_min': round((a['moving_s'] or 0) / 60, 1), + 'ascent_m': round(a['ascent_m']) if a['ascent_m'] is not None else None, 'avg_hr': a['avg_hr'], 'max_hr': a['max_hr'], + 'kcal': a['kcal'], 'te_aerobic': a['te_aerobic'], 'vo2max': a['vo2max'], 'npts': a['npts']}) + t = lib.db.execute('SELECT pts FROM tracks WHERE activity_id=?', (a['id'],)).fetchone() + if t: tracks[a['file']] = json.loads(t[0]) + days = lib.days() + health = {'days': days, 'vo2': lib.series('vo2'), 'fage': lib.series('fage'), 'bp': lib.series('bp'), 'lthr': lib.series('lthr')} if days else None + s = lib.settings + return {'profile': {'name': s.get('name'), 'birth_year': s.get('birth_year'), 'sex': s.get('sex')}, + 'acts': acts, 'tracks': tracks, 'health': health, 'races': races(lib), + 'built': datetime.now().strftime('%Y-%m-%d %H:%M'), 'version': __version__} + +def build(lib, out=None, log=print): + d = data(lib) + if not d['acts']: raise SystemExit('No activities in the library yet: import some first.') + tpl = open(os.path.join(os.path.dirname(__file__), 'dashboard.html'), encoding='utf-8').read() + title = (f"{d['profile']['name']}'s" if d['profile']['name'] else 'My') + ' activity logbook' + js = json.dumps(d, separators=(',', ':'), ensure_ascii=False).replace('' inside the data + html = tpl.replace('__TITLE__', title).replace('__DATA__', js) + out = out or lib.path('dashboard.html') + open(out, 'w', encoding='utf-8').write(html) + with open(os.path.join(os.path.dirname(out), 'all_activities.csv'), 'w', newline='', encoding='utf-8') as f: + w = csv.writer(f); w.writerow(CSV_COLS) + for a in lib.activities(): + a['dist_km'] = round((a['dist_m'] or 0) / 1000, 2); a['moving_min'] = round((a['moving_s'] or 0) / 60, 1) + a['elapsed_min'] = round((a['elapsed_s'] or 0) / 60, 1) + a['flag'] = a['flag'] or ('duplicate' if a['dup_of'] else '') + w.writerow(['' if a.get(c) is None else a[c] for c in CSV_COLS]) + log(f"{len(d['acts'])} activities, {len(d['tracks'])} tracks, {len(d['health']['days']) if d['health'] else 0} health days, " + f"{len(d['races'])} races -> {out}") + return out diff --git a/src/mygarmin/sources/__init__.py b/src/mygarmin/sources/__init__.py new file mode 100644 index 0000000..cf50c47 --- /dev/null +++ b/src/mygarmin/sources/__init__.py @@ -0,0 +1,60 @@ +"""Import anything: a file, a folder or a zip. Account exports (Strava, Garmin Connect) are recognised and handled as a +whole; every other file goes to the importer for its type. Importing the same content twice does nothing.""" +import collections, gzip, io, os, posixpath, zipfile + +class Item: + """A file found on disk or inside a zip; `name` is its path relative to what was imported, with / separators.""" + def __init__(self, name, read): self.name, self._read = name, read + def read(self): + b = self._read() + return gzip.decompress(b) if self.name.lower().endswith('.gz') else b + @property + def base(self): # file name without a .gz suffix + n = posixpath.basename(self.name) + return n[:-3] if n.lower().endswith('.gz') else n + +def _zip_items(zf, prefix, depth): + for zi in zf.infolist(): + if zi.is_dir(): continue + name = prefix + zi.filename + if zi.filename.lower().endswith('.zip') and depth < 2: # Garmin exports nest their uploaded files in zips + yield from _zip_items(zipfile.ZipFile(io.BytesIO(zf.read(zi))), name + '/', depth + 1) + else: + yield Item(name, lambda zf=zf, zi=zi: zf.read(zi)) + +def walk(path): + if os.path.isdir(path): + for dp, _, fs in os.walk(path): + for f in sorted(fs): + p = os.path.join(dp, f); rel = os.path.relpath(p, path).replace(os.sep, '/') + if f.lower().endswith('.zip'): yield from _zip_items(zipfile.ZipFile(p), rel + '/', 1) + else: yield Item(rel, lambda p=p: open(p, 'rb').read()) + elif path.lower().endswith('.zip'): + yield from _zip_items(zipfile.ZipFile(path), '', 0) + else: + yield Item(os.path.basename(path), lambda: open(path, 'rb').read()) + +def _root_of(name, marker): + i = name.find(marker) + return name[:i] if i >= 0 else None + +def import_path(lib, path, log=print): + """Import everything under `path` into the library; returns a Counter of what happened.""" + from . import files, strava, garmin_export + items = list(walk(path)) + stats = collections.Counter() + # account exports first: their files need the export's own index (Strava) or are mostly health data (Garmin) + st_roots = {posixpath.dirname(i.name) for i in items if posixpath.basename(i.name) == 'activities.csv'} + st_roots = {r for r in st_roots if strava.is_export([i for i in items if i.name == posixpath.join(r, 'activities.csv')][0])} + gx_roots = {_root_of(i.name, 'DI_CONNECT/') for i in items if 'DI_CONNECT/' in i.name} + used = set() + for r in sorted(st_roots): + part = [i for i in items if i.name.startswith(r + '/' if r else '')] + stats.update(strava.import_export(lib, part, r, log)); used |= {i.name for i in part} + for r in sorted(gx_roots): + part = [i for i in items if i.name.startswith(r + 'DI_CONNECT/')] + stats.update(garmin_export.import_export(lib, part, log)); used |= {i.name for i in items if i.name.startswith(r)} + for i in items: + if i.name not in used: stats[files.import_file(lib, i)] += 1 + lib.commit() + return stats diff --git a/src/mygarmin/sources/files.py b/src/mygarmin/sources/files.py new file mode 100644 index 0000000..0b7b4e4 --- /dev/null +++ b/src/mygarmin/sources/files.py @@ -0,0 +1,123 @@ +"""Single files: FIT (watch / Connect), TCX (older Garmin), AlpineQuest .trk and GPX. Each returns a short status for the stats.""" +import struct +from datetime import datetime, timezone +from .. import timeutil +from ..formats import aqtrk, fit, geo, gpx, tcx + +SPORT_TAG = {'walk': 'walking', 'hike': 'hiking', 'run': 'running', 'bicycle': 'cycling'} # AlpineQuest activity tags +TRANSPORT = {'drive', 'plane', 'train', 'boat', 'autobus'} + +def activity(lib, source, file, summary, points, offset=None, name=None, flag=None): + """Store one activity from a reader's summary + points; local time from the file, else GPS position, else home zone.""" + p0 = points[0] if points else {} + off = timeutil.offset_min(summary['start'], p0.get('lat'), p0.get('lon'), lib.settings['home_tz'], offset) + a = {'source': source, 'file': file, **timeutil.fields(summary['start'], off), 'name': name, 'flag': flag, + 'npts': len(points), 'lat': p0.get('lat'), 'lon': p0.get('lon'), + **{k: summary.get(k) for k in ('elapsed_s', 'moving_s', 'sport', 'sub_sport', 'dist_m', 'ascent_m', 'avg_hr', 'max_hr', + 'kcal', 'te_aerobic', 'vo2max')}} + return lib.add_activity(a, [[p['lat'], p['lon']] for p in points]) + +def fit_type_quick(data): + """file_id.type straight from the first data message (fast, for sorting thousands of files); falls back to fitparse.""" + try: + hs = data[0]; i = hs; local = {} + while i < len(data) - 2: + h = data[i]; i += 1 + if h & 0x80: return fit.file_type(data) # compressed timestamp header: unusual this early + if h & 0x40: # definition message + arch = data[i + 1]; gnum = struct.unpack('H', data[i + 2:i + 4])[0]; n = data[i + 4] + flds = [tuple(data[i + 5 + 3 * k:i + 8 + 3 * k]) for k in range(n)]; i += 5 + 3 * n + if h & 0x20: nd = data[i]; i += 1 + 3 * nd + local[h & 0x0F] = (gnum, flds) + else: + gnum, flds = local[h & 0x0F] + if gnum == 0: + off = 0 + for num, size, _ in flds: + if num == 0: return {4: 'activity', 6: 'course', 15: 'monitoring_a', 20: 'activity_summary', 32: 'monitoring_b', + 28: 'monitoring_daily', 10: 'totals'}.get(data[i + off], str(data[i + off])) + off += size + return fit.file_type(data) + except Exception: + pass + return fit.file_type(data) + +def import_fit(lib, data, name_hint=''): + if lib.known(data): return 'already imported' + t = fit_type_quick(data) + if t in fit.HEALTH_TYPES: lib.store(data, 'garmin_health', name_hint or 'health.fit', 'health'); return 'health FIT stored' + if t in fit.COURSE_TYPES: lib.store(data, 'garmin_courses', name_hint or 'course.fit', 'course'); return 'course stored' + if t not in fit.ACTIVITY_TYPES: return 'FIT ignored (settings/other)' + r = fit.read(data) + if not r['summary']: return 'FIT without session ignored' + s = r['summary'] + off = r['offset_min'] if r['offset_min'] is not None else timeutil.offset_min(s['start'], *( + (r['points'][0]['lat'], r['points'][0]['lon']) if r['points'] else (None, None)), lib.settings['home_tz']) + local = timeutil.fields(s['start'], off)['start_local'].replace(' ', '-').replace(':', '-') + rel, _ = lib.store(data, 'garmin_fit', local + '.fit') # named like the watch names them: local start time + activity(lib, 'fit', rel, s, r['points'], off, flag='summary only' if r['type'] == 'activity_summary' else None) + return 'FIT activity' + +def import_tcx(lib, data, name): + if lib.known(data): return 'already imported' + r = tcx.read(data, name) + if not r: return 'TCX without activity' + st = timeutil.fields(r['summary']['start'], 0)['start_utc'] + if lib.db.execute("SELECT 1 FROM activities WHERE source='tcx' AND start_utc=?", (st,)).fetchone(): + lib.store(data, 'tcx', name); return 'TCX copy of an imported activity' # older software saved many copies + rel, _ = lib.store(data, 'tcx', name) + activity(lib, 'tcx', rel, r['summary'], r['points']) + return 'TCX activity' + +def from_points(pts, sport=None): + """Summary for a track without one (AlpineQuest, GPX). pts need t as epoch seconds. Returns (summary, flag).""" + dist, mov, asc, p90 = geo.stats(pts) + t0, t1 = pts[0]['t'], pts[-1]['t'] + flag = None + if dist < 300 or mov < 300: flag = 'too short' + v = dist / mov * 3.6 if mov else 0; p90 *= 3.6 + sub = 'tagged' + if not sport: + sub = 'guessed by speed' + if v > 28 or p90 > 45: sport, flag = 'transport', flag or 'transport' + elif v >= 12: sport = 'cycling' + elif v >= 7.5: sport = 'running' + else: sport = 'hiking' if (asc or 0) >= 200 or mov > 3 * 3600 else 'walking' + return {'start': datetime.fromtimestamp(t0, timezone.utc), 'sport': sport, 'sub_sport': sub, 'dist_m': dist, + 'elapsed_s': t1 - t0, 'moving_s': mov, 'ascent_m': round(asc) if asc is not None else None}, flag + +def import_trk(lib, data, name): + if lib.known(data): return 'already imported' + t = aqtrk.parse_any(data) + pts = [dict(p, t=p['t'] / 1000) for s in t['segments'] for p in s if p.get('t')] + rel, _ = lib.store(data, 'alpinequest', name) + if len(pts) < 10: return 'AlpineQuest track without timestamps' + st = datetime.fromtimestamp(pts[0]['t'], timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') + if lib.db.execute("SELECT 1 FROM activities WHERE source='alpinequest' AND start_utc=?", (st,)).fetchone(): + return 'AlpineQuest copy of an imported track' + tag = t['user'].get('activity') + summary, flag = from_points(pts, SPORT_TAG.get(tag)) + if tag in TRANSPORT or 'flight' in name.lower(): summary['sport'], flag = 'transport', 'transport' + activity(lib, 'alpinequest', rel, summary, [dict(p, t=None) for p in pts], name=t['user'].get('name') or None, flag=flag) + return 'AlpineQuest track' + +GPX_SPORT = {'running': 'running', 'run': 'running', 'cycling': 'cycling', 'biking': 'cycling', 'ride': 'cycling', + 'hiking': 'hiking', 'hike': 'hiking', 'walking': 'walking', 'walk': 'walking'} + +def import_gpx(lib, data, name): + if lib.known(data): return 'already imported' + g = gpx.read(data) + pts = [dict(p, t=p['t'].timestamp()) for p in g['points'] if p['t']] + if len(pts) < 10: lib.store(data, 'gpx', name, 'other'); return 'GPX without a timed track (route/waypoints) stored' + rel, _ = lib.store(data, 'gpx', name) + summary, flag = from_points(pts, GPX_SPORT.get(g['type'].lower())) + activity(lib, 'gpx', rel, summary, pts, name=g['name'] or None, flag=flag) + return 'GPX track' + +def import_file(lib, item): + n = item.base.lower() + if n.endswith('.fit'): return import_fit(lib, item.read(), item.base) + if n.endswith('.tcx'): return import_tcx(lib, item.read(), item.base) + if n.endswith('.trk'): return import_trk(lib, item.read(), item.base) + if n.endswith('.gpx'): return import_gpx(lib, item.read(), item.base) + return 'not an activity file' diff --git a/src/mygarmin/sources/garmin_api.py b/src/mygarmin/sources/garmin_api.py new file mode 100644 index 0000000..4e16470 --- /dev/null +++ b/src/mygarmin/sources/garmin_api.py @@ -0,0 +1,108 @@ +"""Garmin Connect through the unofficial python-garminconnect library (pip install "mygarmin[api]"). Read-only. +Garmin offers no personal API; this logs in like the Connect app and may break when Garmin changes its login. +The token is kept on this PC (never in the library folder, which may be on a shared drive), one per library.""" +import hashlib, io, os, re, time, zipfile +from datetime import date, datetime, timedelta, timezone +from . import files +from .garmin_export import bp_entry, clock_hour + +def token_dir(lib): + base = os.environ.get('LOCALAPPDATA') or os.path.expanduser('~/.local/share') + return os.path.join(base, 'myGarmin', 'tokens', hashlib.md5(lib.root.lower().encode()).hexdigest()[:12]) + +def _client(): + try: + from garminconnect import Garmin + except ImportError: + raise SystemExit('The Garmin API needs an extra package: pip install "mygarmin[api]"') + return Garmin + +def login(lib, email, password, prompt_mfa): + Garmin = _client() + api = Garmin(email, password, prompt_mfa=prompt_mfa) + api.login(token_dir(lib)); api.client.dump(token_dir(lib)) + return api.get_full_name() + +def connect(lib): + Garmin = _client() + if not os.path.exists(token_dir(lib)): raise SystemExit('Not logged in to Garmin Connect yet: run "mygarmin login " first.') + api = Garmin() + try: api.login(token_dir(lib)) + except Exception as e: raise SystemExit(f'Garmin login failed ({type(e).__name__}: {e}). Run "mygarmin login " again.') + return api + +def sync(lib, overlap=3, log=print): + """New activities (original FIT) and daily health since the last data in the library, minus `overlap` days.""" + api = connect(lib) + def call(f, *a): + time.sleep(0.3) # be gentle with Garmin's servers + try: return f(*a) + except Exception as e: log(f' warning: {f.__name__}{a}: {type(e).__name__} {str(e)[:100]}'); return None + stats = {} + last = lib.db.execute("SELECT max(start_utc) FROM activities WHERE source='fit'").fetchone()[0] + since = (datetime.strptime(last[:10], '%Y-%m-%d').date() if last else date.today() - timedelta(days=30)) - timedelta(days=overlap) + for a in call(api.get_activities_by_date, since.isoformat(), date.today().isoformat()) or []: + blob = call(api.download_activity, str(a['activityId']), api.ActivityDownloadFormat.ORIGINAL) + if not blob: continue + z = zipfile.ZipFile(io.BytesIO(blob)) + fits = [n for n in z.namelist() if n.lower().endswith('.fit')] + if not fits: s = 'activity without a FIT (manual or imported)' + for n in fits: s = files.import_fit(lib, z.read(n)); stats[s] = stats.get(s, 0) + 1 + if not fits: stats[s] = stats.get(s, 0) + 1 + log(f" activities since {since}: {stats}") + + days = lib.days() + start = (datetime.strptime(days[-1]['d'], '%Y-%m-%d').date() if days else date.today() - timedelta(days=30)) - timedelta(days=overlap) + span = [(start + timedelta(n)).isoformat() for n in range((date.today() - start).days + 1)] + tz = lib.settings['home_tz']; r1 = lambda x: None if x is None else round(x, 1) + races = {p['calendarDate']: p for p in call(api.get_race_predictions, span[0], span[-1], 'daily') or []} + for d in span: + r = {} + s = call(api.get_user_summary, d) or {} + r['rhr'], r['steps'] = s.get('lastSevenDaysAvgRestingHeartRate'), s.get('totalSteps') # 7-day average, as in the export + r['im'] = (s.get('moderateIntensityMinutes') or 0) + 2 * (s.get('vigorousIntensityMinutes') or 0) + if (s.get('averageStressLevel') or -1) >= 0: r['stress'] = s['averageStressLevel'] + r['bbHi'], r['bbLo'] = s.get('bodyBatteryHighestValue'), s.get('bodyBatteryLowestValue') + sl = (call(api.get_sleep_data, d) or {}).get('dailySleepDTO') or {} + st = [sl.get(k) or 0 for k in ('deepSleepSeconds', 'lightSleepSeconds', 'remSleepSeconds', 'awakeSleepSeconds')] + if sum(st[:3]) >= 3600 and sl.get('sleepStartTimestampGMT'): + r['deep'], r['light'], r['rem'], r['awake'] = (round(x / 3600, 2) for x in st) + r['sleep'] = round(sum(st[:3]) / 3600, 2) + g = lambda k: datetime.fromtimestamp(sl[k] / 1000, timezone.utc) + r['bed'], r['wake'] = clock_hour(g('sleepStartTimestampGMT'), tz), clock_hour(g('sleepEndTimestampGMT'), tz) + r['sscore'] = ((sl.get('sleepScores') or {}).get('overall') or {}).get('value') + r['spo2'], r['resp'], r['sstress'] = r1(sl.get('averageSpO2Value')), r1(sl.get('averageRespirationValue')), r1(sl.get('avgSleepStress')) + r['hrv'] = ((call(api.get_hrv_data, d) or {}).get('hrvSummary') or {}).get('lastNightAvg') + tr = call(api.get_training_readiness, d) or [] + tr = sorted(tr if isinstance(tr, list) else [tr], key=lambda t: (t.get('inputContext') != 'AFTER_WAKEUP_RESET', t.get('timestamp', ''))) + if tr: + r['ready'] = tr[0].get('score') + if 10 < (tr[0].get('hrvWeeklyAverage') or 0) < 200: r['hrvW'] = tr[0]['hrvWeeklyAverage'] + ts = call(api.get_training_status, d) or {} + for x in ((ts.get('mostRecentTrainingStatus') or {}).get('latestTrainingStatusData') or {}).values(): + if x.get('calendarDate') == d and x.get('primaryTrainingDevice', True): + ac = x.get('acuteTrainingLoadDTO') or {} + r['acute'], r['chronic'] = ac.get('dailyTrainingLoadAcute'), ac.get('dailyTrainingLoadChronic') + if x.get('trainingStatusFeedbackPhrase'): r['status'] = re.sub(r'_\d+$', '', x['trainingStatusFeedbackPhrase']) + for sport, v in (ts.get('mostRecentVO2Max') or {}).items(): + if sport in ('generic', 'cycling') and isinstance(v, dict) and v.get('vo2MaxValue'): + sp = 'running' if sport == 'generic' else 'cycling' + lib.add_series('vo2', v['calendarDate'], sp, {'sport': sp, 'v': v['vo2MaxValue']}) + p = races.get(d) or {} + r['p5k'], r['p10k'], r['pHalf'] = p.get('time5K'), p.get('time10K'), p.get('timeHalfMarathon') + e = call(api.get_endurance_score, d) or {} + if e.get('calendarDate') == d: r['endur'] = e.get('overallScore') + h = call(api.get_hill_score, d) or {} + if h.get('calendarDate') == d: r['hill'] = h.get('overallScore') + f = call(api.get_fitnessage_data, d) or {} + if f.get('fitnessAge'): + lib.add_series('fage', d, '', {'bio': round(f['fitnessAge'], 1), 'age': f.get('chronologicalAge'), + 'rhr': ((f.get('components') or {}).get('rhr') or {}).get('value')}) + lib.upsert_day(d, r) + lib.commit() + bp = call(api.get_blood_pressure, span[0], span[-1]) or {} + for m in (x for s in bp.get('measurementSummaries') or [] for x in s.get('measurements') or []): + lib.add_series('bp', m['measurementTimestampLocal'][:10], f"{m['systolic']}/{m['diastolic']}", bp_entry(m)) + lib.commit() + log(f' health: {len(span)} days ({span[0]} to {span[-1]})') + return stats diff --git a/src/mygarmin/sources/garmin_export.py b/src/mygarmin/sources/garmin_export.py new file mode 100644 index 0000000..3c333e7 --- /dev/null +++ b/src/mygarmin/sources/garmin_export.py @@ -0,0 +1,113 @@ +"""Garmin Connect account export (garmin.com > Account > Data Management > Export Your Data), the DI_CONNECT part: +daily health and fitness metrics from the JSON files, and activity FITs from DI-Connect-Uploaded-Files/*.zip. +Every JSON file ends in NUL padding.""" +import json, posixpath, re +from datetime import datetime, timedelta, timezone +from zoneinfo import ZoneInfo +from . import files + +def _load(items, pattern): + """All records from the JSON files whose path matches `pattern` (regex), flattened.""" + out = [] + for i in sorted((i for i in items if re.search(pattern, i.name)), key=lambda i: i.name): + s = i.read().decode('utf-8', 'replace').rstrip('\x00 \n\r\t') + if not s: continue + d = json.JSONDecoder().raw_decode(s)[0] + while isinstance(d, list) and len(d) == 1 and isinstance(d[0], (list, dict)) and not ( + isinstance(d[0], dict) and ('calendarDate' in d[0] or 'metaData' in d[0])): + d = d[0] if isinstance(d[0], list) else list(d[0].values())[0] + out += d if isinstance(d, list) else [d] + return out + +def day(v): # calendarDate comes as 'YYYY-MM-DD', epoch ms or [y, m, d, ...] + if isinstance(v, (int, float)): return datetime.fromtimestamp(v / 1000, timezone.utc).strftime('%Y-%m-%d') + if isinstance(v, list): return '%04d-%02d-%02d' % tuple(v[:3]) + return v[:10] + +def clock_hour(dt_utc, tz): + """Local clock time as hours; evening times (after 15:00) negative, so bedtimes around midnight average sensibly.""" + t = dt_utc.astimezone(ZoneInfo(tz)); h = t.hour + t.minute / 60 + return round(h - 24 if h > 15 else h, 2) + +r1 = lambda x, n=1: None if x is None else round(x, n) + +def health(lib, items): + """Daily records + series; returns the number of days written.""" + D = {} + row = lambda d: D.setdefault(d, {}) + tz = lib.settings['home_tz'] + for u in _load(items, r'DI-Connect-Aggregator/UDSFile_.*\.json$'): + r = row(day(u['calendarDate'])) + r['rhr'] = u.get('restingHeartRate') # Garmin's 7-day average resting HR (the day's own value is currentDayRestingHeartRate) + r['steps'] = u.get('totalSteps') + r['im'] = (u.get('moderateIntensityMinutes') or 0) + 2 * (u.get('vigorousIntensityMinutes') or 0) + tot = [a for a in (u.get('allDayStress') or {}).get('aggregatorList', []) if a.get('type') == 'TOTAL'] + if tot and tot[0].get('averageStressLevel', -1) >= 0: r['stress'] = tot[0]['averageStressLevel'] + bb = {s['bodyBatteryStatType']: s['statsValue'] for s in (u.get('bodyBattery') or {}).get('bodyBatteryStatList', [])} + r['bbHi'], r['bbLo'] = bb.get('HIGHEST'), bb.get('LOWEST') + for s in _load(items, r'DI-Connect-Wellness/.*sleepData\.json$'): + if 'sleepStartTimestampGMT' not in s: continue + st = [s.get(k) or 0 for k in ('deepSleepSeconds', 'lightSleepSeconds', 'remSleepSeconds', 'awakeSleepSeconds')] + if sum(st[:3]) < 3600: continue # naps and broken records + r = row(day(s['calendarDate'])) + r['deep'], r['light'], r['rem'], r['awake'] = (round(x / 3600, 2) for x in st) + r['sleep'] = round(sum(st[:3]) / 3600, 2) + g = lambda k: datetime.strptime(s[k][:19], '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) + r['bed'], r['wake'] = clock_hour(g('sleepStartTimestampGMT'), tz), clock_hour(g('sleepEndTimestampGMT'), tz) + r['sscore'] = (s.get('sleepScores') or {}).get('overallScore') + r['spo2'] = r1((s.get('spo2SleepSummary') or {}).get('averageSPO2')) + r['resp'], r['sstress'] = r1(s.get('averageRespiration')), r1(s.get('avgSleepStress')) + for h in _load(items, r'DI-Connect-Wellness/.*healthStatusData\.json$'): + m = {x['type']: x.get('value') for x in h.get('metrics', [])} + if m.get('HRV'): row(day(h['calendarDate']))['hrv'] = m['HRV'] + best = {} + for t in _load(items, r'DI-Connect-Metrics/TrainingReadinessDTO_.*\.json$'): # several per day: prefer the morning one + d, rank = day(t['calendarDate']), 0 if t.get('inputContext') == 'AFTER_WAKEUP_RESET' else 1 + if d not in best or (rank, t.get('timestamp', '')) < best[d][0]: best[d] = ((rank, t.get('timestamp', '')), t) + for d, (_, t) in best.items(): + r = row(d); r['ready'] = t.get('score') + if 10 < (t.get('hrvWeeklyAverage') or 0) < 200: r['hrvW'] = t['hrvWeeklyAverage'] # occasional 511 ms glitch + for t in _load(items, r'DI-Connect-Metrics/MetricsAcuteTrainingLoad_.*\.json$'): + r = row(day(t['calendarDate'])); r['acute'], r['chronic'] = t.get('dailyTrainingLoadAcute'), t.get('dailyTrainingLoadChronic') + for t in _load(items, r'DI-Connect-Metrics/TrainingHistory_.*\.json$'): + row(day(t['calendarDate']))['status'] = t.get('trainingStatus') + for t in _load(items, r'DI-Connect-Metrics/RunRacePredictions_.*\.json$'): + r = row(day(t['calendarDate'])); r['p5k'], r['p10k'], r['pHalf'] = t.get('raceTime5K'), t.get('raceTime10K'), t.get('raceTimeHalf') + for t in _load(items, r'DI-Connect-Metrics/EnduranceScore_.*\.json$'): + row(day(t['calendarDate']))['endur'] = t.get('overallScore') + for t in _load(items, r'DI-Connect-Metrics/HillScore_.*\.json$'): + row(day(t['calendarDate']))['hill'] = t.get('overallScore') + for d, r in D.items(): lib.upsert_day(d, r) + + for m in _load(items, r'DI-Connect-Metrics/MetricsMaxMetData_.*\.json$'): + if m.get('vo2MaxValue'): + sp = m.get('sport', 'RUNNING').lower() + lib.add_series('vo2', day(m['calendarDate']), sp, {'sport': sp, 'v': m['vo2MaxValue']}) + for f in _load(items, r'DI-Connect-Wellness/.*_fitnessAgeData\.json$'): + if f.get('currentBioAge'): + lib.add_series('fage', day(f['asOfDateGmt']), '', {'bio': round(f['currentBioAge'], 1), 'age': f.get('chronologicalAge'), 'rhr': f.get('rhr')}) + for b in _load(items, r'DI-Connect-Wellness/BloodPressureFile_.*\.json$'): + p = b['bloodPressure'] + lib.add_series('bp', day(b['metaData']['calendarDate']), f"{p['systolic']}/{p['diastolic']}", bp_entry(p)) + for b in _load(items, r'DI-Connect-Wellness/.*_userBioMetrics\.json$'): + if b.get('lactateThresholdHearRate'): lib.add_series('lthr', day(b['metaData']['calendarDate']), '', {'v': b['lactateThresholdHearRate']}) + return len(D) + +def bp_entry(p): + """Blood pressure record; a haemoglobin value written in the notes ('Hb 14.7', 'Hgb 14 1', 'Himoglobien 14.2') is picked up.""" + hb = re.search(r'(? My Account > Download or delete your account): activities.csv + activities/*.fit.gz|gpx|tcx. +Every activity is imported; copies of outings that another source also recorded are marked later by dedupe.""" +import csv, io, posixpath, re +from datetime import datetime, timezone +from ..formats import fit, gpx, tcx +from . import files + +SPORT = {'Run': 'running', 'Ride': 'cycling', 'Walk': 'walking', 'Hike': 'hiking', 'Rowing': 'rowing', 'Swim': 'swimming', + 'Virtual Ride': 'cycling', 'Virtual Run': 'running', 'Trail Run': 'running', 'Mountain Bike Ride': 'cycling', + 'Gravel Ride': 'cycling', 'E-Bike Ride': 'cycling', 'Nordic Ski': 'cross_country_skiing', 'Alpine Ski': 'alpine_skiing'} + +def _rows(data): + rows = [r for r in csv.reader(io.StringIO(data.decode('utf-8', 'replace'), newline='')) if len(r) > 10] # ends in NUL padding + return rows[0], rows[1:] + +def is_export(item): + try: return 'Activity ID' in _rows(item.read())[0] + except Exception: return False + +def points(item): + """-> [{lat, lon, ele, t (datetime)}] from the activity file in the export.""" + n, data = item.base.lower(), item.read() + if n.endswith('.fit'): return fit.read(data)['points'] + if n.endswith('.gpx'): return gpx.read(data)['points'] + if n.endswith('.tcx'): return (tcx.read(data.lstrip(), n) or {}).get('points', []) + return [] + +def import_export(lib, items, root, log=print): + by_name = {i.name[len(root) + 1:] if root else i.name: i for i in items} + hdr, rows = _rows(by_name['activities.csv'].read()) + F, L = {}, {} + for i, k in enumerate(hdr): F.setdefault(k, i); L[k] = i # some columns appear twice; either copy may hold the value + num = lambda r, k: float((r[L[k]] if k in L else '') or (r[F[k]] if k in F else '') or 0) + stats = {'Strava activity': 0, 'Strava activity already imported': 0, 'Strava activity without time': 0} + for r in rows: + aid, fn = r[F['Activity ID']], r[F['Filename']] + item = by_name.get(fn) if fn else None + file = 'strava/' + (fn or f'{aid}.manual') + if lib.db.execute('SELECT 1 FROM activities WHERE file=?', ('originals/' + file,)).fetchone(): + stats['Strava activity already imported'] += 1; continue + pts = points(item) if item else [] + if item: lib.store(item._read(), 'strava', fn) # keep the file as Strava gave it (.gz included) + t = datetime.strptime(r[F['Activity Date']], '%b %d, %Y, %I:%M:%S %p').replace(tzinfo=timezone.utc) + ts = [p['t'] for p in pts if p.get('t')] + el = num(r, 'Elapsed Time') or ((max(ts) - min(ts)).total_seconds() if ts else 0) # some uploads carry no times + mov = num(r, 'Moving Time') + if mov < 60: mov = el # sparse old tracks: Strava found almost no movement + dist, name = num(r, 'Distance'), r[F['Activity Name']] + sport = SPORT.get(r[F['Activity Type']], 'generic') + sub = 'mountain' if sport == 'cycling' and re.search(r'mtb|berg|trail|mountain', name + r[F['Activity Type']], re.I) else 'generic' + flag = None if mov >= 60 else 'no time' + vmax, km = num(r, 'Max Speed') * 3.6, dist / 1000 + if sport == 'running' and km > 1 and mov and (mov / 60 / km < 3.5 or vmax > 30 or (mov / 60 / km < 4.5 and el > 1.8 * mov)): + flag = 'suspect GPS' # too fast for a run, or a fast pace from a moving time under 55% of elapsed: GPS glitch or mislabelled ride + summary = {'start': t, 'sport': sport, 'sub_sport': sub, 'dist_m': dist, 'elapsed_s': el, 'moving_s': mov, + 'ascent_m': round(num(r, 'Elevation Gain')) or None, 'kcal': round(num(r, 'Calories')) or None, + 'avg_hr': round(num(r, 'Average Heart Rate')) or None, 'max_hr': round(num(r, 'Max Heart Rate')) or None} + files.activity(lib, 'strava', 'originals/' + file, summary, pts, name=name, flag=flag) + stats['Strava activity' if flag != 'no time' else 'Strava activity without time'] += 1 + return stats diff --git a/src/mygarmin/sources/watch.py b/src/mygarmin/sources/watch.py new file mode 100644 index 0000000..baa0c28 --- /dev/null +++ b/src/mygarmin/sources/watch.py @@ -0,0 +1,46 @@ +"""A Garmin watch connected by USB. Newer watches are MTP devices on Windows (listed under This PC, no drive letter), +so files are copied through the Windows Shell; older ones mount as a drive and can simply be imported as a folder.""" +import os, subprocess, sys, tempfile + +FOLDERS = ['Activity', 'SUMMARY', 'Courses', 'Monitor', 'Sleep', 'HRVStatus', 'Metrics', 'SlpDisr', 'HSA', 'HMD', + 'FbtBackup', 'FbtPtdBackup', 'Records', 'Totals'] + +PS = r''' +param([string]$Dest, [string]$Folders) +$want = $Folders -split ',' +$sh = New-Object -ComObject Shell.Application +$devs = @($sh.NameSpace(17).Items() | Where-Object { $_.Path -match 'vid_091e' }) # Garmin's USB vendor id: any language, never a phone +$found = $null +foreach ($d in $devs) { + foreach ($s in $d.GetFolder.Items()) { $g = $s.GetFolder.Items() | Where-Object Name -eq 'GARMIN'; if ($g) { $found = $g; Write-Output "WATCH $($d.Name)"; break } } + if ($found) { break } +} +if (-not $found) { Write-Output 'NOWATCH'; exit 2 } +function Pull($src, $dst) { + New-Item -ItemType Directory -Force $dst | Out-Null + $target = $sh.NameSpace((Resolve-Path $dst).Path) + foreach ($i in $src.GetFolder.Items()) { + if ($i.IsFolder) { Pull $i (Join-Path $dst $i.Name); continue } + $out = Join-Path $dst $i.Name + if (Test-Path $out) { continue } + $target.CopyHere($i, 4 + 16 + 1024) + $t = 0; while (-not (Test-Path $out) -and $t -lt 600) { Start-Sleep -Milliseconds 100; $t++ } + } +} +foreach ($f in $found.GetFolder.Items() | Where-Object { $_.IsFolder -and $want -contains $_.Name }) { Pull $f (Join-Path $Dest $f.Name) } +Write-Output 'DONE' +''' + +def pull(dest=None, log=print): + """Copy the watch's activity and health folders to `dest` (default: a new temp folder); returns that folder or None.""" + if sys.platform != 'win32': raise SystemExit('Reading the watch over USB is only supported on Windows; import a copied GARMIN folder instead.') + dest = dest or tempfile.mkdtemp(prefix='mygarmin_watch_') + ps1 = os.path.join(dest, '_pull.ps1'); open(ps1, 'w', encoding='utf-8-sig').write(PS) + r = subprocess.run(['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', ps1, dest, ','.join(FOLDERS)], + capture_output=True, text=True) + os.remove(ps1) + out = r.stdout.split() + if 'NOWATCH' in out: log('No Garmin watch found: connect it by USB and unlock it.'); return None + log(next((l for l in r.stdout.splitlines() if l.startswith('WATCH')), 'WATCH ?').replace('WATCH', 'Read from')) + if r.returncode: log(r.stderr[-500:]) + return dest diff --git a/src/mygarmin/timeutil.py b/src/mygarmin/timeutil.py new file mode 100644 index 0000000..f39ea2d --- /dev/null +++ b/src/mygarmin/timeutil.py @@ -0,0 +1,29 @@ +"""UTC <-> local time. The zone comes from the GPS position (offline lookup), else the library's home zone.""" +from datetime import datetime, timedelta, timezone +from zoneinfo import ZoneInfo + +_tf = None +def zone_at(lat, lon): + global _tf + if lat is None or lon is None: return None + if _tf is None: + from timezonefinder import TimezoneFinder + _tf = TimezoneFinder() + return _tf.timezone_at(lng=lon, lat=lat) + +def utc(dt): + """Naive datetimes are taken as UTC.""" + return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt.astimezone(timezone.utc) + +def offset_min(start_utc, lat=None, lon=None, home_tz='UTC', known=None): + """Minutes east of UTC at the start of an activity. known = an offset the file itself states (FIT local_timestamp).""" + if known is not None: return known + return int(utc(start_utc).astimezone(ZoneInfo(zone_at(lat, lon) or home_tz)).utcoffset() / timedelta(minutes=1)) + +def fields(start_utc, off): + """start_utc / utc_offset_min / start_local as stored in the activities table.""" + s = utc(start_utc) + return {'start_utc': s.strftime('%Y-%m-%dT%H:%M:%SZ'), 'utc_offset_min': off, + 'start_local': (s + timedelta(minutes=off)).strftime('%Y-%m-%d %H:%M:%S')} + +def parse_utc(s): return datetime.strptime(s[:19], '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py new file mode 100644 index 0000000..3b90e5a --- /dev/null +++ b/tests/test_pipeline.py @@ -0,0 +1,84 @@ +"""End-to-end test on synthetic data: import every source type, de-duplicate, build the dashboard, export tracks.""" +import csv, io, json, os, zipfile +from datetime import datetime, timedelta, timezone +import pytest +from mygarmin import dedupe, export, report, sources +from mygarmin.formats import aqtrk, gpx +from mygarmin.library import Library + +T0 = datetime(2024, 3, 2, 6, 0, tzinfo=timezone.utc) # 08:00 in Cape Town + +def track(start, minutes, lat=-33.92, lon=18.42, step_s=10, speed=2.8): + """A straight north-going track at `speed` m/s.""" + n = minutes * 60 // step_s + return [{'lat': lat + i * step_s * speed / 111_000, 'lon': lon, 'ele': 100 + (i % 50), 't': start + timedelta(seconds=i * step_s), 'hr': 140} + for i in range(n)] + +def tcx(pts, sport='Running'): + tp = ''.join(f"{p['lat']}" + f"{p['lon']}{p['ele']}" + f"{p['hr']}" for p in pts) + secs = (pts[-1]['t'] - pts[0]['t']).total_seconds() + return (f'' + f'{pts[0]["t"]:%Y-%m-%dT%H:%M:%SZ}{secs}' + f'{secs * 2.8}300{tp}' + f'').encode() + +def trk(pts, tag): + return aqtrk.to_trk([(p['lat'], p['lon'], p['ele'], int(p['t'].timestamp() * 1000)) for p in pts], 'test', tag, 'test', 'test') + +@pytest.fixture +def inbox(tmp_path): + d = tmp_path / 'inbox'; d.mkdir() + run = track(T0, 40) + (d / 'old_running.tcx').write_bytes(tcx(run)) # older Garmin watch + (d / 'phone.trk').write_bytes(trk(track(T0 + timedelta(minutes=2), 35), 'run')) # same run on the phone: duplicate + (d / 'hike.trk').write_bytes(trk(track(T0 + timedelta(days=1), 120, speed=1.2), 'hike')) + (d / 'car.trk').write_bytes(trk(track(T0 + timedelta(days=2), 30, speed=25), 'drive')) # transport: flagged + (d / 'walk.gpx').write_text(gpx.write(track(T0 + timedelta(days=3), 30, speed=1.4), 'Evening walk', 'walking')) + # Strava export: the TCX run again (duplicate) and a ride only Strava has + st = d / 'strava'; (st / 'activities').mkdir(parents=True) + ride = track(T0 + timedelta(days=4), 60, speed=7) + (st / 'activities' / '2.gpx').write_text(gpx.write(ride, 'Morning Ride', 'cycling')) + rows = [['Activity ID', 'Activity Date', 'Activity Name', 'Activity Type', 'Elapsed Time', 'Distance', 'Moving Time', 'Max Speed', + 'Elevation Gain', 'Calories', 'Filename', 'x'], + ['1', f'{T0:%b %d, %Y, %I:%M:%S %p}', 'Morning Run', 'Run', '2400', '6720', '2400', '3.5', '20', '300', '', ''], + ['2', f'{ride[0]["t"]:%b %d, %Y, %I:%M:%S %p}', 'Morning Ride', 'Ride', '3600', '25200', '3500', '9', '50', '500', 'activities/2.gpx', '']] + buf = io.StringIO(); csv.writer(buf).writerows(rows) + (st / 'activities.csv').write_text(buf.getvalue() + '\x00' * 20) # Strava pads its files with NULs + # Garmin Connect export, zipped, with two days of health data + days = [{'calendarDate': f'2024-03-0{i}', 'restingHeartRate': 50 + i, 'totalSteps': 9000, 'bodyBattery': {'bodyBatteryStatList': [ + {'bodyBatteryStatType': 'HIGHEST', 'statsValue': 90}, {'bodyBatteryStatType': 'LOWEST', 'statsValue': 20}]}} for i in (2, 3)] + sleep = [{'calendarDate': '2024-03-03', 'sleepStartTimestampGMT': '2024-03-02T20:30:00.0', 'sleepEndTimestampGMT': '2024-03-03T04:45:00.0', + 'deepSleepSeconds': 4000, 'lightSleepSeconds': 16000, 'remSleepSeconds': 6000, 'awakeSleepSeconds': 600, 'sleepScores': {'overallScore': 81}}] + bp = [{'bloodPressure': {'systolic': 118, 'diastolic': 72, 'pulse': 55, 'notes': 'Hgb 14.6'}, 'metaData': {'calendarDate': [2024, 3, 3]}}] + with zipfile.ZipFile(d / 'garmin_export.zip', 'w') as z: + z.writestr('DI_CONNECT/DI-Connect-Aggregator/UDSFile_2024.json', json.dumps(days) + '\x00' * 10) + z.writestr('DI_CONNECT/DI-Connect-Wellness/1_sleepData.json', json.dumps(sleep)) + z.writestr('DI_CONNECT/DI-Connect-Wellness/BloodPressureFile_1.json', json.dumps(bp)) + return d + +def test_pipeline(tmp_path, inbox): + lib = Library.create(str(tmp_path / 'lib'), name='Test', birth_year=1980, sex='F', home_tz='Africa/Johannesburg') + st = sources.import_path(lib, str(inbox)) + assert st['TCX activity'] == 1 and st['AlpineQuest track'] == 3 and st['GPX track'] == 1 and st['Strava activity'] == 2 + assert sources.import_path(lib, str(inbox))['already imported'] >= 4 # importing again changes nothing + assert dedupe.run(lib) == 2 # phone run and Strava run copy the TCX run + a = {r['file'].split('/')[-1]: r for r in lib.activities()} + assert a['old_running.tcx']['start_local'] == '2024-03-02 08:00:00' # local time from the GPS position + assert a['phone.trk']['dup_of'] == a['old_running.tcx']['id'] + assert a['car.trk']['flag'] == 'transport' + assert a['2.gpx']['dup_of'] is None and a['2.gpx']['name'] == 'Morning Ride' + days = {d['d']: d for d in lib.days()} + assert days['2024-03-03']['rhr'] == 53 and days['2024-03-03']['sleep'] == round(26000 / 3600, 2) + assert days['2024-03-03']['bed'] == -1.5 # 22:30 local + assert lib.series('bp')[0]['hb'] == 14.6 + out = report.build(lib, log=lambda *_: None) + html = open(out, encoding='utf-8').read() + assert '__DATA__' not in html and "Test's activity logbook" in html + data = report.data(lib) + assert len(data['acts']) == 4 and data['health']['days'] # run, hike, walk, ride + assert export.run(lib, log=lambda *_: None) == 4 + z = zipfile.ZipFile(lib.path('exports', 'tracks_trk.zip')) + back = aqtrk.parse_any(z.read([n for n in z.namelist() if 'hiking' in n][0])) + assert back['user']['activity'] == 'hike' and len(back['segments'][0]) == 720 diff --git a/tools/compare_csv.py b/tools/compare_csv.py new file mode 100644 index 0000000..e583159 --- /dev/null +++ b/tools/compare_csv.py @@ -0,0 +1,32 @@ +"""Compare a library with an all_activities.csv written by the original scripts (the reference for phase 0). +usage: python tools/compare_csv.py """ +import collections, csv, sys +from datetime import datetime +sys.path.insert(0, 'src') +from mygarmin.library import Library +from mygarmin.timeutil import parse_utc + +lib = Library(sys.argv[1]) +SHOWN = (None, 'suspect GPS', 'summary only') # flags that still appear in the dashboard +new = [r for r in lib.activities() if not r['dup_of'] and r['flag'] in SHOWN] +old = list(csv.DictReader(open(sys.argv[2], encoding='utf-8'))) +print('per source old -> new'); co, cn = collections.Counter(r['src'] for r in old), collections.Counter(r['source'] for r in new) +for s in sorted(set(co) | set(cn)): print(f' {s:12s} {co[s]:5d} {cn[s]:5d}') + +key = lambda t: parse_utc(t).timestamp() +idx = sorted((key(r['start_utc']), i) for i, r in enumerate(new)) +used, miss, diffs = set(), [], collections.Counter(); ex = collections.defaultdict(list) +for o in old: + t = key(o['start_utc']) + c = [i for tt, i in idx if abs(tt - t) < 120 and i not in used] + if not c: miss.append(o); continue + n = new[c[0]]; used.add(c[0]) + if n['source'] != o['src']: diffs['source'] += 1; ex['source'].append((o['start_local'], o['src'], n['source'])) + if abs((n['dist_m'] or 0) / 1000 - float(o['dist_km'] or 0)) > 0.05: diffs['dist'] += 1; ex['dist'].append((o['start_local'], o['src'], o['dist_km'], round((n['dist_m'] or 0) / 1000, 2))) + if abs((n['moving_s'] or 0) / 60 - float(o['moving_min'] or 0)) > 0.5: diffs['moving'] += 1; ex['moving'].append((o['start_local'], o['src'], o['moving_min'], round((n['moving_s'] or 0) / 60, 1))) + if n['sport'] != o['sport']: diffs['sport'] += 1; ex['sport'].append((o['start_local'], o['src'], o['sport'], n['sport'])) + if n['start_local'][:16] != o['start_local'][:16]: diffs['local time'] += 1; ex['local time'].append((o['start_local'], o['src'], n['start_local'])) +print(f'matched {len(used)}; only in old {len(miss)}; only in new {len(new) - len(used)}') +for k, v in diffs.items(): print(f' differs in {k}: {v}', ex[k][:6]) +print('only old:', [(o['start_local'], o['src'], o['sport'], o['dist_km']) for o in miss[:15]]) +print('only new:', [(n['start_local'], n['source'], n['sport'], round((n['dist_m'] or 0) / 1000, 2), n['flag']) for i, n in enumerate(new) if i not in used][:15])