-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterface.py
1132 lines (834 loc) · 34.2 KB
/
interface.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
# -*- coding: utf-8 -*-
# vim: set ft=python ts=4 sw=4 expandtab:
# pylint: disable=line-too-long,too-many-lines,too-many-positional-arguments,too-many-instance-attributes:
"""
Classes that are part of the SmartApp interface.
"""
# For lifecycle class definitions, see:
#
# https://developer-preview.smartthings.com/docs/connected-services/lifecycles/
# https://developer-preview.smartthings.com/docs/connected-services/configuration/
#
# There is not any public documentation about event structure, only the Javascript
# reference implementation here:
#
# https://github.com/SmartThingsCommunity/smartapp-sdk-nodejs/blob/f1ef97ec9c6dc270ba744197b842c6632c778987/lib/lifecycle-events.d.ts
#
# However, as of this writitng, even that reference implementation is not fully up-to-date
# with the JSON that is being returned for some events I have examined in my testing.
#
# I have access to private documentation that shows all of the attributes. However, that
# documentation doesn't always make it clear which attributes will always be included and
# which are optional. As compromise, I have decided to maintain the actual events as
# dicts rather than true objects. See further discussion below by the Event class.
from abc import ABC, abstractmethod
from enum import Enum
from typing import Any, Callable, Dict, List, Mapping, Optional, Union
from arrow import Arrow
from attrs import field, frozen
AUTHORIZATION_HEADER = "authorization"
CORRELATION_ID_HEADER = "x-st-correlation"
DATE_HEADER = "date"
class LifecyclePhase(Enum):
"""Lifecycle phases."""
CONFIRMATION = "CONFIRMATION"
CONFIGURATION = "CONFIGURATION"
INSTALL = "INSTALL"
UPDATE = "UPDATE"
UNINSTALL = "UNINSTALL"
OAUTH_CALLBACK = "OAUTH_CALLBACK"
EVENT = "EVENT"
class ConfigValueType(Enum):
"""Types of config values."""
DEVICE = "DEVICE"
STRING = "STRING"
class ConfigPhase(Enum):
"""Sub-phases within the CONFIGURATION phase."""
INITIALIZE = "INITIALIZE"
PAGE = "PAGE"
class ConfigSettingType(Enum):
"""Types of config settings."""
DEVICE = "DEVICE"
TEXT = "TEXT"
BOOLEAN = "BOOLEAN"
ENUM = "ENUM"
LINK = "LINK"
PAGE = "PAGE"
IMAGE = "IMAGE"
ICON = "ICON"
TIME = "TIME"
PARAGRAPH = "PARAGRAPH"
EMAIL = "EMAIL"
DECIMAL = "DECIMAL"
NUMBER = "NUMBER"
PHONE = "PHONE"
OAUTH = "OAUTH"
class EventType(Enum):
"""Supported event types."""
DEVICE_COMMANDS_EVENT = "DEVICE_COMMANDS_EVENT"
DEVICE_EVENT = "DEVICE_EVENT"
DEVICE_HEALTH_EVENT = "DEVICE_HEALTH_EVENT"
DEVICE_LIFECYCLE_EVENT = "DEVICE_LIFECYCLE_EVENT"
HUB_HEALTH_EVENT = "HUB_HEALTH_EVENT"
INSTALLED_APP_LIFECYCLE_EVENT = "INSTALLED_APP_LIFECYCLE_EVENT"
MODE_EVENT = "MODE_EVENT"
SCENE_LIFECYCLE_EVENT = "SCENE_LIFECYCLE_EVENT"
SECURITY_ARM_STATE_EVENT = "SECURITY_ARM_STATE_EVENT"
TIMER_EVENT = "TIMER_EVENT"
WEATHER_EVENT = "WEATHER_EVENT"
class SubscriptionType(Enum):
"""Supported subscription types."""
DEVICE = "DEVICE"
CAPABILITY = "CAPABILITY"
MODE = "MODE"
DEVICE_LIFECYCLE = "DEVICE_LIFECYCLE"
DEVICE_HEALTH = "DEVICE_HEALTH"
SECURITY_ARM_STATE = "SECURITY_ARM_STATE"
HUB_HEALTH = "HUB_HEALTH"
SCENE_LIFECYCLE = "SCENE_LIFECYCLE"
class BooleanValue(str, Enum):
"""String boolean values."""
TRUE = "true"
FALSE = "false"
@frozen(kw_only=True)
class AbstractRequest(ABC):
"""Abstract parent class for all types of lifecycle requests."""
lifecycle: LifecyclePhase
execution_id: str
locale: str
version: str
@frozen(kw_only=True)
class AbstractSetting(ABC):
"""Abstract parent class for all types of config settings."""
id: str
name: str
description: str
required: Optional[bool] = False
@frozen(kw_only=True)
class DeviceSetting(AbstractSetting):
"""A DEVICE setting."""
type: ConfigSettingType = ConfigSettingType.DEVICE
multiple: bool
capabilities: List[str] # note that this is treated as AND - you'll get devices that have all capabilities
permissions: List[str]
@frozen(kw_only=True)
class TextSetting(AbstractSetting):
"""A TEXT setting."""
type: ConfigSettingType = ConfigSettingType.TEXT
default_value: str
@frozen(kw_only=True)
class BooleanSetting(AbstractSetting):
"""A BOOLEAN setting."""
type: ConfigSettingType = ConfigSettingType.BOOLEAN
default_value: BooleanValue
@frozen(kw_only=True)
class EnumOption:
"""An option within an ENUM setting"""
id: str
name: str
@frozen(kw_only=True)
class EnumOptionGroup:
"""A group of options within an ENUM setting"""
name: str
options: List[EnumOption]
@frozen(kw_only=True)
class EnumSetting(AbstractSetting):
"""An ENUM setting."""
type: ConfigSettingType = ConfigSettingType.ENUM
multiple: bool
options: Optional[List[EnumOption]] = None
grouped_options: Optional[List[EnumOptionGroup]] = None
@frozen(kw_only=True)
class LinkSetting(AbstractSetting):
"""A LINK setting."""
type: ConfigSettingType = ConfigSettingType.LINK
url: str
image: str
@frozen(kw_only=True)
class PageSetting(AbstractSetting):
"""A PAGE setting."""
type: ConfigSettingType = ConfigSettingType.PAGE
page: str
image: str
@frozen(kw_only=True)
class ImageSetting(AbstractSetting):
"""An IMAGE setting."""
type: ConfigSettingType = ConfigSettingType.IMAGE
image: str
@frozen(kw_only=True)
class IconSetting(AbstractSetting):
"""An ICON setting."""
type: ConfigSettingType = ConfigSettingType.ICON
image: str
@frozen(kw_only=True)
class TimeSetting(AbstractSetting):
"""A TIME setting."""
type: ConfigSettingType = ConfigSettingType.TIME
@frozen(kw_only=True)
class ParagraphSetting(AbstractSetting):
"""A PARAGRAPH setting."""
type: ConfigSettingType = ConfigSettingType.PARAGRAPH
default_value: str
@frozen(kw_only=True)
class EmailSetting(AbstractSetting):
"""An EMAIL setting."""
type: ConfigSettingType = ConfigSettingType.EMAIL
@frozen(kw_only=True)
class DecimalSetting(AbstractSetting):
"""A DECIMAL setting."""
type: ConfigSettingType = ConfigSettingType.DECIMAL
@frozen(kw_only=True)
class NumberSetting(AbstractSetting):
"""A NUMBER setting."""
type: ConfigSettingType = ConfigSettingType.NUMBER
@frozen(kw_only=True)
class PhoneSetting(AbstractSetting):
"""A PHONE setting."""
type: ConfigSettingType = ConfigSettingType.PHONE
@frozen(kw_only=True)
class OauthSetting(AbstractSetting):
"""An OAUTH setting."""
type: ConfigSettingType = ConfigSettingType.OAUTH
browser: bool
url_template: str
ConfigSetting = Union[
DeviceSetting,
TextSetting,
BooleanSetting,
EnumSetting,
LinkSetting,
PageSetting,
ImageSetting,
IconSetting,
TimeSetting,
ParagraphSetting,
EmailSetting,
DecimalSetting,
NumberSetting,
PhoneSetting,
OauthSetting,
]
@frozen(kw_only=True)
class DeviceValue:
device_id: str
component_id: str
@frozen(kw_only=True)
class DeviceConfigValue:
"""DEVICE configuration value."""
device_config: DeviceValue
value_type: ConfigValueType = ConfigValueType.DEVICE
@frozen(kw_only=True)
class StringValue:
value: str
@frozen(kw_only=True)
class StringConfigValue:
"""STRING configuration value."""
string_config: StringValue
value_type: ConfigValueType = ConfigValueType.STRING
ConfigValue = Union[
DeviceConfigValue,
StringConfigValue,
]
@frozen(kw_only=True)
class InstalledApp:
"""Installed application."""
installed_app_id: str
location_id: str
config: Dict[str, List[ConfigValue]]
permissions: List[str] = field(factory=list)
def as_devices(self, key: str) -> List[DeviceValue]:
"""Return a list of devices for a named configuration value."""
return [item.device_config for item in self.config[key]] # type: ignore
def as_str(self, key: str) -> str:
"""Return a named configuration value, interpreted as a string"""
return self.config[key][0].string_config.value # type: ignore
def as_bool(self, key: str) -> bool:
"""Return a named configuration value, interpreted as a boolean"""
return bool(self.as_str(key))
def as_int(self, key: str) -> int:
"""Return a named configuration value, interpreted as an integer"""
return int(self.as_str(key))
def as_float(self, key: str) -> float:
"""Return a named configuration value, interpreted as a float"""
return float(self.as_str(key))
@frozen(kw_only=True)
class Event:
"""Holds the triggered event, one of several different attributes depending on event type."""
event_time: Optional[Arrow] = None
event_type: EventType
device_event: Optional[Dict[str, Any]] = None
device_lifecycle_event: Optional[Dict[str, Any]] = None
device_health_event: Optional[Dict[str, Any]] = None
device_commands_event: Optional[Dict[str, Any]] = None
mode_event: Optional[Dict[str, Any]] = None
timer_event: Optional[Dict[str, Any]] = None
scene_lifecycle_event: Optional[Dict[str, Any]] = None
security_arm_state_event: Optional[Dict[str, Any]] = None
hub_health_event: Optional[Dict[str, Any]] = None
installed_app_lifecycle_event: Optional[Dict[str, Any]] = None
weather_event: Optional[Dict[str, Any]] = None
weather_data: Optional[Dict[str, Any]] = None
air_quality_data: Optional[Dict[str, Any]] = None
def for_type(self, event_type: EventType) -> Optional[Dict[str, Any]]: # pylint: disable=too-many-return-statements
"""Return the attribute associated with an event type."""
if event_type == EventType.DEVICE_COMMANDS_EVENT:
return self.device_commands_event
elif event_type == EventType.DEVICE_EVENT:
return self.device_event
elif event_type == EventType.DEVICE_HEALTH_EVENT:
return self.device_health_event
elif event_type == EventType.DEVICE_LIFECYCLE_EVENT:
return self.device_lifecycle_event
elif event_type == EventType.HUB_HEALTH_EVENT:
return self.hub_health_event
elif event_type == EventType.INSTALLED_APP_LIFECYCLE_EVENT:
return self.installed_app_lifecycle_event
elif event_type == EventType.MODE_EVENT:
return self.mode_event
elif event_type == EventType.SCENE_LIFECYCLE_EVENT:
return self.scene_lifecycle_event
elif event_type == EventType.SECURITY_ARM_STATE_EVENT:
return self.security_arm_state_event
elif event_type == EventType.TIMER_EVENT:
return self.timer_event
elif event_type == EventType.WEATHER_EVENT:
return self.weather_event
return None
@frozen(kw_only=True)
class ConfirmationData:
"""Confirmation data."""
app_id: str
confirmation_url: str
@frozen(kw_only=True)
class ConfigInit:
"""Initialization data."""
id: str
name: str
description: str
permissions: List[str]
first_page_id: str
@frozen(kw_only=True)
class ConfigRequestData:
"""Configuration data provided on the request."""
installed_app_id: str
phase: ConfigPhase
page_id: str
previous_page_id: str
config: Dict[str, List[ConfigValue]]
@frozen(kw_only=True)
class ConfigInitData:
"""Configuration data provided in an INITIALIZATION response."""
initialize: ConfigInit
@frozen(kw_only=True)
class ConfigSection:
"""A section within a configuration page."""
name: str
settings: List[ConfigSetting]
@frozen(kw_only=True)
class ConfigPage:
"""A page of configuration data for the CONFIGURATION phase."""
page_id: str
name: str
previous_page_id: Optional[str]
next_page_id: Optional[str]
complete: bool
sections: List[ConfigSection]
@frozen(kw_only=True)
class ConfigPageData:
"""Configuration data provided in an PAGE response."""
page: ConfigPage
@frozen(kw_only=True)
class InstallData:
"""Install data."""
# note: auth_token and refresh_token are secrets, so we don't include them in string output
auth_token: str = field(repr=False)
refresh_token: str = field(repr=False)
installed_app: InstalledApp
def token(self) -> str:
"""Return the auth token associated with this request."""
return self.auth_token
def app_id(self) -> str:
"""Return the installed application id associated with this request."""
return self.installed_app.installed_app_id
def location_id(self) -> str:
"""Return the installed location id associated with this request."""
return self.installed_app.location_id
def as_devices(self, key: str) -> List[DeviceValue]:
"""Return a list of devices for a named configuration value."""
return self.installed_app.as_devices(key)
def as_str(self, key: str) -> str:
"""Return a named configuration value, interpreted as a string"""
return self.installed_app.as_str(key)
def as_bool(self, key: str) -> bool:
"""Return a named configuration value, interpreted as a boolean"""
return self.installed_app.as_bool(key)
def as_int(self, key: str) -> int:
"""Return a named configuration value, interpreted as an integer"""
return self.installed_app.as_int(key)
def as_float(self, key: str) -> float:
"""Return a named configuration value, interpreted as a float"""
return self.installed_app.as_float(key)
@frozen(kw_only=True)
class UpdateData:
"""Update data."""
# note: auth_token and refresh_token are secrets, so we don't include them in string output
auth_token: str = field(repr=False)
refresh_token: str = field(repr=False)
installed_app: InstalledApp
previous_config: Optional[Dict[str, List[ConfigValue]]] = None
previous_permissions: List[str] = field(factory=list)
def token(self) -> str:
"""Return the auth token associated with this request."""
return self.auth_token
def app_id(self) -> str:
"""Return the installed application id associated with this request."""
return self.installed_app.installed_app_id
def location_id(self) -> str:
"""Return the installed location id associated with this request."""
return self.installed_app.location_id
def as_devices(self, key: str) -> List[DeviceValue]:
"""Return a list of devices for a named configuration value."""
return self.installed_app.as_devices(key)
def as_str(self, key: str) -> str:
"""Return a named configuration value, interpreted as a string"""
return self.installed_app.as_str(key)
def as_bool(self, key: str) -> bool:
"""Return a named configuration value, interpreted as a boolean"""
return self.installed_app.as_bool(key)
def as_int(self, key: str) -> int:
"""Return a named configuration value, interpreted as an integer"""
return self.installed_app.as_int(key)
def as_float(self, key: str) -> float:
"""Return a named configuration value, interpreted as a float"""
return self.installed_app.as_float(key)
@frozen(kw_only=True)
class UninstallData:
"""Install data."""
installed_app: InstalledApp
def app_id(self) -> str:
"""Return the installed application id associated with this request."""
return self.installed_app.installed_app_id
def location_id(self) -> str:
"""Return the installed location id associated with this request."""
return self.installed_app.location_id
@frozen(kw_only=True)
class OauthCallbackData:
installed_app_id: str
url_path: str
@frozen(kw_only=True)
class EventData:
"""Event data."""
# note: auth_token is a secret, so we don't include it in string output
auth_token: str = field(repr=False)
installed_app: InstalledApp
events: List[Event]
def token(self) -> str:
"""Return the auth token associated with this request."""
return self.auth_token
def app_id(self) -> str:
"""Return the installed application id associated with this request."""
return self.installed_app.installed_app_id
def location_id(self) -> str:
"""Return the installed location id associated with this request."""
return self.installed_app.location_id
def for_type(self, event_type: EventType) -> List[Dict[str, Any]]:
"""Get all events for a particular event type, possibly empty."""
return [
event.for_type(event_type) # type: ignore
for event in self.events
if event.event_type == event_type and event.for_type(event_type) is not None
]
def filter(self, event_type: EventType, predicate: Optional[Callable[[Dict[str, Any]], bool]] = None) -> List[Dict[str, Any]]:
"""Apply a filter to a set of events with a particular event type."""
return list(filter(predicate, self.for_type(event_type)))
@frozen(kw_only=True)
class ConfirmationRequest(AbstractRequest):
"""Request for CONFIRMATION phase"""
app_id: str
confirmation_data: ConfirmationData
settings: Dict[str, Any] = field(factory=dict)
@frozen(kw_only=True)
class ConfirmationResponse:
"""Response for CONFIRMATION phase"""
target_url: str
@frozen(kw_only=True)
class ConfigurationRequest(AbstractRequest):
"""Request for CONFIGURATION phase"""
configuration_data: ConfigRequestData
settings: Dict[str, Any] = field(factory=dict)
@frozen(kw_only=True)
class ConfigurationInitResponse:
"""Response for CONFIGURATION/INITIALIZE phase"""
configuration_data: ConfigInitData
@frozen(kw_only=True)
class ConfigurationPageResponse:
"""Response for CONFIGURATION/PAGE phase"""
configuration_data: ConfigPageData
@frozen(kw_only=True)
class InstallRequest(AbstractRequest):
"""Request for INSTALL phase"""
install_data: InstallData
settings: Dict[str, Any] = field(factory=dict)
def token(self) -> str:
"""Return the auth token associated with this request."""
return self.install_data.token()
def app_id(self) -> str:
"""Return the installed application id associated with this request."""
return self.install_data.app_id()
def location_id(self) -> str:
"""Return the installed location id associated with this request."""
return self.install_data.location_id()
def as_devices(self, key: str) -> List[DeviceValue]:
"""Return a list of devices for a named configuration value."""
return self.install_data.as_devices(key)
def as_str(self, key: str) -> str:
"""Return a named configuration value, interpreted as a string"""
return self.install_data.as_str(key)
def as_bool(self, key: str) -> bool:
"""Return a named configuration value, interpreted as a boolean"""
return self.install_data.as_bool(key)
def as_int(self, key: str) -> int:
"""Return a named configuration value, interpreted as an integer"""
return self.install_data.as_int(key)
def as_float(self, key: str) -> float:
"""Return a named configuration value, interpreted as a float"""
return self.install_data.as_float(key)
@frozen(kw_only=True)
class InstallResponse:
"""Response for INSTALL phase"""
install_data: Dict[str, Any] = field(factory=dict) # always empty in the response
@frozen(kw_only=True)
class UpdateRequest(AbstractRequest):
"""Request for UPDATE phase"""
update_data: UpdateData
settings: Dict[str, Any] = field(factory=dict)
def token(self) -> str:
"""Return the auth token associated with this request."""
return self.update_data.token()
def app_id(self) -> str:
"""Return the installed application id associated with this request."""
return self.update_data.app_id()
def location_id(self) -> str:
"""Return the installed location id associated with this request."""
return self.update_data.location_id()
def as_devices(self, key: str) -> List[DeviceValue]:
"""Return a list of devices for a named configuration value."""
return self.update_data.as_devices(key)
def as_str(self, key: str) -> str:
"""Return a named configuration value, interpreted as a string"""
return self.update_data.as_str(key)
def as_bool(self, key: str) -> bool:
"""Return a named configuration value, interpreted as a boolean"""
return self.update_data.as_bool(key)
def as_int(self, key: str) -> int:
"""Return a named configuration value, interpreted as an integer"""
return self.update_data.as_int(key)
def as_float(self, key: str) -> float:
"""Return a named configuration value, interpreted as a float"""
return self.update_data.as_float(key)
@frozen(kw_only=True)
class UpdateResponse:
"""Response for UPDATE phase"""
update_data: Dict[str, Any] = field(factory=dict) # always empty in the response
@frozen(kw_only=True)
class UninstallRequest(AbstractRequest):
"""Request for UNINSTALL phase"""
uninstall_data: UninstallData
settings: Dict[str, Any] = field(factory=dict)
def app_id(self) -> str:
"""Return the installed application id associated with this request."""
return self.uninstall_data.app_id()
def location_id(self) -> str:
"""Return the installed location id associated with this request."""
return self.uninstall_data.location_id()
@frozen(kw_only=True)
class UninstallResponse:
"""Response for UNINSTALL phase"""
uninstall_data: Dict[str, Any] = field(factory=dict) # always empty in the response
@frozen(kw_only=True)
class OauthCallbackRequest(AbstractRequest):
"""Request for OAUTH_CALLBACK phase"""
o_auth_callback_data: OauthCallbackData
@frozen(kw_only=True)
class OauthCallbackResponse:
"""Response for OAUTH_CALLBACK phase"""
o_auth_callback_data: Dict[str, Any] = field(factory=dict) # always empty in the response
@frozen(kw_only=True)
class EventRequest(AbstractRequest):
"""Request for EVENT phase"""
event_data: EventData
settings: Dict[str, Any] = field(factory=dict)
def token(self) -> str:
"""Return the auth token associated with this request."""
return self.event_data.token()
def app_id(self) -> str:
"""Return the installed application id associated with this request."""
return self.event_data.app_id()
def location_id(self) -> str:
"""Return the installed location id associated with this request."""
return self.event_data.location_id()
@frozen(kw_only=True)
class EventResponse:
"""Response for EVENT phase"""
event_data: Dict[str, Any] = field(factory=dict) # always empty in the response
LifecycleRequest = Union[
ConfigurationRequest,
ConfirmationRequest,
InstallRequest,
UpdateRequest,
UninstallRequest,
OauthCallbackRequest,
EventRequest,
]
LifecycleResponse = Union[
ConfigurationInitResponse,
ConfigurationPageResponse,
ConfirmationResponse,
InstallResponse,
UpdateResponse,
UninstallResponse,
OauthCallbackResponse,
EventResponse,
]
REQUEST_BY_PHASE = {
LifecyclePhase.CONFIGURATION: ConfigurationRequest,
LifecyclePhase.CONFIRMATION: ConfirmationRequest,
LifecyclePhase.INSTALL: InstallRequest,
LifecyclePhase.UPDATE: UpdateRequest,
LifecyclePhase.UNINSTALL: UninstallRequest,
LifecyclePhase.OAUTH_CALLBACK: OauthCallbackRequest,
LifecyclePhase.EVENT: EventRequest,
}
CONFIG_VALUE_BY_TYPE = {
ConfigValueType.DEVICE: DeviceConfigValue,
ConfigValueType.STRING: StringConfigValue,
}
CONFIG_SETTING_BY_TYPE = {
ConfigSettingType.DEVICE: DeviceSetting,
ConfigSettingType.TEXT: TextSetting,
ConfigSettingType.BOOLEAN: BooleanSetting,
ConfigSettingType.ENUM: EnumSetting,
ConfigSettingType.LINK: LinkSetting,
ConfigSettingType.PAGE: PageSetting,
ConfigSettingType.IMAGE: ImageSetting,
ConfigSettingType.ICON: IconSetting,
ConfigSettingType.TIME: TimeSetting,
ConfigSettingType.PARAGRAPH: ParagraphSetting,
ConfigSettingType.EMAIL: EmailSetting,
ConfigSettingType.DECIMAL: DecimalSetting,
ConfigSettingType.NUMBER: NumberSetting,
ConfigSettingType.PHONE: PhoneSetting,
ConfigSettingType.OAUTH: OauthSetting,
}
@frozen
class SmartAppError(Exception):
"""An error tied to the SmartApp implementation."""
message: str
correlation_id: Optional[str] = None
@frozen
class InternalError(SmartAppError):
"""An internal error was encountered processing a lifecycle event."""
@frozen
class BadRequestError(SmartAppError):
"""A lifecycle event was invalid."""
@frozen
class SignatureError(SmartAppError):
"""The request signature on a lifecycle event was invalid."""
@frozen(kw_only=True)
class SmartAppDispatcherConfig:
# noinspection PyUnresolvedReferences
"""
Configuration for the SmartAppDispatcher.
Any production SmartApp should always check signatures. We support disabling that feature
to make local testing easier during development.
BEWARE: setting `log_json` to `True` will potentially place secrets (such as authorization
keys) in your logs. This is intended for use during development and debugging only.
Attributes:
check_signatures(bool): Whether to check the digital signature on lifecycle requests
clock_skew_sec(int): Amount of clock skew allowed when verifying digital signatures, or None to allow any skew
keyserver_url(str): The SmartThings keyserver URL, where we retrieve keys for signature checks
log_json(bool): Whether to log JSON data at DEBUG level when processing requests
"""
check_signatures: bool = True
clock_skew_sec: Optional[int] = 300
keyserver_url: str = "https://key.smartthings.com"
log_json: bool = False
class SmartAppEventHandler(ABC):
"""
Application event handler for SmartApp lifecycle events.
Inherit from this class to implement your own application-specific event handler.
The application-specific event handler is always called first, before any default
event handler logic in the dispatcher itself.
The correlation id is an optional value that you can associate with your log messages.
It may aid in debugging if you need to contact SmartThings for support.
Some lifecycle events do not require you to implement any custom event handler logic:
- CONFIRMATION: normally no callback needed, since the dispatcher logs the app id and confirmation URL
- CONFIGURATION: normally no callback needed, since the dispatcher has the information it needs to respond
- INSTALL/UPDATE: set up or replace subscriptions and schedules and persist required data, if any
- UNINSTALL: remove persisted data, if any
- OAUTH_CALLBACK: coordinate with your oauth provider as needed
- EVENT: handle SmartThings events or scheduled triggers
The EventRequest object that you receive for the EVENT callback includes an
authorization token and also the entire configuration bundle for the installed
application. So, if your SmartApp is built around event handling and scheduled
actions triggered by SmartThings, your handler can probably be stateless. There is
probably is not any need to persist any of the data returned in the INSTALL or UPDATE
lifecycle events into your own data store.
Note that SmartAppHandler is a synchronous and single-threaded interface. The
assumption is that if you need high-volume asynchronous or multi-threaded processing,
you will implement that at the tier above this where the actual POST requests are
accepted from remote callers.
"""
@abstractmethod
def handle_confirmation(self, correlation_id: Optional[str], request: ConfirmationRequest) -> None:
"""Handle a CONFIRMATION lifecycle request"""
@abstractmethod
def handle_configuration(self, correlation_id: Optional[str], request: ConfigurationRequest) -> None:
"""Handle a CONFIGURATION lifecycle request."""
@abstractmethod
def handle_install(self, correlation_id: Optional[str], request: InstallRequest) -> None:
"""Handle an INSTALL lifecycle request."""
@abstractmethod
def handle_update(self, correlation_id: Optional[str], request: UpdateRequest) -> None:
"""Handle an UPDATE lifecycle request."""
@abstractmethod
def handle_uninstall(self, correlation_id: Optional[str], request: UninstallRequest) -> None:
"""Handle an UNINSTALL lifecycle request."""
@abstractmethod
def handle_oauth_callback(self, correlation_id: Optional[str], request: OauthCallbackRequest) -> None:
"""Handle an OAUTH_CALLBACK lifecycle request."""
@abstractmethod
def handle_event(self, correlation_id: Optional[str], request: EventRequest) -> None:
"""Handle an EVENT lifecycle request."""
@frozen(kw_only=True)
class SmartAppConfigPage:
"""
A page of configuration for the SmartApp.
"""
page_name: str
sections: List[ConfigSection]
@frozen(kw_only=True)
class SmartAppDefinition:
# noinspection PyUnresolvedReferences
"""
The definition of the SmartApp.
All of this data would normally be static for any given version of your application.
If you wish, you can maintain the definition in YAML or JSON in your source tree
and parse it with `smartapp.converter.CONVERTER`.
Keep in mind that the JSON or YAML format on disk will be consistent with the SmartThings
lifecycle API, so it will use camel case attribute names (like `configPages`) rather than
the Python attribute names you see in source code (like `config_pages`).