-
Notifications
You must be signed in to change notification settings - Fork 32
/
common.py
1052 lines (789 loc) · 29.6 KB
/
common.py
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
"""Common classes and functions."""
from datetime import tzinfo
from enum import Enum, IntEnum
import traceback
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
NamedTuple,
Optional,
Tuple,
Type,
TypeVar,
Union,
cast,
)
import arrow
from arrow import Arrow
from dateutil import tz
from typing_extensions import Final
from .const import (
STATUS_AUTH_FAILED,
STATUS_BAD_STATE,
STATUS_ERROR_OCCURRED,
STATUS_INVALID_PARAMS,
STATUS_SUCCESS,
STATUS_TIMEOUT,
STATUS_TOO_MANY_REQUESTS,
STATUS_UNAUTHORIZED,
)
class SleepModel(IntEnum):
"""Sleep model."""
TRACKER = 16
SLEEP_MONITOR = 32
def new_sleep_model(value: Optional[int]) -> SleepModel:
"""Create enum based on primitive."""
return cast(SleepModel, enum_or_raise(value, SleepModel))
class SleepState(IntEnum):
"""Sleep states."""
AWAKE = 0
LIGHT = 1
DEEP = 2
REM = 3
def new_sleep_state(value: Optional[int]) -> SleepState:
"""Create enum based on primitive."""
return cast(SleepState, enum_or_raise(value, SleepState))
class MeasureGetMeasGroupAttrib(IntEnum):
"""Measure group attributions."""
UNKNOWN = -1
DEVICE_ENTRY_FOR_USER = 0
DEVICE_ENTRY_FOR_USER_AMBIGUOUS = 1
MANUAL_USER_ENTRY = 2
MANUAL_USER_DURING_ACCOUNT_CREATION = 4
MEASURE_AUTO = 5
MEASURE_USER_CONFIRMED = 7
SAME_AS_DEVICE_ENTRY_FOR_USER = 8
def new_measure_group_attrib(value: Optional[int]) -> MeasureGetMeasGroupAttrib:
"""Create enum based on primitive."""
return cast(
MeasureGetMeasGroupAttrib, enum_or_raise(value, MeasureGetMeasGroupAttrib)
)
class MeasureGetMeasGroupCategory(IntEnum):
"""Measure categories."""
REAL = 1
USER_OBJECTIVES = 2
def new_measure_category(value: Optional[int]) -> MeasureGetMeasGroupCategory:
"""Create enum based on primitive."""
return cast(
MeasureGetMeasGroupCategory, enum_or_raise(value, MeasureGetMeasGroupCategory)
)
class MeasureType(IntEnum):
"""Measure types."""
WEIGHT = 1
HEIGHT = 4
FAT_FREE_MASS = 5
FAT_RATIO = 6
FAT_MASS_WEIGHT = 8
DIASTOLIC_BLOOD_PRESSURE = 9
SYSTOLIC_BLOOD_PRESSURE = 10
HEART_RATE = 11
TEMPERATURE = 12
SP02 = 54
BODY_TEMPERATURE = 71
SKIN_TEMPERATURE = 73
MUSCLE_MASS = 76
HYDRATION = 77
BONE_MASS = 88
PULSE_WAVE_VELOCITY = 91
def new_measure_type(value: Optional[int]) -> MeasureType:
"""Create enum based on primitive."""
return cast(MeasureType, enum_or_raise(value, MeasureType))
class NotifyAppli(IntEnum):
"""Data to notify_subscribe to."""
WEIGHT = 1
CIRCULATORY = 4
ACTIVITY = 16
SLEEP = 44
USER = 46
BED_IN = 50
BED_OUT = 51
def new_notify_appli(value: Optional[int]) -> NotifyAppli:
"""Create enum based on primitive."""
return cast(NotifyAppli, enum_or_raise(value, NotifyAppli))
class GetActivityField(Enum):
"""Fields for the getactivity api call."""
STEPS = "steps"
DISTANCE = "distance"
ELEVATION = "elevation"
SOFT = "soft"
MODERATE = "moderate"
INTENSE = "intense"
ACTIVE = "active"
CALORIES = "calories"
TOTAL_CALORIES = "totalcalories"
HR_AVERAGE = "hr_average"
HR_MIN = "hr_min"
HR_MAX = "hr_max"
HR_ZONE_0 = "hr_zone_0"
HR_ZONE_1 = "hr_zone_1"
HR_ZONE_2 = "hr_zone_2"
HR_ZONE_3 = "hr_zone_3"
class GetSleepField(Enum):
"""Fields for getsleep api call."""
HR = "hr"
RR = "rr"
SNORING = "snoring"
class GetSleepSummaryField(Enum):
"""Fields for get sleep summary api call."""
BREATHING_DISTURBANCES_INTENSITY = "breathing_disturbances_intensity"
DEEP_SLEEP_DURATION = "deepsleepduration"
DURATION_TO_SLEEP = "durationtosleep"
DURATION_TO_WAKEUP = "durationtowakeup"
HR_AVERAGE = "hr_average"
HR_MAX = "hr_max"
HR_MIN = "hr_min"
LIGHT_SLEEP_DURATION = "lightsleepduration"
REM_SLEEP_DURATION = "remsleepduration"
RR_AVERAGE = "rr_average"
RR_MAX = "rr_max"
RR_MIN = "rr_min"
SLEEP_SCORE = "sleep_score"
SNORING = "snoring"
SNORING_EPISODE_COUNT = "snoringepisodecount"
WAKEUP_COUNT = "wakeupcount"
WAKEUP_DURATION = "wakeupduration"
class AuthScope(Enum):
"""Authorization scopes."""
USER_INFO = "user.info"
USER_METRICS = "user.metrics"
USER_ACTIVITY = "user.activity"
USER_SLEEP_EVENTS = "user.sleepevents"
class UserGetDeviceDevice(NamedTuple):
"""UserGetDeviceDevice."""
type: str
model: str
battery: str
deviceid: str
timezone: tzinfo
class UserGetDeviceResponse(NamedTuple):
"""UserGetDeviceResponse."""
devices: Tuple[UserGetDeviceDevice, ...]
class SleepGetTimestampValue(NamedTuple):
"""SleepGetTimestampValue."""
timestamp: Arrow
value: int
class SleepGetSerie(NamedTuple):
"""SleepGetSerie."""
enddate: Arrow
startdate: Arrow
state: SleepState
hr: Tuple[SleepGetTimestampValue, ...]
rr: Tuple[SleepGetTimestampValue, ...]
snoring: Tuple[SleepGetTimestampValue, ...]
class SleepGetResponse(NamedTuple):
"""SleepGetResponse."""
model: SleepModel
series: Tuple[SleepGetSerie, ...]
class GetSleepSummaryData(NamedTuple):
"""GetSleepSummaryData."""
breathing_disturbances_intensity: Optional[int]
deepsleepduration: Optional[int]
durationtosleep: Optional[int]
durationtowakeup: Optional[int]
hr_average: Optional[int]
hr_max: Optional[int]
hr_min: Optional[int]
lightsleepduration: Optional[int]
remsleepduration: Optional[int]
rr_average: Optional[int]
rr_max: Optional[int]
rr_min: Optional[int]
sleep_score: Optional[int]
snoring: Optional[int]
snoringepisodecount: Optional[int]
wakeupcount: Optional[int]
wakeupduration: Optional[int]
class GetSleepSummarySerie(NamedTuple):
"""GetSleepSummarySerie."""
timezone: tzinfo
model: SleepModel
startdate: Arrow
enddate: Arrow
date: Arrow
modified: Arrow
data: GetSleepSummaryData
class SleepGetSummaryResponse(NamedTuple):
"""SleepGetSummaryResponse."""
more: bool
offset: int
series: Tuple[GetSleepSummarySerie, ...]
class MeasureGetMeasMeasure(NamedTuple):
"""MeasureGetMeasMeasure."""
type: MeasureType
unit: int
value: int
class MeasureGetMeasGroup(NamedTuple):
"""MeasureGetMeasGroup."""
attrib: MeasureGetMeasGroupAttrib
category: MeasureGetMeasGroupCategory
created: Arrow
date: Arrow
deviceid: Optional[str]
grpid: int
measures: Tuple[MeasureGetMeasMeasure, ...]
class MeasureGetMeasResponse(NamedTuple):
"""MeasureGetMeasResponse."""
measuregrps: Tuple[MeasureGetMeasGroup, ...]
more: Optional[bool]
offset: Optional[int]
timezone: tzinfo
updatetime: Arrow
class MeasureGetActivityActivity(NamedTuple):
"""MeasureGetActivityActivity."""
date: Arrow
timezone: tzinfo
deviceid: Optional[str]
brand: int
is_tracker: bool
steps: Optional[int]
distance: Optional[float]
elevation: Optional[float]
soft: Optional[int]
moderate: Optional[int]
intense: Optional[int]
active: Optional[int]
calories: Optional[float]
totalcalories: float
hr_average: Optional[int]
hr_min: Optional[int]
hr_max: Optional[int]
hr_zone_0: Optional[int]
hr_zone_1: Optional[int]
hr_zone_2: Optional[int]
hr_zone_3: Optional[int]
class MeasureGetActivityResponse(NamedTuple):
"""MeasureGetActivityResponse."""
activities: Tuple[MeasureGetActivityActivity, ...]
more: bool
offset: int
class HeartModel(IntEnum):
"""Heart model."""
BPM_CORE = 44
MOVE_ECG = 91
def new_heart_model(value: Optional[int]) -> HeartModel:
"""Create enum based on primitive."""
return cast(HeartModel, enum_or_raise(value, HeartModel))
class AfibClassification(IntEnum):
"""Atrial fibrillation classification"""
NEGATIVE = 0
POSITIVE = 1
INCONCLUSIVE = 2
def new_afib_classification(value: Optional[int]) -> AfibClassification:
"""Create enum based on primitive."""
return cast(AfibClassification, enum_or_raise(value, AfibClassification))
class HeartWearPosition(IntEnum):
"""Wear position of heart model."""
RIGHT_WRIST = 0
LEFT_WRIST = 1
RIGHT_ARM = 2
LEFT_ARM = 3
RIGHT_FOOT = 4
LEFT_FOOT = 5
def new_heart_wear_position(value: Optional[int]) -> HeartWearPosition:
"""Create enum based on primitive."""
return cast(HeartWearPosition, enum_or_raise(value, HeartWearPosition))
class HeartGetResponse(NamedTuple):
"""HeartGetResponse."""
signal: Tuple[int, ...]
sampling_frequency: int
wearposition: HeartWearPosition
class HeartListECG(NamedTuple):
"""HeartListECG."""
signalid: int
afib: AfibClassification
class HeartBloodPressure(NamedTuple):
"""HeartBloodPressure."""
diastole: int
systole: int
class HeartListSerie(NamedTuple):
"""HeartListSerie"""
ecg: HeartListECG
# blood pressure is optional as not all devices (e.g. Move ECG) collect it
bloodpressure: Optional[HeartBloodPressure]
heart_rate: int
timestamp: Arrow
model: HeartModel
class HeartListResponse(NamedTuple):
"""HeartListResponse."""
more: bool
offset: int
series: Tuple[HeartListSerie, ...]
class Credentials(NamedTuple):
"""Credentials."""
access_token: str
token_expiry: int
token_type: str
refresh_token: str
userid: int
client_id: str
consumer_secret: str
class NotifyListProfile(NamedTuple):
"""NotifyListProfile."""
appli: NotifyAppli
callbackurl: str
expires: Optional[Arrow]
comment: Optional[str]
class NotifyListResponse(NamedTuple):
"""NotifyListResponse."""
profiles: Tuple[NotifyListProfile, ...]
class NotifyGetResponse(NamedTuple):
"""NotifyGetResponse."""
appli: NotifyAppli
callbackurl: str
comment: Optional[str]
GenericType = TypeVar("GenericType")
class UnexpectedTypeException(Exception):
"""Thrown when encountering an unexpected type."""
def __init__(self, value: Any, expected: Type[GenericType]):
"""Initialize."""
super().__init__(
'Expected of "%s" to be "%s" but was "%s."' % (value, expected, type(value))
)
def enforce_type(value: Any, expected: Type[GenericType]) -> GenericType:
"""Enforce a data type."""
if not isinstance(value, expected):
raise UnexpectedTypeException(value, expected)
return value
def value_or_none(
value: Any, convert_fn: Callable[[Any], GenericType]
) -> Union[GenericType, None]:
"""Convert a value given a specific conversion function."""
if value is None:
return None
try:
return convert_fn(value)
except Exception: # pylint: disable=broad-except
return None
def enum_or_raise(value: Optional[Union[str, int]], enum: Type[Enum]) -> Enum:
"""Return Enum or raise exception."""
if value is None:
raise Exception("Received None value for enum %s" % enum)
return enum(value)
def str_or_raise(value: Any) -> str:
"""Return string or raise exception."""
return enforce_type(str_or_none(value), str)
def str_or_none(value: Any) -> Optional[str]:
"""Return str or None."""
return value_or_none(value, str)
def bool_or_raise(value: Any) -> bool:
"""Return bool or raise exception."""
return enforce_type(value, bool)
def bool_or_none(value: Any) -> Optional[bool]:
"""Return bool or None."""
return value_or_none(value, bool)
def int_or_raise(value: Any) -> int:
"""Return int or raise exception."""
return enforce_type(int_or_none(value), int)
def int_or_none(value: Any) -> Optional[int]:
"""Return int or None."""
return value_or_none(value, int)
def float_or_raise(value: Any) -> float:
"""Return float or raise exception."""
return enforce_type(float_or_none(value), float)
def float_or_none(value: Any) -> Optional[float]:
"""Return float or None."""
return value_or_none(value, float)
def arrow_or_none(value: Any) -> Optional[Arrow]:
"""Return Arrow or None."""
if value is None:
return None
return arrow.get(value)
def timezone_or_none(value: Any) -> Optional[tzinfo]:
"""Return tzinfo or None."""
if value is None:
return None
return tz.gettz(value)
def arrow_or_raise(value: Any) -> Arrow:
"""Return Arrow or raise exception."""
return enforce_type(arrow_or_none(value), Arrow)
def timezone_or_raise(value: Any) -> tzinfo:
"""Return tzinfo or raise exception."""
return enforce_type(timezone_or_none(value), tzinfo)
def dict_or_raise(value: Any) -> Dict[Any, Any]:
"""Return dict or raise exception."""
return enforce_type(value, dict)
def dict_or_none(value: Any) -> Optional[Dict[Any, Any]]:
"""Return dict or None."""
return value_or_none(value, dict)
def new_credentials(
client_id: str, consumer_secret: str, data: Dict[str, Any]
) -> Credentials:
"""Create Credentials from config and json."""
return Credentials(
access_token=str_or_raise(data.get("access_token")),
token_expiry=arrow.utcnow().timestamp + data.get("expires_in"),
token_type=str_or_raise(data.get("token_type")),
refresh_token=str_or_raise(data.get("refresh_token")),
userid=int_or_raise(data.get("userid")),
client_id=str_or_raise(client_id),
consumer_secret=str_or_raise(consumer_secret),
)
def new_user_get_device_device(data: dict) -> UserGetDeviceDevice:
"""Create GetDeviceDevice from json."""
return UserGetDeviceDevice(
type=str_or_raise(data.get("type")),
model=str_or_raise(data.get("model")),
battery=str_or_raise(data.get("battery")),
deviceid=str_or_raise(data.get("deviceid")),
timezone=timezone_or_raise(data.get("timezone")),
)
def new_user_get_device_response(data: dict) -> UserGetDeviceResponse:
"""Create GetDeviceResponse from json."""
return UserGetDeviceResponse(
devices=_flexible_tuple_of(data.get("devices", ()), new_user_get_device_device)
)
def new_notify_list_profile(data: dict) -> NotifyListProfile:
"""Create ListSubscriptionProfile from json."""
return NotifyListProfile(
appli=new_notify_appli(data.get("appli")),
callbackurl=str_or_raise(data.get("callbackurl")),
expires=arrow_or_none(data.get("expires")),
comment=str_or_none(data.get("comment")),
)
def new_notify_list_response(data: dict) -> NotifyListResponse:
"""Create NotifyListResponse from json."""
return NotifyListResponse(
profiles=_flexible_tuple_of(data.get("profiles", ()), new_notify_list_profile)
)
def new_notify_get_response(data: dict) -> NotifyGetResponse:
"""Create NotifyGetResponse from json."""
return NotifyGetResponse(
appli=new_notify_appli(data.get("appli")),
callbackurl=str_or_raise(data.get("callbackurl")),
comment=str_or_none(data.get("comment")),
)
def new_sleep_timestamps(
data: Optional[Dict[Any, Any]]
) -> Tuple[SleepGetTimestampValue, ...]:
"""Create SleepTimestamp from json."""
if data is None:
return ()
return tuple(
SleepGetTimestampValue(arrow_or_raise(int(timestamp)), value)
for timestamp, value in data.items()
)
def new_sleep_get_serie(data: dict) -> SleepGetSerie:
"""Create GetSleepSerie from json."""
return SleepGetSerie(
enddate=arrow_or_raise(data.get("enddate")),
startdate=arrow_or_raise(data.get("startdate")),
state=new_sleep_state(data.get("state")),
hr=new_sleep_timestamps(dict_or_none(data.get(GetSleepField.HR.value))),
rr=new_sleep_timestamps(dict_or_none(data.get(GetSleepField.RR.value))),
snoring=new_sleep_timestamps(
dict_or_none(data.get(GetSleepField.SNORING.value))
),
)
def new_sleep_get_response(data: dict) -> SleepGetResponse:
"""Create GetSleepResponse from json."""
return SleepGetResponse(
model=new_sleep_model(data.get("model")),
series=_flexible_tuple_of(data.get("series", ()), new_sleep_get_serie),
)
def new_get_sleep_summary_data(data: dict) -> GetSleepSummaryData:
"""Create GetSleepSummarySerie from json."""
return GetSleepSummaryData(
breathing_disturbances_intensity=int_or_none(
data.get(GetSleepSummaryField.BREATHING_DISTURBANCES_INTENSITY.value)
),
deepsleepduration=int_or_none(
data.get(GetSleepSummaryField.DEEP_SLEEP_DURATION.value)
),
durationtosleep=int_or_none(
data.get(GetSleepSummaryField.DURATION_TO_SLEEP.value)
),
durationtowakeup=int_or_none(
data.get(GetSleepSummaryField.DURATION_TO_WAKEUP.value)
),
hr_average=int_or_none(data.get(GetSleepSummaryField.HR_AVERAGE.value)),
hr_max=int_or_none(data.get(GetSleepSummaryField.HR_MAX.value)),
hr_min=int_or_none(data.get(GetSleepSummaryField.HR_MIN.value)),
lightsleepduration=int_or_none(
data.get(GetSleepSummaryField.LIGHT_SLEEP_DURATION.value)
),
remsleepduration=int_or_none(
data.get(GetSleepSummaryField.REM_SLEEP_DURATION.value)
),
rr_average=int_or_none(data.get(GetSleepSummaryField.RR_AVERAGE.value)),
rr_max=int_or_none(data.get(GetSleepSummaryField.RR_MAX.value)),
rr_min=int_or_none(data.get(GetSleepSummaryField.RR_MIN.value)),
sleep_score=int_or_none(data.get(GetSleepSummaryField.SLEEP_SCORE.value)),
snoring=int_or_none(data.get(GetSleepSummaryField.SNORING.value)),
snoringepisodecount=int_or_none(
data.get(GetSleepSummaryField.SNORING_EPISODE_COUNT.value)
),
wakeupcount=int_or_none(data.get(GetSleepSummaryField.WAKEUP_COUNT.value)),
wakeupduration=int_or_none(
data.get(GetSleepSummaryField.WAKEUP_DURATION.value)
),
)
def new_get_sleep_summary_serie(data: dict) -> GetSleepSummarySerie:
"""Create GetSleepSummarySerie from json."""
timezone: Final = timezone_or_raise(data.get("timezone"))
return GetSleepSummarySerie(
date=arrow_or_raise(data.get("date")).to(timezone),
enddate=arrow_or_raise(data.get("enddate")).to(timezone),
model=new_sleep_model(data.get("model")),
modified=arrow_or_raise(data.get("modified")).to(timezone),
startdate=arrow_or_raise(data.get("startdate")).to(timezone),
timezone=timezone,
data=new_get_sleep_summary_data(dict_or_raise(data.get("data"))),
)
def new_sleep_get_summary_response(data: dict) -> SleepGetSummaryResponse:
"""Create GetSleepSummaryResponse from json."""
return SleepGetSummaryResponse(
more=bool_or_raise(data.get("more")),
offset=int_or_raise(data.get("offset")),
series=_flexible_tuple_of(data.get("series", ()), new_get_sleep_summary_serie),
)
def new_measure_get_meas_measure(data: dict) -> MeasureGetMeasMeasure:
"""Create GetMeasMeasure from json."""
return MeasureGetMeasMeasure(
value=int_or_raise(data.get("value")),
type=new_measure_type(data.get("type")),
unit=int_or_raise(data.get("unit")),
)
def new_measure_get_meas_group(data: dict, timezone: tzinfo) -> MeasureGetMeasGroup:
"""Create GetMeasGroup from json."""
return MeasureGetMeasGroup(
grpid=int_or_raise(data.get("grpid")),
attrib=new_measure_group_attrib(data.get("attrib")),
date=arrow_or_raise(data.get("date")).to(timezone),
created=arrow_or_raise(data.get("created")).to(timezone),
category=new_measure_category(data.get("category")),
deviceid=data.get("deviceid"),
measures=_flexible_tuple_of(
data.get("measures", ()), new_measure_get_meas_measure
),
)
def _flexible_tuple_of(
items: Iterable[Any], fun: Callable[[Any], GenericType]
) -> Tuple[GenericType, ...]:
"""Create a tuple of objects resolved through lambda.
If the lambda throws an exception, the resulting item will be ignored.
"""
new_items: Final[List[GenericType]] = []
for item in items:
try:
new_items.append(fun(item))
except Exception: # pylint:disable=broad-except
print(
"Warning: Failed to convert object. See exception for details.",
traceback.format_exc(),
)
return tuple(new_items)
def new_measure_get_meas_response(data: dict) -> MeasureGetMeasResponse:
"""Create GetMeasResponse from json."""
timezone: Final = timezone_or_raise(data.get("timezone"))
return MeasureGetMeasResponse(
measuregrps=_flexible_tuple_of(
data.get("measuregrps", ()),
lambda group: new_measure_get_meas_group(group, timezone),
),
more=data.get("more"),
offset=data.get("offset"),
timezone=timezone,
updatetime=arrow_or_raise(data.get("updatetime")).to(timezone),
)
def new_measure_get_activity_activity(data: dict) -> MeasureGetActivityActivity:
"""Create GetActivityActivity from json."""
timezone: Final = timezone_or_raise(data.get("timezone"))
return MeasureGetActivityActivity(
date=arrow_or_raise(data.get("date")).to(timezone),
timezone=timezone,
deviceid=str_or_none(data.get("deviceid")),
brand=int_or_raise(data.get("brand")),
is_tracker=bool_or_raise(data.get("is_tracker")),
steps=int_or_none(data.get(GetActivityField.STEPS.value)),
distance=float_or_raise(data.get(GetActivityField.DISTANCE.value)),
elevation=float_or_raise(data.get(GetActivityField.ELEVATION.value)),
soft=int_or_none(data.get(GetActivityField.SOFT.value)),
moderate=int_or_none(data.get(GetActivityField.MODERATE.value)),
intense=int_or_none(data.get(GetActivityField.INTENSE.value)),
active=int_or_none(data.get(GetActivityField.ACTIVE.value)),
calories=float_or_raise(data.get(GetActivityField.CALORIES.value)),
totalcalories=float_or_raise(data.get(GetActivityField.TOTAL_CALORIES.value)),
hr_average=int_or_none(data.get(GetActivityField.HR_AVERAGE.value)),
hr_min=int_or_none(data.get(GetActivityField.HR_MIN.value)),
hr_max=int_or_none(data.get(GetActivityField.HR_MAX.value)),
hr_zone_0=int_or_none(data.get(GetActivityField.HR_ZONE_0.value)),
hr_zone_1=int_or_none(data.get(GetActivityField.HR_ZONE_1.value)),
hr_zone_2=int_or_none(data.get(GetActivityField.HR_ZONE_2.value)),
hr_zone_3=int_or_none(data.get(GetActivityField.HR_ZONE_3.value)),
)
def new_measure_get_activity_response(data: dict) -> MeasureGetActivityResponse:
"""Create GetActivityResponse from json."""
return MeasureGetActivityResponse(
activities=_flexible_tuple_of(
data.get("activities", ()), new_measure_get_activity_activity
),
more=bool_or_raise(data.get("more")),
offset=int_or_raise(data.get("offset")),
)
AMBIGUOUS_GROUP_ATTRIBS: Final = (
MeasureGetMeasGroupAttrib.DEVICE_ENTRY_FOR_USER_AMBIGUOUS,
MeasureGetMeasGroupAttrib.MANUAL_USER_DURING_ACCOUNT_CREATION,
)
class MeasureGroupAttribs:
"""Groups of MeasureGetMeasGroupAttrib."""
ANY: Final = tuple(enum_val for enum_val in MeasureGetMeasGroupAttrib)
AMBIGUOUS: Final = AMBIGUOUS_GROUP_ATTRIBS
UNAMBIGUOUS: Final = tuple(
enum_val
for enum_val in MeasureGetMeasGroupAttrib
if enum_val not in AMBIGUOUS_GROUP_ATTRIBS
)
class MeasureTypes:
"""Groups of MeasureType."""
ANY: Final = tuple(enum_val for enum_val in MeasureType)
def query_measure_groups(
from_source: Union[
MeasureGetMeasGroup, MeasureGetMeasResponse, Tuple[MeasureGetMeasGroup, ...]
],
with_measure_type: Union[MeasureType, Tuple[MeasureType, ...]] = MeasureTypes.ANY,
with_group_attrib: Union[
MeasureGetMeasGroupAttrib, Tuple[MeasureGetMeasGroupAttrib, ...]
] = MeasureGroupAttribs.ANY,
) -> Tuple[MeasureGetMeasGroup, ...]:
"""Return a groups and measurements based on filters."""
if isinstance(from_source, MeasureGetMeasResponse):
iter_groups = cast(MeasureGetMeasResponse, from_source).measuregrps
elif isinstance(from_source, MeasureGetMeasGroup):
iter_groups = (cast(MeasureGetMeasGroup, from_source),)
else:
iter_groups = cast(Tuple[MeasureGetMeasGroup], from_source)
if isinstance(with_measure_type, MeasureType):
iter_measure_type = (cast(MeasureType, with_measure_type),)
else:
iter_measure_type = cast(Tuple[MeasureType], with_measure_type)
if isinstance(with_group_attrib, MeasureGetMeasGroupAttrib):
iter_group_attrib = (cast(MeasureGetMeasGroupAttrib, with_group_attrib),)
else:
iter_group_attrib = cast(Tuple[MeasureGetMeasGroupAttrib], with_group_attrib)
return tuple(
MeasureGetMeasGroup(
attrib=group.attrib,
category=group.category,
created=group.created,
date=group.date,
deviceid=group.deviceid,
grpid=group.grpid,
measures=tuple(
measure
for measure in group.measures
if measure.type in iter_measure_type
),
)
for group in iter_groups
if group.attrib in iter_group_attrib
)
def get_measure_value(
from_source: Union[
MeasureGetMeasGroup, MeasureGetMeasResponse, Tuple[MeasureGetMeasGroup, ...]
],
with_measure_type: Union[MeasureType, Tuple[MeasureType, ...]],
with_group_attrib: Union[
MeasureGetMeasGroupAttrib, Tuple[MeasureGetMeasGroupAttrib, ...]
] = MeasureGroupAttribs.ANY,
) -> Optional[float]:
"""Get the first value of a measure that meet the query requirements."""
groups: Final = query_measure_groups(
from_source, with_measure_type, with_group_attrib
)
return next(
iter(
tuple(
float(measure.value * pow(10, measure.unit))
for group in groups
for measure in group.measures
)
),
None,
)
def new_heart_get_response(data: dict) -> HeartGetResponse:
"""Create GetSleepResponse from json."""
return HeartGetResponse(
signal=tuple(sample for sample in data.get("signal", ())),
sampling_frequency=int_or_raise(data.get("sampling_frequency")),
wearposition=new_heart_wear_position(data.get("wearposition")),
)
def new_heart_list_ecg(data: dict) -> HeartListECG:
"""Create HeartListECG from json."""
return HeartListECG(
signalid=int_or_raise(data.get("signalid")),
afib=new_afib_classification(data.get("afib")),
)
def new_heart_blood_pressure(
data: Optional[Dict[Any, Any]]
) -> Optional[HeartBloodPressure]:
"""Create HeartBloodPressure from json."""
if data is None:
return data
return HeartBloodPressure(
diastole=int_or_raise(data.get("diastole")),
systole=int_or_raise(data.get("systole")),
)
def new_heart_list_serie(data: dict) -> HeartListSerie:
"""Create HeartListSerie from json."""
return HeartListSerie(
model=new_heart_model(int_or_raise(data.get("model"))),
ecg=new_heart_list_ecg(dict_or_raise(data.get("ecg"))),
bloodpressure=new_heart_blood_pressure(dict_or_none(data.get("bloodpressure"))),
heart_rate=int_or_raise(data.get("heart_rate")),
timestamp=arrow_or_raise((int_or_raise(data.get("timestamp")))),
)
def new_heart_list_response(data: dict) -> HeartListResponse:
"""Create HeartListResponse from json."""
return HeartListResponse(
more=bool_or_raise(data.get("more")),
offset=int_or_raise(data.get("offset")),
series=_flexible_tuple_of(data.get("series", ()), new_heart_list_serie),
)
class StatusException(Exception):
"""Status exception."""
def __init__(self, status: Any):
"""Create instance."""
super().__init__("Error code %s" % str(status))
class AuthFailedException(StatusException):
"""Withings status error code exception."""
class InvalidParamsException(StatusException):