forked from cyberjunky/python-garminconnect
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.py
More file actions
executable file
·3591 lines (3198 loc) · 141 KB
/
demo.py
File metadata and controls
executable file
·3591 lines (3198 loc) · 141 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
🏃♂️ Comprehensive Garmin Connect API Demo
==========================================
This is a comprehensive demonstration program showing ALL available API calls
and error handling patterns for python-garminconnect.
For a simple getting-started example, see example.py
Dependencies:
pip3 install garth requests readchar
Environment Variables (optional):
export EMAIL=<your garmin email address>
export PASSWORD=<your garmin password>
export GARMINTOKENS=<path to token storage>
"""
import datetime
import json
import logging
import os
import sys
from contextlib import suppress
from datetime import timedelta
from getpass import getpass
from pathlib import Path
from typing import Any
import readchar
import requests
from garth.exc import GarthException, GarthHTTPError
from garminconnect import (
Garmin,
GarminConnectAuthenticationError,
GarminConnectConnectionError,
GarminConnectTooManyRequestsError,
)
# Configure logging to reduce verbose error output from garminconnect library
# This prevents double error messages for known API issues
logging.getLogger("garminconnect").setLevel(logging.CRITICAL)
api: Garmin | None = None
class Config:
"""Configuration class for the Garmin Connect API demo."""
def __init__(self):
# Load environment variables
self.email = os.getenv("EMAIL")
self.password = os.getenv("PASSWORD")
self.tokenstore = os.getenv("GARMINTOKENS") or "~/.garminconnect"
self.tokenstore_base64 = (
os.getenv("GARMINTOKENS_BASE64") or "~/.garminconnect_base64"
)
# Date settings
self.today = datetime.date.today()
self.week_start = self.today - timedelta(days=7)
self.month_start = self.today - timedelta(days=30)
# API call settings
self.default_limit = 100
self.start = 0
self.start_badge = 1 # Badge related calls start counting at 1
# Activity settings
self.activitytype = "" # Possible values: cycling, running, swimming, multi_sport, fitness_equipment, hiking, walking, other
self.activityfile = (
"test_data/sample_activity.gpx" # Supported file types: .fit .gpx .tcx
)
self.workoutfile = "test_data/sample_workout.json" # Sample workout JSON file
# Export settings
self.export_dir = Path("your_data")
self.export_dir.mkdir(exist_ok=True)
# Initialize configuration
config = Config()
# Organized menu categories
menu_categories = {
"1": {
"name": "👤 User & Profile",
"options": {
"1": {"desc": "Get full name", "key": "get_full_name"},
"2": {"desc": "Get unit system", "key": "get_unit_system"},
"3": {"desc": "Get user profile", "key": "get_user_profile"},
"4": {
"desc": "Get userprofile settings",
"key": "get_userprofile_settings",
},
},
},
"2": {
"name": "📊 Daily Health & Activity",
"options": {
"1": {
"desc": f"Get activity data for '{config.today.isoformat()}'",
"key": "get_stats",
},
"2": {
"desc": f"Get user summary for '{config.today.isoformat()}'",
"key": "get_user_summary",
},
"3": {
"desc": f"Get stats and body composition for '{config.today.isoformat()}'",
"key": "get_stats_and_body",
},
"4": {
"desc": f"Get steps data for '{config.today.isoformat()}'",
"key": "get_steps_data",
},
"5": {
"desc": f"Get heart rate data for '{config.today.isoformat()}'",
"key": "get_heart_rates",
},
"6": {
"desc": f"Get resting heart rate for '{config.today.isoformat()}'",
"key": "get_resting_heart_rate",
},
"7": {
"desc": f"Get sleep data for '{config.today.isoformat()}'",
"key": "get_sleep_data",
},
"8": {
"desc": f"Get stress data for '{config.today.isoformat()}'",
"key": "get_all_day_stress",
},
},
},
"3": {
"name": "🔬 Advanced Health Metrics",
"options": {
"1": {
"desc": f"Get training readiness for '{config.today.isoformat()}'",
"key": "get_training_readiness",
},
"2": {
"desc": f"Get training status for '{config.today.isoformat()}'",
"key": "get_training_status",
},
"3": {
"desc": f"Get respiration data for '{config.today.isoformat()}'",
"key": "get_respiration_data",
},
"4": {
"desc": f"Get SpO2 data for '{config.today.isoformat()}'",
"key": "get_spo2_data",
},
"5": {
"desc": f"Get max metrics (VO2, fitness age) for '{config.today.isoformat()}'",
"key": "get_max_metrics",
},
"6": {
"desc": f"Get Heart Rate Variability (HRV) for '{config.today.isoformat()}'",
"key": "get_hrv_data",
},
"7": {
"desc": f"Get Fitness Age data for '{config.today.isoformat()}'",
"key": "get_fitnessage_data",
},
"8": {
"desc": f"Get stress data for '{config.today.isoformat()}'",
"key": "get_stress_data",
},
"9": {"desc": "Get lactate threshold data", "key": "get_lactate_threshold"},
"0": {
"desc": f"Get intensity minutes for '{config.today.isoformat()}'",
"key": "get_intensity_minutes_data",
},
},
},
"4": {
"name": "📈 Historical Data & Trends",
"options": {
"1": {
"desc": f"Get daily steps from '{config.week_start.isoformat()}' to '{config.today.isoformat()}'",
"key": "get_daily_steps",
},
"2": {
"desc": f"Get body battery from '{config.week_start.isoformat()}' to '{config.today.isoformat()}'",
"key": "get_body_battery",
},
"3": {
"desc": f"Get floors data for '{config.week_start.isoformat()}'",
"key": "get_floors",
},
"4": {
"desc": f"Get blood pressure from '{config.week_start.isoformat()}' to '{config.today.isoformat()}'",
"key": "get_blood_pressure",
},
"5": {
"desc": f"Get progress summary from '{config.week_start.isoformat()}' to '{config.today.isoformat()}'",
"key": "get_progress_summary_between_dates",
},
"6": {
"desc": f"Get body battery events for '{config.week_start.isoformat()}'",
"key": "get_body_battery_events",
},
},
},
"5": {
"name": "🏃 Activities & Workouts",
"options": {
"1": {
"desc": f"Get recent activities (limit {config.default_limit})",
"key": "get_activities",
},
"2": {"desc": "Get last activity", "key": "get_last_activity"},
"3": {
"desc": f"Get activities for today '{config.today.isoformat()}'",
"key": "get_activities_fordate",
},
"4": {
"desc": f"Download activities by date range '{config.week_start.isoformat()}' to '{config.today.isoformat()}'",
"key": "download_activities",
},
"5": {
"desc": "Get all activity types and statistics",
"key": "get_activity_types",
},
"6": {
"desc": f"Upload activity data from {config.activityfile}",
"key": "upload_activity",
},
"7": {"desc": "Get workouts", "key": "get_workouts"},
"8": {"desc": "Get activity splits (laps)", "key": "get_activity_splits"},
"9": {
"desc": "Get activity typed splits",
"key": "get_activity_typed_splits",
},
"0": {
"desc": "Get activity split summaries",
"key": "get_activity_split_summaries",
},
"a": {"desc": "Get activity weather data", "key": "get_activity_weather"},
"b": {
"desc": "Get activity heart rate zones",
"key": "get_activity_hr_in_timezones",
},
"c": {
"desc": "Get detailed activity information",
"key": "get_activity_details",
},
"d": {"desc": "Get activity gear information", "key": "get_activity_gear"},
"e": {"desc": "Get single activity data", "key": "get_activity"},
"f": {
"desc": "Get strength training exercise sets",
"key": "get_activity_exercise_sets",
},
"g": {"desc": "Get workout by ID", "key": "get_workout_by_id"},
"h": {"desc": "Download workout to .FIT file", "key": "download_workout"},
"i": {
"desc": f"Upload workout from {config.workoutfile}",
"key": "upload_workout",
},
"j": {
"desc": f"Get activities by date range '{config.today.isoformat()}'",
"key": "get_activities_by_date",
},
"k": {"desc": "Set activity name", "key": "set_activity_name"},
"l": {"desc": "Set activity type", "key": "set_activity_type"},
"m": {"desc": "Create manual activity", "key": "create_manual_activity"},
"n": {"desc": "Delete activity", "key": "delete_activity"},
},
},
"6": {
"name": "⚖️ Body Composition & Weight",
"options": {
"1": {
"desc": f"Get body composition for '{config.today.isoformat()}'",
"key": "get_body_composition",
},
"2": {
"desc": f"Get weigh-ins from '{config.week_start.isoformat()}' to '{config.today.isoformat()}'",
"key": "get_weigh_ins",
},
"3": {
"desc": f"Get daily weigh-ins for '{config.today.isoformat()}'",
"key": "get_daily_weigh_ins",
},
"4": {"desc": "Add a weigh-in (interactive)", "key": "add_weigh_in"},
"5": {
"desc": f"Set body composition data for '{config.today.isoformat()}' (interactive)",
"key": "set_body_composition",
},
"6": {
"desc": f"Add body composition for '{config.today.isoformat()}' (interactive)",
"key": "add_body_composition",
},
"7": {
"desc": f"Delete all weigh-ins for '{config.today.isoformat()}'",
"key": "delete_weigh_ins",
},
"8": {"desc": "Delete specific weigh-in", "key": "delete_weigh_in"},
},
},
"7": {
"name": "🏆 Goals & Achievements",
"options": {
"1": {"desc": "Get personal records", "key": "get_personal_records"},
"2": {"desc": "Get earned badges", "key": "get_earned_badges"},
"3": {"desc": "Get adhoc challenges", "key": "get_adhoc_challenges"},
"4": {
"desc": "Get available badge challenges",
"key": "get_available_badge_challenges",
},
"5": {"desc": "Get active goals", "key": "get_active_goals"},
"6": {"desc": "Get future goals", "key": "get_future_goals"},
"7": {"desc": "Get past goals", "key": "get_past_goals"},
"8": {"desc": "Get badge challenges", "key": "get_badge_challenges"},
"9": {
"desc": "Get non-completed badge challenges",
"key": "get_non_completed_badge_challenges",
},
"0": {
"desc": "Get virtual challenges in progress",
"key": "get_inprogress_virtual_challenges",
},
"a": {"desc": "Get race predictions", "key": "get_race_predictions"},
"b": {
"desc": f"Get hill score from '{config.week_start.isoformat()}' to '{config.today.isoformat()}'",
"key": "get_hill_score",
},
"c": {
"desc": f"Get endurance score from '{config.week_start.isoformat()}' to '{config.today.isoformat()}'",
"key": "get_endurance_score",
},
"d": {"desc": "Get available badges", "key": "get_available_badges"},
"e": {"desc": "Get badges in progress", "key": "get_in_progress_badges"},
},
},
"8": {
"name": "⌚ Device & Technical",
"options": {
"1": {"desc": "Get all device information", "key": "get_devices"},
"2": {"desc": "Get device alarms", "key": "get_device_alarms"},
"3": {"desc": "Get solar data from your devices", "key": "get_solar_data"},
"4": {
"desc": f"Request data reload (epoch) for '{config.today.isoformat()}'",
"key": "request_reload",
},
"5": {"desc": "Get device settings", "key": "get_device_settings"},
"6": {"desc": "Get device last used", "key": "get_device_last_used"},
"7": {
"desc": "Get primary training device",
"key": "get_primary_training_device",
},
},
},
"9": {
"name": "🎽 Gear & Equipment",
"options": {
"1": {"desc": "Get user gear list", "key": "get_gear"},
"2": {"desc": "Get gear defaults", "key": "get_gear_defaults"},
"3": {"desc": "Get gear statistics", "key": "get_gear_stats"},
"4": {"desc": "Get gear activities", "key": "get_gear_activities"},
"5": {"desc": "Set gear default", "key": "set_gear_default"},
"6": {
"desc": "Track gear usage (total time used)",
"key": "track_gear_usage",
},
},
},
"0": {
"name": "💧 Hydration & Wellness",
"options": {
"1": {
"desc": f"Get hydration data for '{config.today.isoformat()}'",
"key": "get_hydration_data",
},
"2": {"desc": "Add hydration data", "key": "add_hydration_data"},
"3": {
"desc": "Set blood pressure and pulse (interactive)",
"key": "set_blood_pressure",
},
"4": {"desc": "Get pregnancy summary data", "key": "get_pregnancy_summary"},
"5": {
"desc": f"Get all day events for '{config.week_start.isoformat()}'",
"key": "get_all_day_events",
},
"6": {
"desc": f"Get body battery events for '{config.week_start.isoformat()}'",
"key": "get_body_battery_events",
},
"7": {
"desc": f"Get menstrual data for '{config.today.isoformat()}'",
"key": "get_menstrual_data_for_date",
},
"8": {
"desc": f"Get menstrual calendar from '{config.week_start.isoformat()}' to '{config.today.isoformat()}'",
"key": "get_menstrual_calendar_data",
},
"9": {
"desc": "Delete blood pressure entry",
"key": "delete_blood_pressure",
},
},
},
"a": {
"name": "🔧 System & Export",
"options": {
"1": {"desc": "Create sample health report", "key": "create_health_report"},
"2": {
"desc": "Remove stored login tokens (logout)",
"key": "remove_tokens",
},
"3": {"desc": "Disconnect from Garmin Connect", "key": "disconnect"},
"4": {"desc": "Execute GraphQL query", "key": "query_garmin_graphql"},
},
},
}
current_category = None
def print_main_menu():
"""Print the main category menu."""
print("\n" + "=" * 50)
print("🚴 Full-blown Garmin Connect API Demo - Main Menu")
print("=" * 50)
print("Select a category:")
print()
for key, category in menu_categories.items():
print(f" [{key}] {category['name']}")
print()
print(" [q] Exit program")
print()
print("Make your selection: ", end="", flush=True)
def print_category_menu(category_key: str):
"""Print options for a specific category."""
if category_key not in menu_categories:
return False
category = menu_categories[category_key]
print(f"\n📋 #{category_key} {category['name']} - Options")
print("-" * 40)
for key, option in category["options"].items():
print(f" [{key}] {option['desc']}")
print()
print(" [q] Back to main menu")
print()
print("Make your selection: ", end="", flush=True)
return True
def get_mfa() -> str:
"""Get MFA token."""
return input("MFA one-time code: ")
class DataExporter:
"""Utilities for exporting data in various formats."""
@staticmethod
def save_json(data: Any, filename: str, pretty: bool = True) -> str:
"""Save data as JSON file."""
filepath = config.export_dir / f"{filename}.json"
with open(filepath, "w", encoding="utf-8") as f:
if pretty:
json.dump(data, f, indent=4, default=str, ensure_ascii=False)
else:
json.dump(data, f, default=str, ensure_ascii=False)
return str(filepath)
@staticmethod
def create_health_report(api_instance: Garmin) -> str:
"""Create a comprehensive health report in JSON and HTML formats."""
report_data = {
"generated_at": datetime.datetime.now().isoformat(),
"user_info": {"full_name": "N/A", "unit_system": "N/A"},
"today_summary": {},
"recent_activities": [],
"health_metrics": {},
"weekly_data": [],
"device_info": [],
}
try:
# Basic user info
report_data["user_info"]["full_name"] = (
api_instance.get_full_name() or "N/A"
)
report_data["user_info"]["unit_system"] = (
api_instance.get_unit_system() or "N/A"
)
# Today's summary
today_str = config.today.isoformat()
report_data["today_summary"] = api_instance.get_user_summary(today_str)
# Recent activities
recent_activities = api_instance.get_activities(0, 10)
report_data["recent_activities"] = recent_activities or []
# Weekly data for trends
for i in range(7):
date = config.today - datetime.timedelta(days=i)
try:
daily_data = api_instance.get_user_summary(date.isoformat())
if daily_data:
daily_data["date"] = date.isoformat()
report_data["weekly_data"].append(daily_data)
except Exception as e:
print(
f"Skipping data for {date.isoformat()}: {e}"
) # Skip if data not available
# Health metrics for today
health_metrics = {}
metrics_to_fetch = [
("heart_rate", lambda: api_instance.get_heart_rates(today_str)),
("steps", lambda: api_instance.get_steps_data(today_str)),
("sleep", lambda: api_instance.get_sleep_data(today_str)),
("stress", lambda: api_instance.get_all_day_stress(today_str)),
(
"body_battery",
lambda: api_instance.get_body_battery(
config.week_start.isoformat(), today_str
),
),
]
for metric_name, fetch_func in metrics_to_fetch:
try:
health_metrics[metric_name] = fetch_func()
except Exception:
health_metrics[metric_name] = None
report_data["health_metrics"] = health_metrics
# Device information
try:
report_data["device_info"] = api_instance.get_devices()
except Exception:
report_data["device_info"] = []
except Exception as e:
print(f"Error creating health report: {e}")
# Create HTML version
html_filepath = DataExporter.create_readable_health_report(report_data)
print(f"📊 Report created: {html_filepath}")
return html_filepath
@staticmethod
def create_readable_health_report(report_data: dict) -> str:
"""Create a readable HTML report from comprehensive health data."""
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
html_filename = f"health_report_{timestamp}.html"
# Extract key information
user_name = report_data.get("user_info", {}).get("full_name", "Unknown User")
generated_at = report_data.get("generated_at", "Unknown")
# Create HTML content with complete styling
html_content = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Garmin Health Report - {user_name}</title>
<style>
body {{
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
margin: 0;
padding: 20px;
background-color: #f5f5f5;
color: #333;
}}
.container {{
max-width: 1200px;
margin: 0 auto;
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}}
.header {{
text-align: center;
border-bottom: 3px solid #007ACC;
padding-bottom: 20px;
margin-bottom: 30px;
}}
.header h1 {{
color: #007ACC;
margin: 0;
font-size: 2.5em;
}}
.meta-info {{
background: #f8f9fa;
padding: 15px;
border-radius: 5px;
margin-bottom: 30px;
}}
.section {{
margin-bottom: 40px;
}}
.section h2 {{
color: #007ACC;
border-bottom: 2px solid #007ACC;
padding-bottom: 10px;
margin-bottom: 20px;
}}
.metric-grid {{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
margin-bottom: 20px;
}}
.metric-card {{
background: #f8f9fa;
padding: 20px;
border-radius: 8px;
border-left: 4px solid #007ACC;
}}
.metric-card h4 {{
margin: 0 0 10px 0;
color: #007ACC;
font-size: 1.1em;
}}
.metric-value {{
font-size: 1.5em;
font-weight: bold;
color: #333;
}}
.metric-unit {{
color: #666;
font-size: 0.9em;
}}
.activity-item {{
background: #f8f9fa;
padding: 15px;
margin-bottom: 10px;
border-radius: 5px;
border-left: 4px solid #28a745;
}}
.activity-item h4 {{
margin: 0 0 10px 0;
color: #28a745;
}}
.activity-details {{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 10px;
font-size: 0.9em;
}}
.no-data {{
color: #666;
font-style: italic;
text-align: center;
padding: 20px;
background: #f8f9fa;
border-radius: 5px;
}}
.footer {{
text-align: center;
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #ddd;
color: #666;
font-size: 0.9em;
}}
@media print {{
body {{ background: white; }}
.container {{ box-shadow: none; }}
}}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🏃 Garmin Health Report</h1>
<p><strong>{user_name}</strong></p>
</div>
<div class="meta-info">
<p><strong>Generated:</strong> {generated_at}</p>
<p><strong>Date:</strong> {config.today.isoformat()}</p>
</div>
"""
# Today's Summary Section
today_summary = report_data.get("today_summary", {})
if today_summary:
steps = today_summary.get("totalSteps", 0)
calories = today_summary.get("totalKilocalories", 0)
distance = (
round(today_summary.get("totalDistanceMeters", 0) / 1000, 2)
if today_summary.get("totalDistanceMeters")
else 0
)
active_calories = today_summary.get("activeKilocalories", 0)
html_content += f"""
<div class="section">
<h2>📈 Today's Activity Summary</h2>
<div class="metric-grid">
<div class="metric-card">
<h4>👟 Steps</h4>
<div class="metric-value">{steps:,} <span class="metric-unit">steps</span></div>
</div>
<div class="metric-card">
<h4>🔥 Calories</h4>
<div class="metric-value">{calories:,} <span class="metric-unit">total</span></div>
<div style="margin-top: 10px;">{active_calories:,} active</div>
</div>
<div class="metric-card">
<h4>📏 Distance</h4>
<div class="metric-value">{distance} <span class="metric-unit">km</span></div>
</div>
</div>
</div>
"""
else:
html_content += """
<div class="section">
<h2>📈 Today's Activity Summary</h2>
<div class="no-data">No activity data available for today</div>
</div>
"""
# Health Metrics Section
health_metrics = report_data.get("health_metrics", {})
if health_metrics and any(health_metrics.values()):
html_content += """
<div class="section">
<h2>❤️ Health Metrics</h2>
<div class="metric-grid">
"""
# Heart Rate
heart_rate = health_metrics.get("heart_rate", {})
if heart_rate and isinstance(heart_rate, dict):
resting_hr = heart_rate.get("restingHeartRate", "N/A")
max_hr = heart_rate.get("maxHeartRate", "N/A")
html_content += f"""
<div class="metric-card">
<h4>💓 Heart Rate</h4>
<div class="metric-value">{resting_hr} <span class="metric-unit">bpm (resting)</span></div>
<div style="margin-top: 10px;">Max: {max_hr} bpm</div>
</div>
"""
# Sleep Data
sleep_data = health_metrics.get("sleep", {})
if (
sleep_data
and isinstance(sleep_data, dict)
and "dailySleepDTO" in sleep_data
):
sleep_seconds = sleep_data["dailySleepDTO"].get("sleepTimeSeconds", 0)
sleep_hours = round(sleep_seconds / 3600, 1) if sleep_seconds else 0
deep_sleep = sleep_data["dailySleepDTO"].get("deepSleepSeconds", 0)
deep_hours = round(deep_sleep / 3600, 1) if deep_sleep else 0
html_content += f"""
<div class="metric-card">
<h4>😴 Sleep</h4>
<div class="metric-value">{sleep_hours} <span class="metric-unit">hours</span></div>
<div style="margin-top: 10px;">Deep Sleep: {deep_hours} hours</div>
</div>
"""
# Steps
steps_data = health_metrics.get("steps", {})
if steps_data and isinstance(steps_data, dict):
total_steps = steps_data.get("totalSteps", 0)
goal = steps_data.get("dailyStepGoal", 10000)
html_content += f"""
<div class="metric-card">
<h4>🎯 Step Goal</h4>
<div class="metric-value">{total_steps:,} <span class="metric-unit">of {goal:,}</span></div>
<div style="margin-top: 10px;">Goal: {round((total_steps/goal)*100) if goal else 0}%</div>
</div>
"""
# Stress Data
stress_data = health_metrics.get("stress", {})
if stress_data and isinstance(stress_data, dict):
avg_stress = stress_data.get("avgStressLevel", "N/A")
max_stress = stress_data.get("maxStressLevel", "N/A")
html_content += f"""
<div class="metric-card">
<h4>😰 Stress Level</h4>
<div class="metric-value">{avg_stress} <span class="metric-unit">avg</span></div>
<div style="margin-top: 10px;">Max: {max_stress}</div>
</div>
"""
# Body Battery
body_battery = health_metrics.get("body_battery", [])
if body_battery and isinstance(body_battery, list) and body_battery:
latest_bb = body_battery[-1] if body_battery else {}
charged = latest_bb.get("charged", "N/A")
drained = latest_bb.get("drained", "N/A")
html_content += f"""
<div class="metric-card">
<h4>🔋 Body Battery</h4>
<div class="metric-value">+{charged} <span class="metric-unit">charged</span></div>
<div style="margin-top: 10px;">-{drained} drained</div>
</div>
"""
html_content += " </div>\n </div>\n"
else:
html_content += """
<div class="section">
<h2>❤️ Health Metrics</h2>
<div class="no-data">No health metrics data available</div>
</div>
"""
# Weekly Trends Section
weekly_data = report_data.get("weekly_data", [])
if weekly_data:
html_content += """
<div class="section">
<h2>📊 Weekly Trends (Last 7 Days)</h2>
<div class="metric-grid">
"""
for daily in weekly_data[:7]: # Show last 7 days
date = daily.get("date", "Unknown")
steps = daily.get("totalSteps", 0)
calories = daily.get("totalKilocalories", 0)
distance = (
round(daily.get("totalDistanceMeters", 0) / 1000, 2)
if daily.get("totalDistanceMeters")
else 0
)
html_content += f"""
<div class="metric-card">
<h4>📅 {date}</h4>
<div class="metric-value">{steps:,} <span class="metric-unit">steps</span></div>
<div style="margin-top: 10px;">
<div>{calories:,} kcal</div>
<div>{distance} km</div>
</div>
</div>
"""
html_content += " </div>\n </div>\n"
# Recent Activities Section
activities = report_data.get("recent_activities", [])
if activities:
html_content += """
<div class="section">
<h2>🏃 Recent Activities</h2>
"""
for activity in activities[:5]: # Show last 5 activities
name = activity.get("activityName", "Unknown Activity")
activity_type = activity.get("activityType", {}).get(
"typeKey", "Unknown"
)
date = (
activity.get("startTimeLocal", "").split("T")[0]
if activity.get("startTimeLocal")
else "Unknown"
)
duration = activity.get("duration", 0)
duration_min = round(duration / 60, 1) if duration else 0
distance = (
round(activity.get("distance", 0) / 1000, 2)
if activity.get("distance")
else 0
)
calories = activity.get("calories", 0)
avg_hr = activity.get("avgHR", 0)
html_content += f"""
<div class="activity-item">
<h4>{name} ({activity_type})</h4>
<div class="activity-details">
<div><strong>Date:</strong> {date}</div>
<div><strong>Duration:</strong> {duration_min} min</div>
<div><strong>Distance:</strong> {distance} km</div>
<div><strong>Calories:</strong> {calories}</div>
<div><strong>Avg HR:</strong> {avg_hr} bpm</div>
</div>
</div>
"""
html_content += " </div>\n"
else:
html_content += """
<div class="section">
<h2>🏃 Recent Activities</h2>
<div class="no-data">No recent activities found</div>
</div>
"""
# Device Information
device_info = report_data.get("device_info", [])
if device_info:
html_content += """
<div class="section">
<h2>⌚ Device Information</h2>
<div class="metric-grid">
"""
for device in device_info:
device_name = device.get("displayName", "Unknown Device")
model = device.get("productDisplayName", "Unknown Model")
version = device.get("softwareVersion", "Unknown")
html_content += f"""
<div class="metric-card">
<h4>{device_name}</h4>
<div><strong>Model:</strong> {model}</div>
<div><strong>Software:</strong> {version}</div>
</div>
"""
html_content += " </div>\n </div>\n"
# Footer
html_content += f"""
<div class="footer">
<p>Generated by Garmin Connect API Demo on {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
<p>This report is for informational purposes only. Consult healthcare professionals for medical advice.</p>
</div>
</div>
</body>
</html>
"""
# Save HTML file
html_filepath = config.export_dir / html_filename
with open(html_filepath, "w", encoding="utf-8") as f:
f.write(html_content)
return str(html_filepath)
def safe_api_call(api_method, *args, method_name: str = None, **kwargs):
"""
Centralized API call wrapper with comprehensive error handling.
This function provides unified error handling for all Garmin Connect API calls.
It handles common HTTP errors (400, 401, 403, 404, 429, 500, 503) with
user-friendly messages and provides consistent error reporting.
Usage:
success, result, error_msg = safe_api_call(api.get_user_summary)
Args:
api_method: The API method to call
*args: Positional arguments for the API method
method_name: Human-readable name for the API method (optional)
**kwargs: Keyword arguments for the API method
Returns:
tuple: (success: bool, result: Any, error_message: str|None)
"""
if method_name is None:
method_name = getattr(api_method, "__name__", str(api_method))
try:
result = api_method(*args, **kwargs)
return True, result, None
except GarthHTTPError as e:
# Handle specific HTTP errors more gracefully
error_str = str(e)
# Extract status code more reliably
status_code = None
if hasattr(e, "response") and hasattr(e.response, "status_code"):
status_code = e.response.status_code
# Handle specific status codes
if status_code == 400 or ("400" in error_str and "Bad Request" in error_str):
error_msg = "Endpoint not available (400 Bad Request) - This feature may not be enabled for your account or region"
# Don't print for 400 errors as they're often expected for unavailable features
elif status_code == 401 or "401" in error_str:
error_msg = (
"Authentication required (401 Unauthorized) - Please re-authenticate"
)
print(f"⚠️ {method_name} failed: {error_msg}")
elif status_code == 403 or "403" in error_str:
error_msg = "Access denied (403 Forbidden) - Your account may not have permission for this feature"
print(f"⚠️ {method_name} failed: {error_msg}")
elif status_code == 404 or "404" in error_str:
error_msg = (
"Endpoint not found (404) - This feature may have been moved or removed"
)
print(f"⚠️ {method_name} failed: {error_msg}")