diff --git a/.gitignore b/.gitignore index 52828de..32f3003 100644 --- a/.gitignore +++ b/.gitignore @@ -8,7 +8,8 @@ *.trk *.ldk *.zip -dashboard*.html +/dashboard*.html +/*.html settings.json .garminconnect/ garmin_tokens.json @@ -16,6 +17,12 @@ library/ originals/ exports/ inbox/ +*.gpx +*.csv +*.json +*.gz +*.log +build_log.txt # synthetic test fixtures are allowed !tests/data/** @@ -26,3 +33,6 @@ build/ dist/ *.egg-info/ .venv/ + +# packaging output and generated files +packaging/version_info.txt diff --git a/README.md b/README.md index d703e6d..31677a1 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,12 @@ Everything stays on your PC: there is no server and no account, and nothing is u > 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: +**Windows:** download `myGarmin-setup-.exe` from the releases page and run it. No admin rights or Python needed; +it installs for your user only and adds myGarmin to the Start menu. The app window needs Microsoft Edge WebView2, +which Windows 11 includes (setup checks and points you to Microsoft's download if it is missing). +Uninstalling removes the program only; your library folder stays where you put it. + +**From source** (any OS with Python 3.12 or newer; the app window and watch-over-USB are Windows-first): ``` pip install -e . # from a checkout of this repo pip install -e ".[api]" # also the Garmin Connect API (optional) @@ -53,7 +58,14 @@ mygarmin update D:\myGarmin # all of the above + build + export 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. +`pip install -e ".[dev,app]"`, then `pytest` (tests use synthetic files only) and `mygarmin-app` for the window. + +Build the Windows installer (needs `pip install pyinstaller` and Inno Setup 6): +``` +powershell -ExecutionPolicy Bypass -File packaging\build.ps1 # -> build\installer\myGarmin-setup-.exe +``` +The bundled `myGarmin.exe` also runs the command line (`myGarmin.exe status `); as it has no console, output +goes to `%LOCALAPPDATA%\myGarmin\cli.log`. `MYGARMIN_SELFTEST=` makes the window write what it shows and close. ## Licence MIT, see [LICENSE](LICENSE). diff --git a/packaging/build.ps1 b/packaging/build.ps1 new file mode 100644 index 0000000..cec759f --- /dev/null +++ b/packaging/build.ps1 @@ -0,0 +1,26 @@ +# Build myGarmin-setup-.exe: PyInstaller (one folder, Python included) -> Inno Setup installer. +# Needs: pip install pyinstaller ; Inno Setup 6 (winget install JRSoftware.InnoSetup). +# usage (from the repo): powershell -ExecutionPolicy Bypass -File packaging\build.ps1 +$ErrorActionPreference = 'Stop' +$here = Split-Path -Parent $MyInvocation.MyCommand.Path +Set-Location $here +$version = (Select-String -Path ..\pyproject.toml -Pattern '^version = "(.+)"').Matches[0].Groups[1].Value +$v4 = (($version -split '\.') + @('0', '0', '0'))[0..3] -join ', ' + +# Windows file version resource for myGarmin.exe +@" +VSVersionInfo(ffi=FixedFileInfo(filevers=($v4), prodvers=($v4)), + kids=[StringFileInfo([StringTable('040904B0', [StringStruct('ProductName', 'myGarmin'), StringStruct('FileDescription', 'myGarmin activity and health logbook'), + StringStruct('FileVersion', '$version'), StringStruct('ProductVersion', '$version'), StringStruct('LegalCopyright', 'MIT licence')])]), + VarFileInfo([VarStruct('Translation', [1033, 1200])])]) +"@ | Out-File -Encoding utf8 version_info.txt + +python -m PyInstaller --noconfirm --clean --distpath ..\build\dist --workpath ..\build\work myGarmin.spec +if ($LASTEXITCODE) { throw 'PyInstaller failed' } + +$iscc = @("$env:LOCALAPPDATA\Programs\Inno Setup 6\ISCC.exe", "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe", "$env:ProgramFiles\Inno Setup 6\ISCC.exe") | + Where-Object { Test-Path $_ } | Select-Object -First 1 +if (-not $iscc) { throw 'Inno Setup 6 not found (winget install JRSoftware.InnoSetup)' } +& $iscc "/DAppVersion=$version" myGarmin.iss +if ($LASTEXITCODE) { throw 'Inno Setup failed' } +Get-Item ..\build\installer\*.exe | Select-Object Name, @{n='MB'; e={[math]::Round($_.Length / 1MB, 1)}} diff --git a/packaging/launcher.py b/packaging/launcher.py new file mode 100644 index 0000000..9a67fa9 --- /dev/null +++ b/packaging/launcher.py @@ -0,0 +1,19 @@ +# Entry point of the bundled myGarmin.exe (PyInstaller). +# No arguments: the app window. With arguments: the mygarmin command line (myGarmin.exe import ...); +# the exe has no console, so its output goes to %LOCALAPPDATA%\myGarmin\cli.log. +import os, sys + +if len(sys.argv) > 1: + log = os.path.join(os.environ.get('LOCALAPPDATA', os.path.expanduser('~')), 'myGarmin', 'cli.log') + os.makedirs(os.path.dirname(log), exist_ok=True) + sys.stdout = sys.stderr = open(log, 'a', encoding='utf-8', buffering=1) + print('>', ' '.join(sys.argv[1:])) + from mygarmin.cli import main + try: main(sys.argv[1:]) + except SystemExit as e: + if e.code not in (None, 0): print('exit:', e.code); raise + except Exception: + import traceback; traceback.print_exc(); sys.exit(1) +else: + from mygarmin.app import main + main() diff --git a/packaging/myGarmin.ico b/packaging/myGarmin.ico new file mode 100644 index 0000000..87c628a Binary files /dev/null and b/packaging/myGarmin.ico differ diff --git a/packaging/myGarmin.iss b/packaging/myGarmin.iss new file mode 100644 index 0000000..85a4094 --- /dev/null +++ b/packaging/myGarmin.iss @@ -0,0 +1,69 @@ +; Inno Setup script for myGarmin. Built by packaging\build.ps1 (passes /DAppVersion=x.y.z). +; Installs per user (no admin rights) into %LOCALAPPDATA%\Programs\myGarmin. The user's library folder, +; settings and Garmin token live elsewhere and are never touched by setup or uninstall. +#ifndef AppVersion + #define AppVersion "0.0.0" +#endif + +[Setup] +AppId={{6B0E8C5A-3F2D-4C1B-9E7A-2D5F8A1C4B90} +AppName=myGarmin +AppVersion={#AppVersion} +AppVerName=myGarmin {#AppVersion} +AppPublisher=myGarmin (open source, MIT) +AppPublisherURL=https://services.doorduin.co.za/gitea/public/myGarminApp +DefaultDirName={autopf}\myGarmin +DefaultGroupName=myGarmin +DisableProgramGroupPage=yes +PrivilegesRequired=lowest +PrivilegesRequiredOverridesAllowed=dialog +ArchitecturesAllowed=x64compatible +ArchitecturesInstallIn64BitMode=x64compatible +MinVersion=10.0 +OutputDir=..\build\installer +OutputBaseFilename=myGarmin-setup-{#AppVersion} +SetupIconFile=myGarmin.ico +UninstallDisplayIcon={app}\myGarmin.exe +LicenseFile=..\LICENSE +Compression=lzma2/max +SolidCompression=yes +WizardStyle=modern +CloseApplications=yes + +[Tasks] +Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}" + +[Files] +Source: "..\build\dist\myGarmin\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs + +[Icons] +Name: "{group}\myGarmin"; Filename: "{app}\myGarmin.exe" +Name: "{group}\Uninstall myGarmin"; Filename: "{uninstallexe}" +Name: "{autodesktop}\myGarmin"; Filename: "{app}\myGarmin.exe"; Tasks: desktopicon + +[Run] +Filename: "{app}\myGarmin.exe"; Description: "{cm:LaunchProgram,myGarmin}"; Flags: nowait postinstall skipifsilent + +[Code] +// The app window uses Microsoft Edge WebView2 (part of Windows 11; usually present on Windows 10). +function HasWebView2(): Boolean; +var v: String; +begin + Result := RegQueryStringValue(HKLM, 'SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}', 'pv', v) + or RegQueryStringValue(HKCU, 'Software\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}', 'pv', v); + Result := Result and (v <> '') and (v <> '0.0.0.0'); +end; + +function InitializeSetup(): Boolean; +var code: Integer; +begin + Result := True; + if not HasWebView2() then + if MsgBox('myGarmin needs the Microsoft Edge WebView2 Runtime, which is not installed on this PC.' + #13#10#13#10 + + 'Open the Microsoft download page now? (Install the "Evergreen Bootstrapper", then run this setup again.)', + mbConfirmation, MB_YESNO) = IDYES then + begin + ShellExec('open', 'https://developer.microsoft.com/microsoft-edge/webview2/', '', '', SW_SHOWNORMAL, ewNoWait, code); + Result := False; + end; +end; diff --git a/packaging/myGarmin.png b/packaging/myGarmin.png new file mode 100644 index 0000000..32457b1 Binary files /dev/null and b/packaging/myGarmin.png differ diff --git a/packaging/myGarmin.spec b/packaging/myGarmin.spec new file mode 100644 index 0000000..0a495cd --- /dev/null +++ b/packaging/myGarmin.spec @@ -0,0 +1,16 @@ +# PyInstaller spec: one-folder, windowed build of the myGarmin app. Build with packaging\build.ps1. +from PyInstaller.utils.hooks import collect_all, collect_data_files + +datas = collect_data_files('mygarmin', includes=['**/*.html']) +datas += collect_data_files('timezonefinder') + collect_data_files('tzdata') +binaries, hidden = [], [] +for pkg in ('webview', 'clr_loader', 'pythonnet', 'garminconnect', 'curl_cffi', 'timezonefinder'): # js files, .NET bridge, native libs, tz data (needs numpy) + d, b, h = collect_all(pkg); datas += d; binaries += b; hidden += h + +a = Analysis(['launcher.py'], pathex=['../src'], binaries=binaries, datas=datas, + hiddenimports=hidden + ['mygarmin.sources.garmin_api', 'mygarmin.sources.watch', 'mygarmin.cli', 'mygarmin.export', 'mygarmin.report', 'mygarmin.dedupe', 'clr'], + excludes=['tkinter', 'matplotlib', 'pandas', 'PIL', 'pytest'], noarchive=False) +pyz = PYZ(a.pure) +exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='myGarmin', icon='myGarmin.ico', + console=False, upx=False, version='version_info.txt') +coll = COLLECT(exe, a.binaries, a.datas, name='myGarmin', upx=False) diff --git a/src/mygarmin/app/__init__.py b/src/mygarmin/app/__init__.py index 18379e0..24419c0 100644 --- a/src/mygarmin/app/__init__.py +++ b/src/mygarmin/app/__init__.py @@ -222,7 +222,9 @@ def _main(): from webview.dom import DOMEventHandler except ImportError: raise SystemExit('The app window needs pywebview: pip install "mygarmin[app]"') - if sys.platform == 'win32': # a second window would share (and block on) the same browser data folder + selftest_out = os.environ.get('MYGARMIN_SELFTEST') # developer check, runs beside an open app with its own browser data + storage = os.path.join(os.path.dirname(STATE), 'webview-selftest' if selftest_out else 'webview') + if sys.platform == 'win32' and not selftest_out: # a second window would share (and block on) the same browser data folder import ctypes main._mutex = ctypes.windll.kernel32.CreateMutexW(None, False, 'Local\\myGarminApp') if ctypes.windll.kernel32.GetLastError() == 183: # ERROR_ALREADY_EXISTS @@ -242,11 +244,11 @@ def _main(): el.events.dragover += DOMEventHandler(lambda e: None, prevent_default=True) el.events.drop += DOMEventHandler(on_drop, prevent_default=True, stop_propagation=True) win.events.loaded += loaded - if os.environ.get('MYGARMIN_SELFTEST'): # developer check: does the page render through the real bridge? + if selftest_out: # does the page render through the real bridge? def selftest(): import time; time.sleep(6) r = win.evaluate_js("[document.getElementById('home').className, document.getElementById('setup').className, " "document.getElementById('tiles').innerText.replace(/\\s+/g, ' ').slice(0, 120)].join(' | ')") - open(os.environ['MYGARMIN_SELFTEST'], 'w', encoding='utf-8').write(str(r)); win.destroy() + open(selftest_out, 'w', encoding='utf-8').write(str(r)); win.destroy() threading.Thread(target=selftest, daemon=True).start() - webview.start(private_mode=False, storage_path=os.path.join(os.path.dirname(STATE), 'webview')) + webview.start(private_mode=False, storage_path=storage) diff --git a/src/mygarmin/report/dashboard.html b/src/mygarmin/report/dashboard.html new file mode 100644 index 0000000..3010fc3 --- /dev/null +++ b/src/mygarmin/report/dashboard.html @@ -0,0 +1,528 @@ + + + + + +__TITLE__ + + + + + + +
+
+
+

