forked from cyberjunky/python-garminconnect
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
2226 lines (1790 loc) · 84.5 KB
/
__init__.py
File metadata and controls
2226 lines (1790 loc) · 84.5 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
"""Python 3 API wrapper for Garmin Connect."""
import logging
import numbers
import os
import re
from collections.abc import Callable
from datetime import date, datetime, timezone
from enum import Enum, auto
from pathlib import Path
from typing import Any
import garth
import requests
from garth.exc import GarthException, GarthHTTPError
from requests import HTTPError
from .fit import FitEncoderWeight # type: ignore
logger = logging.getLogger(__name__)
# Constants for validation
MAX_ACTIVITY_LIMIT = 1000
MAX_HYDRATION_ML = 10000 # 10 liters
DATE_FORMAT_REGEX = r"^\d{4}-\d{2}-\d{2}$"
DATE_FORMAT_STR = "%Y-%m-%d"
VALID_WEIGHT_UNITS = {"kg", "lbs"}
# Add validation utilities
def _validate_date_format(date_str: str, param_name: str = "date") -> str:
"""Validate date string format YYYY-MM-DD."""
if not isinstance(date_str, str):
raise ValueError(f"{param_name} must be a string")
# Remove any extra whitespace
date_str = date_str.strip()
if not re.fullmatch(DATE_FORMAT_REGEX, date_str):
raise ValueError(
f"{param_name} must be in format 'YYYY-MM-DD', got: {date_str}"
)
try:
# Validate that it's a real date
datetime.strptime(date_str, DATE_FORMAT_STR)
except ValueError as e:
raise ValueError(f"invalid {param_name}: {e}") from e
return date_str
def _validate_positive_number(
value: int | float, param_name: str = "value"
) -> int | float:
"""Validate that a number is positive."""
if not isinstance(value, numbers.Real):
raise ValueError(f"{param_name} must be a number")
if isinstance(value, bool):
raise ValueError(f"{param_name} must be a number, not bool")
if value <= 0:
raise ValueError(f"{param_name} must be positive, got: {value}")
return value
def _validate_non_negative_integer(value: int, param_name: str = "value") -> int:
"""Validate that a value is a non-negative integer."""
if not isinstance(value, int) or isinstance(value, bool):
raise ValueError(f"{param_name} must be an integer")
if value < 0:
raise ValueError(f"{param_name} must be non-negative, got: {value}")
return value
def _validate_positive_integer(value: int, param_name: str = "value") -> int:
"""Validate that a value is a positive integer."""
if not isinstance(value, int) or isinstance(value, bool):
raise ValueError(f"{param_name} must be an integer")
if value <= 0:
raise ValueError(f"{param_name} must be a positive integer, got: {value}")
return value
def _fmt_ts(dt: datetime) -> str:
# Use ms precision to match server expectations
return dt.replace(tzinfo=None).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3]
class Garmin:
"""Class for fetching data from Garmin Connect."""
def __init__(
self,
email: str | None = None,
password: str | None = None,
is_cn: bool = False,
prompt_mfa: Callable[[], str] | None = None,
return_on_mfa: bool = False,
) -> None:
"""Create a new class instance."""
# Validate input types
if email is not None and not isinstance(email, str):
raise ValueError("email must be a string or None")
if password is not None and not isinstance(password, str):
raise ValueError("password must be a string or None")
if not isinstance(is_cn, bool):
raise ValueError("is_cn must be a boolean")
if not isinstance(return_on_mfa, bool):
raise ValueError("return_on_mfa must be a boolean")
self.username = email
self.password = password
self.is_cn = is_cn
self.prompt_mfa = prompt_mfa
self.return_on_mfa = return_on_mfa
self.garmin_connect_user_settings_url = (
"/userprofile-service/userprofile/user-settings"
)
self.garmin_connect_userprofile_settings_url = (
"/userprofile-service/userprofile/settings"
)
self.garmin_connect_devices_url = "/device-service/deviceregistration/devices"
self.garmin_connect_device_url = "/device-service/deviceservice"
self.garmin_connect_primary_device_url = (
"/web-gateway/device-info/primary-training-device"
)
self.garmin_connect_solar_url = "/web-gateway/solar"
self.garmin_connect_weight_url = "/weight-service"
self.garmin_connect_daily_summary_url = "/usersummary-service/usersummary/daily"
self.garmin_connect_metrics_url = "/metrics-service/metrics/maxmet/daily"
self.garmin_connect_biometric_url = "/biometric-service/biometric"
self.garmin_connect_biometric_stats_url = "/biometric-service/stats"
self.garmin_connect_daily_hydration_url = (
"/usersummary-service/usersummary/hydration/daily"
)
self.garmin_connect_set_hydration_url = (
"/usersummary-service/usersummary/hydration/log"
)
self.garmin_connect_daily_stats_steps_url = (
"/usersummary-service/stats/steps/daily"
)
self.garmin_connect_personal_record_url = (
"/personalrecord-service/personalrecord/prs"
)
self.garmin_connect_earned_badges_url = "/badge-service/badge/earned"
self.garmin_connect_available_badges_url = "/badge-service/badge/available"
self.garmin_connect_adhoc_challenges_url = (
"/adhocchallenge-service/adHocChallenge/historical"
)
self.garmin_connect_badge_challenges_url = (
"/badgechallenge-service/badgeChallenge/completed"
)
self.garmin_connect_available_badge_challenges_url = (
"/badgechallenge-service/badgeChallenge/available"
)
self.garmin_connect_non_completed_badge_challenges_url = (
"/badgechallenge-service/badgeChallenge/non-completed"
)
self.garmin_connect_inprogress_virtual_challenges_url = (
"/badgechallenge-service/virtualChallenge/inProgress"
)
self.garmin_connect_daily_sleep_url = (
"/wellness-service/wellness/dailySleepData"
)
self.garmin_connect_daily_stress_url = "/wellness-service/wellness/dailyStress"
self.garmin_connect_hill_score_url = "/metrics-service/metrics/hillscore"
self.garmin_connect_daily_body_battery_url = (
"/wellness-service/wellness/bodyBattery/reports/daily"
)
self.garmin_connect_body_battery_events_url = (
"/wellness-service/wellness/bodyBattery/events"
)
self.garmin_connect_blood_pressure_endpoint = (
"/bloodpressure-service/bloodpressure/range"
)
self.garmin_connect_set_blood_pressure_endpoint = (
"/bloodpressure-service/bloodpressure"
)
self.garmin_connect_endurance_score_url = (
"/metrics-service/metrics/endurancescore"
)
self.garmin_connect_menstrual_calendar_url = (
"/periodichealth-service/menstrualcycle/calendar"
)
self.garmin_connect_menstrual_dayview_url = (
"/periodichealth-service/menstrualcycle/dayview"
)
self.garmin_connect_pregnancy_snapshot_url = (
"/periodichealth-service/menstrualcycle/pregnancysnapshot"
)
self.garmin_connect_goals_url = "/goal-service/goal/goals"
self.garmin_connect_rhr_url = "/userstats-service/wellness/daily"
self.garmin_connect_hrv_url = "/hrv-service/hrv"
self.garmin_connect_training_readiness_url = (
"/metrics-service/metrics/trainingreadiness"
)
self.garmin_connect_race_predictor_url = (
"/metrics-service/metrics/racepredictions"
)
self.garmin_connect_training_status_url = (
"/metrics-service/metrics/trainingstatus/aggregated"
)
self.garmin_connect_user_summary_chart = (
"/wellness-service/wellness/dailySummaryChart"
)
self.garmin_connect_floors_chart_daily_url = (
"/wellness-service/wellness/floorsChartData/daily"
)
self.garmin_connect_heartrates_daily_url = (
"/wellness-service/wellness/dailyHeartRate"
)
self.garmin_connect_daily_respiration_url = (
"/wellness-service/wellness/daily/respiration"
)
self.garmin_connect_daily_spo2_url = "/wellness-service/wellness/daily/spo2"
self.garmin_connect_daily_intensity_minutes = (
"/wellness-service/wellness/daily/im"
)
self.garmin_daily_events_url = "/wellness-service/wellness/dailyEvents"
self.garmin_connect_activities = (
"/activitylist-service/activities/search/activities"
)
self.garmin_connect_activities_baseurl = "/activitylist-service/activities/"
self.garmin_connect_activity = "/activity-service/activity"
self.garmin_connect_activity_types = "/activity-service/activity/activityTypes"
self.garmin_connect_activity_fordate = "/mobile-gateway/heartRate/forDate"
self.garmin_connect_fitnessstats = "/fitnessstats-service/activity"
self.garmin_connect_fitnessage = "/fitnessage-service/fitnessage"
self.garmin_connect_fit_download = "/download-service/files/activity"
self.garmin_connect_tcx_download = "/download-service/export/tcx/activity"
self.garmin_connect_gpx_download = "/download-service/export/gpx/activity"
self.garmin_connect_kml_download = "/download-service/export/kml/activity"
self.garmin_connect_csv_download = "/download-service/export/csv/activity"
self.garmin_connect_upload = "/upload-service/upload"
self.garmin_connect_gear = "/gear-service/gear/filterGear"
self.garmin_connect_gear_baseurl = "/gear-service/gear"
self.garmin_request_reload_url = "/wellness-service/wellness/epoch/request"
self.garmin_workouts = "/workout-service"
self.garmin_connect_delete_activity_url = "/activity-service/activity"
self.garmin_graphql_endpoint = "graphql-gateway/graphql"
self.garth = garth.Client(
domain="garmin.cn" if is_cn else "garmin.com",
pool_connections=20,
pool_maxsize=20,
)
self.display_name = None
self.full_name = None
self.unit_system = None
def connectapi(self, path: str, **kwargs: Any) -> Any:
"""Wrapper for garth connectapi with error handling."""
try:
return self.garth.connectapi(path, **kwargs)
except (HTTPError, GarthHTTPError) as e:
# For GarthHTTPError, extract status from the wrapped HTTPError
if isinstance(e, GarthHTTPError):
status = getattr(
getattr(e.error, "response", None), "status_code", None
)
else:
status = getattr(getattr(e, "response", None), "status_code", None)
logger.error(
"API call failed for path '%s': %s (status=%s)", path, e, status
)
if status == 401:
raise GarminConnectAuthenticationError(
f"Authentication failed: {e}"
) from e
elif status == 429:
raise GarminConnectTooManyRequestsError(
f"Rate limit exceeded: {e}"
) from e
elif status and 400 <= status < 500:
# Client errors (400-499) - API endpoint issues, bad parameters, etc.
raise GarminConnectConnectionError(
f"API client error ({status}): {e}"
) from e
else:
raise GarminConnectConnectionError(f"HTTP error: {e}") from e
except Exception as e:
logger.exception("Connection error during connectapi path=%s", path)
raise GarminConnectConnectionError(f"Connection error: {e}") from e
def download(self, path: str, **kwargs: Any) -> Any:
"""Wrapper for garth download with error handling."""
try:
return self.garth.download(path, **kwargs)
except (HTTPError, GarthHTTPError) as e:
# For GarthHTTPError, extract status from the wrapped HTTPError
if isinstance(e, GarthHTTPError):
status = getattr(
getattr(e.error, "response", None), "status_code", None
)
else:
status = getattr(getattr(e, "response", None), "status_code", None)
logger.exception("Download failed for path '%s' (status=%s)", path, status)
if status == 401:
raise GarminConnectAuthenticationError(f"Download error: {e}") from e
elif status == 429:
raise GarminConnectTooManyRequestsError(f"Download error: {e}") from e
elif status and 400 <= status < 500:
# Client errors (400-499) - API endpoint issues, bad parameters, etc.
raise GarminConnectConnectionError(
f"Download client error ({status}): {e}"
) from e
else:
raise GarminConnectConnectionError(f"Download error: {e}") from e
except Exception as e:
logger.exception("Download failed for path '%s'", path)
raise GarminConnectConnectionError(f"Download error: {e}") from e
def login(self, /, tokenstore: str | None = None) -> tuple[str | None, str | None]:
"""
Log in using Garth.
Returns:
Tuple[str | None, str | None]: (access_token, refresh_token) when using credential flow;
(None, None) when loading from tokenstore.
"""
tokenstore = tokenstore or os.getenv("GARMINTOKENS")
try:
token1 = None
token2 = None
if tokenstore:
if len(tokenstore) > 512:
self.garth.loads(tokenstore)
else:
self.garth.load(tokenstore)
else:
# Validate credentials before attempting login
if not self.username or not self.password:
raise GarminConnectAuthenticationError(
"Username and password are required"
)
# Validate email format when actually used for login
if not self.is_cn and self.username and "@" not in self.username:
raise GarminConnectAuthenticationError(
"Email must contain '@' symbol"
)
if self.return_on_mfa:
token1, token2 = self.garth.login(
self.username,
self.password,
return_on_mfa=self.return_on_mfa,
)
# In MFA early-return mode, profile/settings are not loaded yet
return token1, token2
else:
token1, token2 = self.garth.login(
self.username,
self.password,
prompt_mfa=self.prompt_mfa,
)
# Continue to load profile/settings below
# Ensure profile is loaded (tokenstore path may not populate it)
if not getattr(self.garth, "profile", None):
try:
prof = self.garth.connectapi(
"/userprofile-service/userprofile/profile"
)
except Exception as e:
raise GarminConnectAuthenticationError(
"Failed to retrieve profile"
) from e
if not prof or "displayName" not in prof:
raise GarminConnectAuthenticationError("Invalid profile data found")
# Use profile data directly since garth.profile is read-only
self.display_name = prof.get("displayName")
self.full_name = prof.get("fullName")
else:
self.display_name = self.garth.profile.get("displayName")
self.full_name = self.garth.profile.get("fullName")
settings = self.garth.connectapi(self.garmin_connect_user_settings_url)
if not settings:
raise GarminConnectAuthenticationError(
"Failed to retrieve user settings"
)
if "userData" not in settings:
raise GarminConnectAuthenticationError("Invalid user settings found")
self.unit_system = settings["userData"].get("measurementSystem")
return token1, token2
except (HTTPError, requests.exceptions.HTTPError, GarthException) as e:
status = getattr(getattr(e, "response", None), "status_code", None)
logger.error("Login failed: %s (status=%s)", e, status)
# Check status code first
if status == 401:
raise GarminConnectAuthenticationError(
f"Authentication failed: {e}"
) from e
elif status == 429:
raise GarminConnectTooManyRequestsError(
f"Rate limit exceeded: {e}"
) from e
# If no status code, check error message for authentication indicators
error_str = str(e).lower()
auth_indicators = ["401", "unauthorized", "authentication failed"]
if any(indicator in error_str for indicator in auth_indicators):
raise GarminConnectAuthenticationError(
f"Authentication failed: {e}"
) from e
# Default to connection error
raise GarminConnectConnectionError(f"Login failed: {e}") from e
except FileNotFoundError:
# Let FileNotFoundError pass through - this is expected when no tokens exist
raise
except Exception as e:
if isinstance(e, GarminConnectAuthenticationError):
raise
# Check if this is an authentication error based on the error message
error_str = str(
e
).lower() # Convert to lowercase for case-insensitive matching
auth_indicators = ["401", "unauthorized", "authentication", "login failed"]
is_auth_error = any(indicator in error_str for indicator in auth_indicators)
if is_auth_error:
raise GarminConnectAuthenticationError(
f"Authentication failed: {e}"
) from e
logger.exception("Login failed")
raise GarminConnectConnectionError(f"Login failed: {e}") from e
def resume_login(
self, client_state: dict[str, Any], mfa_code: str
) -> tuple[Any, Any]:
"""Resume login using Garth."""
result1, result2 = self.garth.resume_login(client_state, mfa_code)
if self.garth.profile:
self.display_name = self.garth.profile["displayName"]
self.full_name = self.garth.profile["fullName"]
settings = self.garth.connectapi(self.garmin_connect_user_settings_url)
if settings and "userData" in settings:
self.unit_system = settings["userData"]["measurementSystem"]
return result1, result2
def get_full_name(self) -> str | None:
"""Return full name."""
return self.full_name
def get_unit_system(self) -> str | None:
"""Return unit system."""
return self.unit_system
def get_stats(self, cdate: str) -> dict[str, Any]:
"""
Return user activity summary for 'cdate' format 'YYYY-MM-DD'
(compat for garminconnect).
"""
return self.get_user_summary(cdate)
def get_user_summary(self, cdate: str) -> dict[str, Any]:
"""Return user activity summary for 'cdate' format 'YYYY-MM-DD'."""
# Validate input
cdate = _validate_date_format(cdate, "cdate")
url = f"{self.garmin_connect_daily_summary_url}/{self.display_name}"
params = {"calendarDate": cdate}
logger.debug("Requesting user summary")
response = self.connectapi(url, params=params)
if not response:
raise GarminConnectConnectionError("No data received from server")
if response.get("privacyProtected") is True:
raise GarminConnectAuthenticationError("Authentication error")
return response
def get_steps_data(self, cdate: str) -> list[dict[str, Any]]:
"""Fetch available steps data 'cDate' format 'YYYY-MM-DD'."""
# Validate input
cdate = _validate_date_format(cdate, "cdate")
url = f"{self.garmin_connect_user_summary_chart}/{self.display_name}"
params = {"date": cdate}
logger.debug("Requesting steps data")
response = self.connectapi(url, params=params)
if response is None:
logger.warning("No steps data received")
return []
return response
def get_floors(self, cdate: str) -> dict[str, Any]:
"""Fetch available floors data 'cDate' format 'YYYY-MM-DD'."""
# Validate input
cdate = _validate_date_format(cdate, "cdate")
url = f"{self.garmin_connect_floors_chart_daily_url}/{cdate}"
logger.debug("Requesting floors data")
response = self.connectapi(url)
if response is None:
raise GarminConnectConnectionError("No floors data received")
return response
def get_daily_steps(self, start: str, end: str) -> list[dict[str, Any]]:
"""Fetch available steps data 'start' and 'end' format 'YYYY-MM-DD'."""
# Validate inputs
start = _validate_date_format(start, "start")
end = _validate_date_format(end, "end")
# Validate date range
start_date = datetime.strptime(start, DATE_FORMAT_STR).date()
end_date = datetime.strptime(end, DATE_FORMAT_STR).date()
if start_date > end_date:
raise ValueError("start date cannot be after end date")
url = f"{self.garmin_connect_daily_stats_steps_url}/{start}/{end}"
logger.debug("Requesting daily steps data")
return self.connectapi(url)
def get_heart_rates(self, cdate: str) -> dict[str, Any]:
"""Fetch available heart rates data 'cDate' format 'YYYY-MM-DD'.
Args:
cdate: Date string in format 'YYYY-MM-DD'
Returns:
Dictionary containing heart rate data for the specified date
Raises:
ValueError: If cdate format is invalid
GarminConnectConnectionError: If no data received
GarminConnectAuthenticationError: If authentication fails
"""
# Validate input
cdate = _validate_date_format(cdate, "cdate")
url = f"{self.garmin_connect_heartrates_daily_url}/{self.display_name}"
params = {"date": cdate}
logger.debug("Requesting heart rates")
response = self.connectapi(url, params=params)
if response is None:
raise GarminConnectConnectionError("No heart rate data received")
return response
def get_stats_and_body(self, cdate: str) -> dict[str, Any]:
"""Return activity data and body composition (compat for garminconnect)."""
stats = self.get_stats(cdate)
body = self.get_body_composition(cdate)
body_avg = body.get("totalAverage") or {}
if not isinstance(body_avg, dict):
body_avg = {}
return {**stats, **body_avg}
def get_body_composition(
self, startdate: str, enddate: str | None = None
) -> dict[str, Any]:
"""
Return available body composition data for 'startdate' format
'YYYY-MM-DD' through enddate 'YYYY-MM-DD'.
"""
startdate = _validate_date_format(startdate, "startdate")
enddate = (
startdate if enddate is None else _validate_date_format(enddate, "enddate")
)
if (
datetime.strptime(startdate, DATE_FORMAT_STR).date()
> datetime.strptime(enddate, DATE_FORMAT_STR).date()
):
raise ValueError("startdate cannot be after enddate")
url = f"{self.garmin_connect_weight_url}/weight/dateRange"
params = {"startDate": str(startdate), "endDate": str(enddate)}
logger.debug("Requesting body composition")
return self.connectapi(url, params=params)
def add_body_composition(
self,
timestamp: str | None,
weight: float,
percent_fat: float | None = None,
percent_hydration: float | None = None,
visceral_fat_mass: float | None = None,
bone_mass: float | None = None,
muscle_mass: float | None = None,
basal_met: float | None = None,
active_met: float | None = None,
physique_rating: float | None = None,
metabolic_age: float | None = None,
visceral_fat_rating: float | None = None,
bmi: float | None = None,
) -> dict[str, Any]:
weight = _validate_positive_number(weight, "weight")
dt = datetime.fromisoformat(timestamp) if timestamp else datetime.now()
fitEncoder = FitEncoderWeight()
fitEncoder.write_file_info()
fitEncoder.write_file_creator()
fitEncoder.write_device_info(dt)
fitEncoder.write_weight_scale(
dt,
weight=weight,
percent_fat=percent_fat,
percent_hydration=percent_hydration,
visceral_fat_mass=visceral_fat_mass,
bone_mass=bone_mass,
muscle_mass=muscle_mass,
basal_met=basal_met,
active_met=active_met,
physique_rating=physique_rating,
metabolic_age=metabolic_age,
visceral_fat_rating=visceral_fat_rating,
bmi=bmi,
)
fitEncoder.finish()
url = self.garmin_connect_upload
files = {
"file": ("body_composition.fit", fitEncoder.getvalue()),
}
return self.garth.post("connectapi", url, files=files, api=True).json()
def add_weigh_in(
self, weight: int | float, unitKey: str = "kg", timestamp: str = ""
) -> dict[str, Any]:
"""Add a weigh-in (default to kg)"""
# Validate inputs
weight = _validate_positive_number(weight, "weight")
if unitKey not in VALID_WEIGHT_UNITS:
raise ValueError(f"unitKey must be one of {VALID_WEIGHT_UNITS}")
url = f"{self.garmin_connect_weight_url}/user-weight"
try:
dt = datetime.fromisoformat(timestamp) if timestamp else datetime.now()
except ValueError as e:
raise ValueError(f"invalid timestamp format: {e}") from e
# Apply timezone offset to get UTC/GMT time
dtGMT = dt.astimezone(timezone.utc)
payload = {
"dateTimestamp": _fmt_ts(dt),
"gmtTimestamp": _fmt_ts(dtGMT),
"unitKey": unitKey,
"sourceType": "MANUAL",
"value": weight,
}
logger.debug("Adding weigh-in")
return self.garth.post("connectapi", url, json=payload).json()
def add_weigh_in_with_timestamps(
self,
weight: int | float,
unitKey: str = "kg",
dateTimestamp: str = "",
gmtTimestamp: str = "",
) -> dict[str, Any]:
"""Add a weigh-in with explicit timestamps (default to kg)"""
url = f"{self.garmin_connect_weight_url}/user-weight"
if unitKey not in VALID_WEIGHT_UNITS:
raise ValueError(f"unitKey must be one of {VALID_WEIGHT_UNITS}")
# Make local timestamp timezone-aware
dt = (
datetime.fromisoformat(dateTimestamp).astimezone()
if dateTimestamp
else datetime.now().astimezone()
)
if gmtTimestamp:
g = datetime.fromisoformat(gmtTimestamp)
# Assume provided GMT is UTC if naive; otherwise convert to UTC
if g.tzinfo is None:
g = g.replace(tzinfo=timezone.utc)
dtGMT = g.astimezone(timezone.utc)
else:
dtGMT = dt.astimezone(timezone.utc)
# Validate weight for consistency with add_weigh_in
weight = _validate_positive_number(weight, "weight")
# Build the payload
payload = {
"dateTimestamp": _fmt_ts(dt), # Local time (ms)
"gmtTimestamp": _fmt_ts(dtGMT), # GMT/UTC time (ms)
"unitKey": unitKey,
"sourceType": "MANUAL",
"value": weight,
}
# Debug log for payload
logger.debug("Adding weigh-in with explicit timestamps: %s", payload)
# Make the POST request
return self.garth.post("connectapi", url, json=payload).json()
def get_weigh_ins(self, startdate: str, enddate: str) -> dict[str, Any]:
"""Get weigh-ins between startdate and enddate using format 'YYYY-MM-DD'."""
startdate = _validate_date_format(startdate, "startdate")
enddate = _validate_date_format(enddate, "enddate")
url = f"{self.garmin_connect_weight_url}/weight/range/{startdate}/{enddate}"
params = {"includeAll": True}
logger.debug("Requesting weigh-ins")
return self.connectapi(url, params=params)
def get_daily_weigh_ins(self, cdate: str) -> dict[str, Any]:
"""Get weigh-ins for 'cdate' format 'YYYY-MM-DD'."""
cdate = _validate_date_format(cdate, "cdate")
url = f"{self.garmin_connect_weight_url}/weight/dayview/{cdate}"
params = {"includeAll": True}
logger.debug("Requesting weigh-ins")
return self.connectapi(url, params=params)
def delete_weigh_in(self, weight_pk: str, cdate: str) -> Any:
"""Delete specific weigh-in."""
cdate = _validate_date_format(cdate, "cdate")
url = f"{self.garmin_connect_weight_url}/weight/{cdate}/byversion/{weight_pk}"
logger.debug("Deleting weigh-in")
return self.garth.request(
"DELETE",
"connectapi",
url,
api=True,
)
def delete_weigh_ins(self, cdate: str, delete_all: bool = False) -> int | None:
"""
Delete weigh-in for 'cdate' format 'YYYY-MM-DD'.
Includes option to delete all weigh-ins for that date.
"""
daily_weigh_ins = self.get_daily_weigh_ins(cdate)
weigh_ins = daily_weigh_ins.get("dateWeightList", [])
if not weigh_ins or len(weigh_ins) == 0:
logger.warning(f"No weigh-ins found on {cdate}")
return None
elif len(weigh_ins) > 1:
logger.warning(f"Multiple weigh-ins found for {cdate}")
if not delete_all:
logger.warning(
f"Set delete_all to True to delete all {len(weigh_ins)} weigh-ins"
)
return None
for w in weigh_ins:
self.delete_weigh_in(w["samplePk"], cdate)
return len(weigh_ins)
def get_body_battery(
self, startdate: str, enddate: str | None = None
) -> list[dict[str, Any]]:
"""
Return body battery values by day for 'startdate' format
'YYYY-MM-DD' through enddate 'YYYY-MM-DD'
"""
startdate = _validate_date_format(startdate, "startdate")
if enddate is None:
enddate = startdate
else:
enddate = _validate_date_format(enddate, "enddate")
url = self.garmin_connect_daily_body_battery_url
params = {"startDate": str(startdate), "endDate": str(enddate)}
logger.debug("Requesting body battery data")
return self.connectapi(url, params=params)
def get_body_battery_events(self, cdate: str) -> list[dict[str, Any]]:
"""
Return body battery events for date 'cdate' format 'YYYY-MM-DD'.
The return value is a list of dictionaries, where each dictionary contains event data for a specific event.
Events can include sleep, recorded activities, auto-detected activities, and naps
"""
cdate = _validate_date_format(cdate, "cdate")
url = f"{self.garmin_connect_body_battery_events_url}/{cdate}"
logger.debug("Requesting body battery event data")
return self.connectapi(url)
def set_blood_pressure(
self,
systolic: int,
diastolic: int,
pulse: int,
timestamp: str = "",
notes: str = "",
) -> dict[str, Any]:
"""
Add blood pressure measurement
"""
url = f"{self.garmin_connect_set_blood_pressure_endpoint}"
dt = datetime.fromisoformat(timestamp) if timestamp else datetime.now()
# Apply timezone offset to get UTC/GMT time
dtGMT = dt.astimezone(timezone.utc)
payload = {
"measurementTimestampLocal": _fmt_ts(dt),
"measurementTimestampGMT": _fmt_ts(dtGMT),
"systolic": systolic,
"diastolic": diastolic,
"pulse": pulse,
"sourceType": "MANUAL",
"notes": notes,
}
for name, val, lo, hi in (
("systolic", systolic, 70, 260),
("diastolic", diastolic, 40, 150),
("pulse", pulse, 20, 250),
):
if not isinstance(val, int) or not (lo <= val <= hi):
raise ValueError(f"{name} must be an int in [{lo}, {hi}]")
logger.debug("Adding blood pressure")
return self.garth.post("connectapi", url, json=payload).json()
def get_blood_pressure(
self, startdate: str, enddate: str | None = None
) -> dict[str, Any]:
"""
Returns blood pressure by day for 'startdate' format
'YYYY-MM-DD' through enddate 'YYYY-MM-DD'
"""
startdate = _validate_date_format(startdate, "startdate")
if enddate is None:
enddate = startdate
else:
enddate = _validate_date_format(enddate, "enddate")
url = f"{self.garmin_connect_blood_pressure_endpoint}/{startdate}/{enddate}"
params = {"includeAll": True}
logger.debug("Requesting blood pressure data")
return self.connectapi(url, params=params)
def delete_blood_pressure(self, version: str, cdate: str) -> dict[str, Any]:
"""Delete specific blood pressure measurement."""
url = f"{self.garmin_connect_set_blood_pressure_endpoint}/{cdate}/{version}"
logger.debug("Deleting blood pressure measurement")
return self.garth.request(
"DELETE",
"connectapi",
url,
api=True,
).json()
def get_max_metrics(self, cdate: str) -> dict[str, Any]:
"""Return available max metric data for 'cdate' format 'YYYY-MM-DD'."""
cdate = _validate_date_format(cdate, "cdate")
url = f"{self.garmin_connect_metrics_url}/{cdate}/{cdate}"
logger.debug("Requesting max metrics")
return self.connectapi(url)
def get_lactate_threshold(
self,
*,
latest: bool = True,
start_date: str | date | None = None,
end_date: str | date | None = None,
aggregation: str = "daily",
) -> dict[str, Any]:
"""
Returns Running Lactate Threshold information, including heart rate, power, and speed
:param bool (Required) - latest: Whether to query for the latest Lactate Threshold info or a range. False if querying a range
:param date (Optional) - start_date: The first date in the range to query, format 'YYYY-MM-DD'. Required if `latest` is False. Ignored if `latest` is True
:param date (Optional) - end_date: The last date in the range to query, format 'YYYY-MM-DD'. Defaults to current data. Ignored if `latest` is True
:param str (Optional) - aggregation: How to aggregate the data. Must be one of `daily`, `weekly`, `monthly`, `yearly`.
"""
if latest:
speed_and_heart_rate_url = (
f"{self.garmin_connect_biometric_url}/latestLactateThreshold"
)
power_url = f"{self.garmin_connect_biometric_url}/powerToWeight/latest/{date.today()}?sport=Running"
power = self.connectapi(power_url)
if isinstance(power, list) and power:
power_dict = power[0]
elif isinstance(power, dict):
power_dict = power
else:
power_dict = {}
speed_and_heart_rate = self.connectapi(speed_and_heart_rate_url)
speed_and_heart_rate_dict = {
"userProfilePK": None,
"version": None,
"calendarDate": None,
"sequence": None,
"speed": None,
"heartRate": None,
"heartRateCycling": None,
}
# Garmin /latestLactateThreshold endpoint returns a list of two
# (or more, if cyclingHeartRate ever gets values) nearly identical dicts.
# We're combining them here
for entry in speed_and_heart_rate:
speed = entry.get("speed")
if speed is not None:
speed_and_heart_rate_dict["userProfilePK"] = entry["userProfilePK"]
speed_and_heart_rate_dict["version"] = entry["version"]
speed_and_heart_rate_dict["calendarDate"] = entry["calendarDate"]
speed_and_heart_rate_dict["sequence"] = entry["sequence"]
speed_and_heart_rate_dict["speed"] = speed
# Prefer correct key; fall back to Garmin's historical typo ("hearRate")
hr = entry.get("heartRate") or entry.get("hearRate")
if hr is not None:
speed_and_heart_rate_dict["heartRate"] = hr
# Doesn't exist for me but adding it just in case. We'll check for each entry
hrc = entry.get("heartRateCycling")
if hrc is not None:
speed_and_heart_rate_dict["heartRateCycling"] = hrc
return {
"speed_and_heart_rate": speed_and_heart_rate_dict,
"power": power_dict,
}
if start_date is None:
raise ValueError("you must either specify 'latest=True' or a start_date")
if end_date is None:
end_date = date.today().isoformat()
# Normalize and validate
if isinstance(start_date, date):