- sources/labs.py reads .xlsx/.csv sheets with a Date column; columns are recognised by header (ferritin, Hb, serum iron, transferrin saturation), with the lab's reference range and the user's Min/Max target. Formula cells are skipped. - Importing a sheet from disk remembers it in settings "lab_files"; every dashboard build reads it again. Editable in the app's settings. - Dashboard: ferritin chart (log scale, main lab as a line, a second lab as points, target range dashed), results table and a finding. - openpyxl added as a dependency and to the installer bundle. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
284 lines
16 KiB
Markdown
284 lines
16 KiB
Markdown
# How myGarmin works
|
||
|
||
This document explains how data gets in, what is stored where, and how the dashboard and the exports are made.
|
||
Module names refer to `src/mygarmin/`.
|
||
|
||
## The big picture
|
||
|
||
```mermaid
|
||
flowchart LR
|
||
subgraph IN[Data sources]
|
||
W[Garmin watch<br/>USB / MTP]
|
||
GE[Garmin Connect<br/>export zip]
|
||
API[Garmin Connect API<br/>unofficial]
|
||
SE[Strava<br/>export zip]
|
||
AQ[AlpineQuest<br/>.trk files]
|
||
F[Loose files<br/>.fit .tcx .gpx]
|
||
end
|
||
subgraph LIB[Library folder]
|
||
O[(originals/<br/>untouched files)]
|
||
DB[(myGarmin.db<br/>SQLite)]
|
||
end
|
||
subgraph OUT[Outputs]
|
||
D[dashboard.html]
|
||
C[all_activities.csv]
|
||
X[exports/<br/>tracks_gpx.zip<br/>tracks_trk.zip]
|
||
end
|
||
W -->|watch.pull| IMP
|
||
GE --> IMP
|
||
SE --> IMP
|
||
AQ --> IMP
|
||
F --> IMP
|
||
API -->|garmin_api.sync| IMP
|
||
IMP[Importers<br/>sources/] --> O
|
||
IMP --> DB
|
||
DB --> DD[dedupe.run]
|
||
DD --> DB
|
||
DB --> R[report.build] --> D & C
|
||
DB --> E[export.run]
|
||
O --> E --> X
|
||
```
|
||
|
||
The pipeline always runs in the same order: **import → de-duplicate → build → export**. The command line (`cli.py`) and the
|
||
app window (`app/`) are two front ends to the same functions; `mygarmin update` and the app's *Update everything* run the
|
||
whole chain.
|
||
|
||
Three principles shape everything:
|
||
1. **Originals are kept unchanged.** Every imported file is copied once into `originals/<source>/`. The database, the
|
||
dashboard and the exports can always be rebuilt from them.
|
||
2. **Importing is idempotent.** Files are recognised by content (MD5). Importing the same zip or folder again changes
|
||
nothing, so users can simply re-import everything they have.
|
||
3. **Nothing is thrown away.** Duplicates, car trips and broken recordings are *marked*, not deleted, and a later rule
|
||
change can bring them back.
|
||
|
||
## The library folder
|
||
|
||
One folder per person, chosen by the user:
|
||
|
||
| Path | Contents |
|
||
|---|---|
|
||
| `settings.json` | name, birth year, sex, home time zone, optional `copy_dashboard_to` paths and `lab_files` (blood test spreadsheets) |
|
||
| `myGarmin.db` | the SQLite database (below) |
|
||
| `originals/garmin_fit/` | activity FIT files, named by local start time (`2024-05-01-07-30-00.fit`) |
|
||
| `originals/garmin_health/`, `garmin_courses/` | health FITs (monitoring, sleep, HRV…) and courses, kept for later use |
|
||
| `originals/tcx/`, `alpinequest/`, `gpx/`, `strava/`, `labs/` | the other sources, under their original names |
|
||
| `races.csv` | optional, typed by the user: `date,event,time[,km,age_grade,position,pb]` |
|
||
| `dashboard.html`, `all_activities.csv` | built outputs |
|
||
| `exports/tracks_gpx.zip`, `exports/tracks_trk.zip` | built outputs, one track per outing, in year folders |
|
||
|
||
Things that belong to the PC, not the library, live in `%LOCALAPPDATA%\myGarmin\`:
|
||
- `app.json`: last and recent libraries;
|
||
- `tokens\<hash>\`: the Garmin Connect login, one per library. It is kept off the library because a library may sit on a shared drive;
|
||
- `webview\`: the app window's browser data;
|
||
- `app.log`, `cli.log`: error and command logs.
|
||
|
||
## The database
|
||
|
||
```mermaid
|
||
erDiagram
|
||
files {
|
||
text md5 PK
|
||
text path
|
||
text source
|
||
text kind
|
||
text imported
|
||
}
|
||
activities {
|
||
int id PK
|
||
text source
|
||
text file UK
|
||
text start_utc
|
||
int utc_offset_min
|
||
text start_local
|
||
real elapsed_s
|
||
real moving_s
|
||
text sport
|
||
text sub_sport
|
||
text name
|
||
real dist_m
|
||
real ascent_m
|
||
int avg_hr
|
||
int max_hr
|
||
int kcal
|
||
real te_aerobic
|
||
real vo2max
|
||
int npts
|
||
real lat
|
||
real lon
|
||
text flag
|
||
int dup_of
|
||
}
|
||
tracks {
|
||
int activity_id PK
|
||
text pts
|
||
}
|
||
health_days {
|
||
text date PK
|
||
text data
|
||
}
|
||
health_series {
|
||
text kind PK
|
||
text date PK
|
||
text key PK
|
||
text data
|
||
}
|
||
activities ||--o| tracks : "simplified map line"
|
||
activities ||--o| activities : "dup_of"
|
||
```
|
||
|
||
- **files:** every original ever stored, by MD5. This is what makes imports idempotent.
|
||
- **activities:** one row per recording from any source, with a summary in common units (metres, seconds) and
|
||
UTC plus local start time.
|
||
- `flag` says why a row is left out of the dashboard: `transport`, `too short` and `no time` are hidden; `suspect GPS`
|
||
is shown but kept out of pace figures; `summary only` is shown.
|
||
- `dup_of` points at the recording of the same outing that is kept.
|
||
- **tracks:** about 400 points per activity, enough for the map. Full-resolution tracks are always re-read from the originals.
|
||
- **health_days:** one JSON record per calendar day (sleep, resting HR, HRV, stress, Body Battery, steps, readiness,
|
||
training load and status, race predictions, endurance and hill score). New values are merged in, so a later source can
|
||
complete or correct a day.
|
||
- **health_series:** values that are not daily: `vo2` (per sport), `fage` (fitness age), `bp` (blood pressure, with any
|
||
haemoglobin value found in the note), `lthr` (lactate-threshold heart rate), `lab` (blood test results: ferritin,
|
||
haemoglobin, serum iron, transferrin saturation, each with its lab, reference range and the user's target range).
|
||
|
||
## Getting data in
|
||
|
||
### One entry point: `sources.import_path`
|
||
Anything can be imported: a single file, a folder, or a zip, including zips inside zips (Garmin's export nests its files).
|
||
`walk()` lists every file without unpacking to disk, then the importer decides what each one is:
|
||
|
||
```mermaid
|
||
flowchart TD
|
||
P[path: file, folder or zip] --> WK[walk: list all files,<br/>open nested zips, un-gzip]
|
||
WK --> Q1{activities.csv with<br/>'Activity ID' column?}
|
||
Q1 -->|yes| ST[Strava export importer]
|
||
WK --> Q2{DI_CONNECT/ in path?}
|
||
Q2 -->|yes| GX[Garmin export importer]
|
||
WK --> REST[everything else] --> T{extension}
|
||
T -->|.fit| FIT[import_fit]
|
||
T -->|.tcx| TCX[import_tcx]
|
||
T -->|.trk| TRK[import_trk]
|
||
T -->|.gpx| GPX[import_gpx]
|
||
T -->|other| IGN[ignored]
|
||
```
|
||
|
||
Account exports are recognised first, because their files only make sense together (Strava's names, times and sports are
|
||
in `activities.csv`, not in the track files). Every other file is imported on its own.
|
||
|
||
### Per file type (`sources/files.py`, readers in `formats/`)
|
||
|
||
| Type | What happens |
|
||
|---|---|
|
||
| **FIT** (`formats/fit.py`) | Already-known content is skipped. The file type is read straight from the header (fast enough for Garmin's ~11,000 uploaded files). Health and course FITs are only stored. Activity FITs: the session summary (distance, timer and elapsed time, ascent, heart rate, calories, training effect) plus GPS points; VO2max comes from an undocumented Garmin message. Stored as `originals/garmin_fit/<local start>.fit`, the same name the watch uses. |
|
||
| **TCX** (`formats/tcx.py`) | Summed from the laps; sport from the file name (old Garmin software put it there) or the `Sport` attribute; ascent with 3 m hysteresis. A second file with the same start is stored as a copy but not counted (old software saved many). |
|
||
| **AlpineQuest .trk** (`formats/aqtrk.py`) | Binary format per Psyberia's spec (current and pre-2.2.8 versions). Tracks with fewer than 10 timed points are stored only. The summary is computed from the points (see *Tracks without a summary*). Sport from AlpineQuest's activity tag, else guessed by speed. |
|
||
| **GPX** (`formats/gpx.py`) | Any creator. Files without a timed track (routes, waypoints) are stored only. Otherwise as AlpineQuest. |
|
||
|
||
### Tracks without a summary (`formats/geo.py`, `files.from_points`)
|
||
Phone tracks carry only points, so distance and time are worked out:
|
||
- **Distance:** sum of great-circle steps, skipping fixes with accuracy worse than 50 m.
|
||
- **Moving time:** time between points moving at 0.3–70 m/s with gaps under 5 min.
|
||
- **Ascent:** rises of more than 5 m (noise filter).
|
||
- **Flags:**
|
||
- `too short`: under 300 m or under 5 min moving.
|
||
- `transport`: tagged car, plane, train, boat or bus; or average above 28 km/h; or the 90th-percentile speed above 45 km/h.
|
||
- **Sport when untagged:** cycling from 12 km/h; running from 7.5 km/h; otherwise hiking (200 m+ climb or over 3 h), else walking.
|
||
|
||
### Strava export (`sources/strava.py`)
|
||
One row of `activities.csv` per activity:
|
||
- **Name, type, times:** from the CSV, which is UTC and has some columns twice; either copy may hold the value.
|
||
- **Points:** from the activity file (`.fit.gz`, `.gpx` or `.tcx`).
|
||
- **Time fixes:**
|
||
- Elapsed time falls back to the track's own time span.
|
||
- Moving time under 60 s (very sparse old tracks) is replaced by the elapsed time.
|
||
- **Flags:**
|
||
- `no time`: no usable time at all.
|
||
- `suspect GPS`: a "run" faster than 3:30/km, faster than 30 km/h at peak, or under 4:30/km while moving less than 55% of the elapsed time (GPS glitches and rides saved as runs).
|
||
|
||
### Garmin Connect export (`sources/garmin_export.py`)
|
||
- **Health JSON** under `DI_CONNECT/`. Every file ends in NUL padding, which is stripped before parsing.
|
||
- Daily summary (`UDSFile`): resting HR (Garmin's 7-day average), steps, intensity minutes (moderate + 2 × vigorous), all-day stress, Body Battery high and low.
|
||
- Sleep: stages, score, SpO2, respiration and sleep stress. Nights under 1 h of sleep are skipped. Bed and wake times are stored as local clock hours, with evening times negative so averages around midnight work.
|
||
- HRV, training readiness (the morning value preferred; HRV glitches outside 10–200 ms dropped), acute and chronic load, training status, race predictions, endurance and hill score.
|
||
- VO2max, fitness age, blood pressure (haemoglobin parsed from the note) and lactate threshold go to `health_series`.
|
||
- **Uploaded files:** of the FITs in `DI-Connect-Uploaded-Files/*.zip`, only activities are imported. The monitoring files are already covered by the JSON. This is how activities missing from a watch archive turn up.
|
||
|
||
### Garmin watch over USB (`sources/watch.py`)
|
||
- **Finding the watch:** newer watches have no drive letter on Windows (MTP). The watch is found by Garmin's USB vendor ID `091e`, which works in any Windows language and never matches a phone.
|
||
- **Copying:** its `Activity`, `Monitor`, `Sleep`, `HRVStatus`, `Metrics`, `Courses`, … folders are copied through the Windows Shell to a temporary folder. That folder is then imported like any other, and deleted.
|
||
- **Older watches** that appear as a drive can simply be imported as a folder.
|
||
|
||
### Garmin Connect API (`sources/garmin_api.py`)
|
||
Uses the unofficial `python-garminconnect` library (read-only). Garmin has no personal API.
|
||
- **Login:** once, with password and MFA code. Only a self-refreshing token is stored, per library, on the PC.
|
||
- **Activities:** everything since the newest FIT in the library minus 3 days. Each is downloaded in its original format: a zip holding the very same FIT file the watch made, so it goes through `import_fit` and can never create a duplicate.
|
||
- **Health:** every day from the last stored day minus 3 days up to today. The last days are re-fetched because Garmin completes them later. The fields are the same as from the export, so both sources fill the same records.
|
||
- **Pacing:** calls are spaced 0.3 s apart. A failing call is logged and skipped.
|
||
|
||
### Blood test spreadsheets (`sources/labs.py`)
|
||
For results the user keeps in Excel (.xlsx) or a .csv, e.g. ferritin during treatment for iron overload.
|
||
- **Layout:** a header row with a `Date` column. Other columns are recognised by their header: ferritin (or a µg/L or ng/mL unit), haemoglobin/Hb, serum iron, transferrin saturation. A range in brackets, such as `(30-400)`, is the lab's reference range; what is left of the header is the lab's name. Columns headed `Min` and `Max` are the user's own target range.
|
||
- **Only typed-in numbers count.** Cells with a formula (estimates, differences) are skipped, so a sheet can keep its own calculations.
|
||
- **Two lab methods** in two columns stay separate series: the dashboard draws the one with most results as a line and the other as points.
|
||
- **Kept in sync:** importing a sheet from disk adds its path to `lab_files` in the settings. Every dashboard build reads those sheets again and replaces their earlier results, so edits and deleted rows show. A sheet that is missing (moved, drive offline) keeps its last results; change the path in the app's settings.
|
||
- A sheet found inside a folder or zip is imported once and kept under `originals/labs/`.
|
||
|
||
## Time zones (`timeutil.py`)
|
||
Every activity keeps its UTC start and the offset to local time. The offset comes from:
|
||
1. the file itself (FIT `local_timestamp`, rounded to 15 min); else
|
||
2. the time zone at the first GPS point (offline lookup with `timezonefinder`, daylight saving included); else
|
||
3. the library's home time zone.
|
||
|
||
## De-duplication (`dedupe.py`)
|
||
One outing is often recorded several times: watch, phone app and Strava. All copies are imported; afterwards a single pass
|
||
decides which one to keep:
|
||
|
||
```mermaid
|
||
flowchart LR
|
||
A[all activities except<br/>transport / too short / no time] --> S[sort by source priority,<br/>then start time]
|
||
S --> L{for each: an already-kept<br/>activity of the same outing?}
|
||
L -->|yes| M[mark dup_of = kept one]
|
||
L -->|no| K[keep]
|
||
```
|
||
|
||
- **Priority:** FIT (watch) > TCX (older Garmin) > AlpineQuest > Strava > GPX. The watch has heart rate and the best summary.
|
||
- **Same outing:** the starts are less than 15 min apart, **or** more than half of the lower-priority recording lies
|
||
inside the kept one. The second rule catches a phone that was started late; it deliberately lets a short run recorded
|
||
during a long phone-tracked ride stand on its own.
|
||
- **Same source:** only starts less than 60 s apart count (the same activity saved twice).
|
||
- The pass is rerun after every import and recomputes all `dup_of` values from scratch, so it reflects the current rules.
|
||
|
||
## Building the dashboard (`report/`)
|
||
1. Select the activities to show: not a duplicate, and flag empty, `suspect GPS` or `summary only`.
|
||
2. Collect one JSON object: profile (name, birth year, sex), activities, simplified tracks, health days and series, and races from `races.csv`.
|
||
3. Put it into the template `report/dashboard.html` (`__DATA__`) and write a single self-contained HTML file.
|
||
Charts (Chart.js) and the map (Leaflet with Esri and OpenTopoMap tiles) load from the web; everything else is in the file.
|
||
4. Everything visible is computed **in the page** from that data, so nothing personal is in the template:
|
||
- the header: sources, years covered, gaps without recordings;
|
||
- totals, the year-by-year table, monthly volume and fitness charts;
|
||
- the findings: busiest year, fastest running period, VO2max rated against the Cooper Institute norms for the person's age and sex, efficiency trend, maximum heart rate. Headlines pick their wording from the direction of the data ("getting shorter" or "longer");
|
||
- the sleep and health section and the races section, only when there is data.
|
||
5. `all_activities.csv` lists **every** row, including duplicates and flagged ones, with the reason, for checking in Excel.
|
||
6. The dashboard is also copied to any `copy_dashboard_to` paths in the settings.
|
||
|
||
Before step 1, the blood test sheets in `lab_files` are read again.
|
||
|
||
## Exports (`export.py`)
|
||
- **Which tracks:** the same as on the dashboard, but only with GPS. One file per outing, so duplicate recordings never appear twice.
|
||
- **Full resolution:** points are re-read from each original file (FIT, TCX, GPX, AlpineQuest or Strava).
|
||
- **Two zips, in year folders:**
|
||
- `tracks_gpx.zip` (with heart rate as Garmin's GPX extension);
|
||
- `tracks_trk.zip` in AlpineQuest's own format, ready to copy to the phone. Every `.trk` is read back and compared before it is written.
|
||
- **File names:** local start, sport and name (`2024-05-04-08-00_running_Saturday-5k.trk`).
|
||
|
||
## The app window (`app/`)
|
||
- **Window:** a pywebview window (WebView2 on Windows) showing `app/ui.html`, which calls the Python `Api` class.
|
||
- **Jobs:** import, watch, sync, build, export and update run one at a time in a worker thread. Each streams its log lines into the page and refreshes the overview when done.
|
||
- **Garmin MFA:** the login waits while the page asks for the code.
|
||
- **Startup:** the window opens the last library used. Only one copy runs at a time, because a second would block on the shared browser data. Startup errors are shown in a message box and written to `app.log`.
|
||
|
||
## Installer (`packaging/`)
|
||
- **Bundle:** PyInstaller makes a one-folder, windowed `myGarmin.exe` with Python and all libraries inside.
|
||
- **Installer:** Inno Setup wraps it into `myGarmin-setup-<version>.exe`. It installs per user without admin rights, checks for WebView2, and its uninstaller never touches libraries.
|
||
- **Command line:** given arguments, the bundled exe runs the CLI and writes its output to `cli.log`.
|
||
- **Build:** run `packaging\build.ps1`.
|