+

+

+
+ +
+
+
+ +
+

What the data says about fitness and age

+

+
+

Year by year

+
+
+ +
+

Activity per month

+
+ + + +
+
+
+ +
+

Fitness markers from the activities

+

From the values stamped into each activity file. VO2max is Garmin's running estimate (updated on outdoor runs with GPS and heart rate). Higher efficiency means more distance per heartbeat, a sign of aerobic fitness. Charts without data are left out.

+
+

VO2max (ml/kg/min)

+

Running efficiency (metres per heartbeat), each run

+

Running: average pace (min/km), each run

Runs slower than 12 min/km (paused recordings) and runs with GPS errors are left out.

+

Running: average heart rate (bpm), each run

+

Aerobic training effect, monthly average

+

Climbing per month (m ascent, all sports)

+
+
+ + + + + +
+

Where you went

+
+
+
+

Tracks are simplified to about 400 points each for speed; full-resolution tracks are in the exports folder (GPX and AlpineQuest). Click a track for details. Switch between street, topographic and satellite maps at the top right of the map.

+
+ +
+

Month by month

+
+
+ +
+

All activities

+
+
+
+ +
+ + + + + + diff --git a/src/mygarmin/sources/garmin_export.py b/src/mygarmin/sources/garmin_export.py index 3c333e7..ad13056 100644 --- a/src/mygarmin/sources/garmin_export.py +++ b/src/mygarmin/sources/garmin_export.py @@ -94,7 +94,7 @@ def health(lib, items): 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.""" + """Blood pressure record; a haemoglobin value written in the notes ('Hb 15.0', 'Hgb 15 0', 'Haemoglobin 15.0') is picked up.""" hb = re.search(r'(?