-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathmodels.py
More file actions
1411 lines (1200 loc) · 45.8 KB
/
models.py
File metadata and controls
1411 lines (1200 loc) · 45.8 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
"""Models representing Overkiz API payloads and convenient accessors."""
from __future__ import annotations
import json
import logging
import re
from collections.abc import Iterator
from typing import Any, cast
from attr import define, field
from pyoverkiz.enums import (
DataType,
EventName,
ExecutionState,
ExecutionSubType,
ExecutionType,
FailureType,
GatewaySubType,
GatewayType,
ProductType,
UIClass,
UIWidget,
UpdateBoxStatus,
)
from pyoverkiz.enums.command import OverkizCommand, OverkizCommandParam
from pyoverkiz.enums.protocol import Protocol
from pyoverkiz.enums.server import APIType, Server
from pyoverkiz.obfuscate import obfuscate_email, obfuscate_id, obfuscate_string
from pyoverkiz.types import DATA_TYPE_TO_PYTHON, StateType
# pylint: disable=unused-argument, too-many-instance-attributes, too-many-locals
# <protocol>://<gatewayId>/<deviceAddress>[#<subsystemId>]
DEVICE_URL_RE = re.compile(
r"(?P<protocol>[^:]+)://(?P<gatewayId>[^/]+)/(?P<deviceAddress>[^#]+)(#(?P<subsystemId>\d+))?"
)
_LOGGER = logging.getLogger(__name__)
@define(init=False, kw_only=True)
class Setup:
"""Representation of a complete setup returned by the Overkiz API."""
creation_time: int | None = None
last_update_time: int | None = None
id: str | None = field(repr=obfuscate_id, default=None)
location: Location | None = None
gateways: list[Gateway]
devices: list[Device]
zones: list[Zone] | None = None
reseller_delegation_type: str | None = None
oid: str | None = None
root_place: Place | None = None
features: list[Feature] | None = None
def __init__(
self,
*,
creation_time: int | None = None,
last_update_time: int | None = None,
id: str | None = None,
location: dict[str, Any] | None = None,
gateways: list[dict[str, Any]],
devices: list[dict[str, Any]],
zones: list[dict[str, Any]] | None = None,
reseller_delegation_type: str | None = None,
oid: str | None = None,
root_place: dict[str, Any] | None = None,
features: list[dict[str, Any]] | None = None,
**_: Any,
) -> None:
"""Initialize a Setup and construct nested model instances."""
self.id = id
self.creation_time = creation_time
self.last_update_time = last_update_time
self.location = Location(**location) if location else None
self.gateways = [Gateway(**g) for g in gateways]
self.devices = [Device(**d) for d in devices]
self.zones = [Zone(**z) for z in zones] if zones else None
self.reseller_delegation_type = reseller_delegation_type
self.oid = oid
self.root_place = Place(**root_place) if root_place else None
self.features = [Feature(**f) for f in features] if features else None
@define(init=False, kw_only=True)
class Location:
"""Geographical and address metadata for a Setup."""
creation_time: int
last_update_time: int | None = None
city: str = field(repr=obfuscate_string, default=None)
country: str = field(repr=obfuscate_string, default=None)
postal_code: str = field(repr=obfuscate_string, default=None)
address_line1: str = field(repr=obfuscate_string, default=None)
address_line2: str = field(repr=obfuscate_string, default=None)
timezone: str
longitude: str = field(repr=obfuscate_string, default=None)
latitude: str = field(repr=obfuscate_string, default=None)
twilight_mode: int
twilight_angle: str
twilight_city: str | None = None
summer_solstice_dusk_minutes: str
winter_solstice_dusk_minutes: str
twilight_offset_enabled: bool
dawn_offset: int
dusk_offset: int
def __init__(
self,
*,
creation_time: int,
last_update_time: int | None = None,
city: str = field(repr=obfuscate_string, default=None),
country: str = field(repr=obfuscate_string, default=None),
postal_code: str = field(repr=obfuscate_string, default=None),
address_line1: str = field(repr=obfuscate_string, default=None),
address_line2: str = field(repr=obfuscate_string, default=None),
timezone: str,
longitude: str = field(repr=obfuscate_string, default=None),
latitude: str = field(repr=obfuscate_string, default=None),
twilight_mode: int,
twilight_angle: str,
twilight_city: str | None = None,
summer_solstice_dusk_minutes: str,
winter_solstice_dusk_minutes: str,
twilight_offset_enabled: bool,
dawn_offset: int,
dusk_offset: int,
**_: Any,
) -> None:
"""Initialize Location with address and timezone information."""
self.creation_time = creation_time
self.last_update_time = last_update_time
self.city = city
self.country = country
self.postal_code = postal_code
self.address_line1 = address_line1
self.address_line2 = address_line2
self.timezone = timezone
self.longitude = longitude
self.latitude = latitude
self.twilight_mode = twilight_mode
self.twilight_angle = twilight_angle
self.twilight_city = twilight_city
self.summer_solstice_dusk_minutes = summer_solstice_dusk_minutes
self.winter_solstice_dusk_minutes = winter_solstice_dusk_minutes
self.twilight_offset_enabled = twilight_offset_enabled
self.dawn_offset = dawn_offset
self.dusk_offset = dusk_offset
@define(init=False, kw_only=True)
class DeviceIdentifier:
"""Parsed components from a device URL."""
protocol: Protocol
gateway_id: str = field(repr=obfuscate_id)
device_address: str = field(repr=obfuscate_id)
subsystem_id: int | None = None
base_device_url: str = field(repr=obfuscate_id, init=False)
def __init__(
self,
*,
protocol: Protocol,
gateway_id: str,
device_address: str,
subsystem_id: int | None = None,
) -> None:
"""Initialize DeviceIdentifier with required URL components."""
self.protocol = protocol
self.gateway_id = gateway_id
self.device_address = device_address
self.subsystem_id = subsystem_id
self.base_device_url = f"{protocol}://{gateway_id}/{device_address}"
@property
def is_sub_device(self) -> bool:
"""Return True if this identifier represents a sub-device (subsystem_id > 1)."""
return self.subsystem_id is not None and self.subsystem_id > 1
@classmethod
def from_device_url(cls, device_url: str) -> DeviceIdentifier:
"""Parse a device URL into its structured identifier components."""
match = DEVICE_URL_RE.fullmatch(device_url)
if not match:
raise ValueError(f"Invalid device URL: {device_url}")
subsystem_id = (
int(match.group("subsystemId")) if match.group("subsystemId") else None
)
return cls(
protocol=Protocol(match.group("protocol")),
gateway_id=match.group("gatewayId"),
device_address=match.group("deviceAddress"),
subsystem_id=subsystem_id,
)
@define(init=False, kw_only=True)
class Device:
"""Representation of a device in the setup including parsed fields and states."""
attributes: States
available: bool
enabled: bool
label: str = field(repr=obfuscate_string)
device_url: str = field(repr=obfuscate_id)
controllable_name: str
definition: Definition
states: States
type: ProductType
oid: str | None = field(repr=obfuscate_id, default=None)
place_oid: str | None = None
creation_time: int | None = None
last_update_time: int | None = None
shortcut: bool | None = None
metadata: str | None = None
synced: bool | None = None # Local API only
subsystem_id: int | None = None # Local API only
identifier: DeviceIdentifier = field(init=False, repr=False)
_ui_class: UIClass | None = field(init=False, repr=False)
_widget: UIWidget | None = field(init=False, repr=False)
def __init__(
self,
*,
attributes: list[dict[str, Any]] | None = None,
available: bool,
enabled: bool,
label: str,
device_url: str,
controllable_name: str,
definition: dict[str, Any],
widget: str | None = None,
ui_class: str | None = None,
states: list[dict[str, Any]] | None = None,
type: int,
oid: str | None = None,
place_oid: str | None = None,
creation_time: int | None = None,
last_update_time: int | None = None,
shortcut: bool | None = None,
metadata: str | None = None,
synced: bool | None = None,
subsystem_id: int | None = None,
**_: Any,
) -> None:
"""Initialize Device and parse URL, protocol and nested definitions."""
self.attributes = States(attributes)
self.available = available
self.definition = Definition(**definition)
self.device_url = device_url
self.enabled = enabled
self.label = label
self.controllable_name = controllable_name
self.states = States(states)
self.type = ProductType(type)
self.oid = oid
self.place_oid = place_oid
self.creation_time = creation_time
self.last_update_time = last_update_time
self.shortcut = shortcut
self.metadata = metadata
self.synced = synced
self.subsystem_id = subsystem_id
self.identifier = DeviceIdentifier.from_device_url(device_url)
self._ui_class = UIClass(ui_class) if ui_class else None
self._widget = UIWidget(widget) if widget else None
@property
def ui_class(self) -> UIClass:
"""Return the UI class, falling back to the definition if available."""
if self._ui_class is not None:
return self._ui_class
if self.definition.ui_class:
return UIClass(self.definition.ui_class)
raise ValueError(f"Device {self.device_url} has no UI class defined")
@property
def widget(self) -> UIWidget:
"""Return the widget, falling back to the definition if available."""
if self._widget is not None:
return self._widget
if self.definition.widget_name:
return UIWidget(self.definition.widget_name)
raise ValueError(f"Device {self.device_url} has no widget defined")
def supports_command(self, command: str | OverkizCommand) -> bool:
"""Check if device supports a command."""
return str(command) in self.definition.commands
def supports_any_command(self, commands: list[str | OverkizCommand]) -> bool:
"""Check if device supports any of the commands."""
return self.definition.commands.has_any(commands)
def select_first_command(self, commands: list[str | OverkizCommand]) -> str | None:
"""Return first supported command name from list, or None."""
return self.definition.commands.select(commands)
def get_state_value(self, state: str) -> StateType | None:
"""Get value of a single state, or None if not found or None."""
return self.states.select_value([state])
def select_first_state_value(self, states: list[str]) -> StateType | None:
"""Return value of first state with non-None value from list, or None."""
return self.states.select_value(states)
def has_state_value(self, state: str) -> bool:
"""Check if a state exists with a non-None value."""
return self.states.has_any([state])
def has_any_state_value(self, states: list[str]) -> bool:
"""Check if any of the states exist with non-None values."""
return self.states.has_any(states)
def get_state_definition(self, state: str) -> StateDefinition | None:
"""Get StateDefinition for a single state name, or None."""
return self.definition.get_state_definition([state])
def select_first_state_definition(
self, states: list[str]
) -> StateDefinition | None:
"""Return first matching StateDefinition from list, or None."""
return self.definition.get_state_definition(states)
def get_attribute_value(self, attribute: str) -> StateType | None:
"""Get value of a single attribute, or None if not found or None."""
return self.attributes.select_value([attribute])
def select_first_attribute_value(self, attributes: list[str]) -> StateType | None:
"""Return value of first attribute with non-None value from list, or None."""
return self.attributes.select_value(attributes)
@define(init=False, kw_only=True)
class DataProperty:
"""Data property with qualified name and value."""
qualified_name: str
value: str
def __init__(
self,
*,
qualified_name: str,
value: str,
**_: Any,
) -> None:
"""Initialize DataProperty."""
self.qualified_name = qualified_name
self.value = value
@define(init=False, kw_only=True)
class StateDefinition:
"""Definition metadata for a state (qualified name, type and possible values)."""
qualified_name: str
type: str | None = None
values: list[str] | None = None
event_based: bool | None = None
def __init__(
self,
name: str | None = None,
qualified_name: str | None = None,
type: str | None = None,
values: list[str] | None = None,
event_based: bool | None = None,
**_: Any,
) -> None:
"""Initialize StateDefinition and set qualified name from either `name` or `qualified_name`."""
self.type = type
self.values = values
self.event_based = event_based
if qualified_name:
self.qualified_name = qualified_name
elif name:
self.qualified_name = name
else:
raise ValueError(
"StateDefinition requires either `name` or `qualified_name`."
)
@define(init=False, kw_only=True)
class Definition:
"""Definition of device capabilities: command definitions, state definitions and UI hints."""
commands: CommandDefinitions
states: list[StateDefinition]
data_properties: list[DataProperty]
widget_name: str | None = None
ui_class: str | None = None
qualified_name: str | None = None
ui_profiles: list[str] | None = None
ui_classifiers: list[str] | None = None
type: str | None = None
attributes: list[dict[str, Any]] | None = None # Local API only
def __init__(
self,
*,
commands: list[dict[str, Any]],
states: list[dict[str, Any]] | None = None,
data_properties: list[dict[str, Any]] | None = None,
widget_name: str | None = None,
ui_class: str | None = None,
qualified_name: str | None = None,
ui_profiles: list[str] | None = None,
ui_classifiers: list[str] | None = None,
type: str | None = None,
attributes: list[dict[str, Any]] | None = None,
**_: Any,
) -> None:
"""Initialize Definition and construct nested command/state definitions."""
self.commands = CommandDefinitions(commands)
self.states = [StateDefinition(**sd) for sd in states] if states else []
self.data_properties = (
[DataProperty(**dp) for dp in data_properties] if data_properties else []
)
self.widget_name = widget_name
self.ui_class = ui_class
self.qualified_name = qualified_name
self.ui_profiles = ui_profiles
self.ui_classifiers = ui_classifiers
self.type = type
self.attributes = attributes
def get_state_definition(self, states: list[str]) -> StateDefinition | None:
"""Return the first StateDefinition whose `qualified_name` matches, or None."""
states_set = set(states)
for state_def in self.states:
if state_def.qualified_name in states_set:
return state_def
return None
def has_state_definition(self, states: list[str]) -> bool:
"""Return True if any of the given state definitions exist."""
return self.get_state_definition(states) is not None
@define(init=False, kw_only=True)
class CommandDefinition:
"""Metadata for a single command definition (name and parameter count)."""
command_name: str
nparams: int
def __init__(self, command_name: str, nparams: int, **_: Any) -> None:
"""Initialize CommandDefinition."""
self.command_name = command_name
self.nparams = nparams
@define(init=False)
class CommandDefinitions:
"""Container for command definitions providing convenient lookup by name."""
_commands: list[CommandDefinition]
def __init__(self, commands: list[dict[str, Any]]):
"""Build the inner list of CommandDefinition objects from raw data."""
self._commands = [CommandDefinition(**command) for command in commands]
def __iter__(self) -> Iterator[CommandDefinition]:
"""Iterate over defined commands."""
return self._commands.__iter__()
def __contains__(self, name: str) -> bool:
"""Return True if a command with `name` exists."""
return self.__getitem__(name) is not None
def __getitem__(self, command: str) -> CommandDefinition | None:
"""Return the command definition or None if missing."""
return next((cd for cd in self._commands if cd.command_name == command), None)
def __len__(self) -> int:
"""Return number of command definitions."""
return len(self._commands)
get = __getitem__
def select(self, commands: list[str | OverkizCommand]) -> str | None:
"""Return the first command name that exists in this definition, or None."""
return next(
(str(command) for command in commands if str(command) in self), None
)
def has_any(self, commands: list[str | OverkizCommand]) -> bool:
"""Return True if any of the given commands exist in this definition."""
return self.select(commands) is not None
@define(init=False, kw_only=True)
class State:
"""A single device state with typed accessors for its value."""
name: str
type: DataType
value: StateType
def __init__(
self,
name: str,
type: int,
value: StateType = None,
**_: Any,
) -> None:
"""Initialize State and set its declared data type."""
self.name = name
self.value = value
self.type = DataType(type)
@property
def value_as_int(self) -> int | None:
"""Return the integer value or None if not set; raise on type mismatch."""
if self.type == DataType.NONE:
return None
if self.type == DataType.INTEGER:
return cast(int, self.value)
raise TypeError(f"{self.name} is not an integer")
@property
def value_as_float(self) -> float | None:
"""Return the float value, allow int->float conversion; raise on type mismatch."""
if self.type == DataType.NONE:
return None
if self.type == DataType.FLOAT:
return cast(float, self.value)
if self.type == DataType.INTEGER:
return float(cast(int, self.value))
raise TypeError(f"{self.name} is not a float")
@property
def value_as_bool(self) -> bool | None:
"""Return the boolean value or raise on type mismatch."""
if self.type == DataType.NONE:
return None
if self.type == DataType.BOOLEAN:
return cast(bool, self.value)
raise TypeError(f"{self.name} is not a boolean")
@property
def value_as_str(self) -> str | None:
"""Return the string value or raise on type mismatch."""
if self.type == DataType.NONE:
return None
if self.type == DataType.STRING:
return cast(str, self.value)
raise TypeError(f"{self.name} is not a string")
@property
def value_as_dict(self) -> dict[str, Any] | None:
"""Return the dict value or raise if state is not a JSON object."""
if self.type == DataType.NONE:
return None
if self.type == DataType.JSON_OBJECT:
return cast(dict, self.value)
raise TypeError(f"{self.name} is not a JSON object")
@property
def value_as_list(self) -> list[Any] | None:
"""Return the list value or raise if state is not a JSON array."""
if self.type == DataType.NONE:
return None
if self.type == DataType.JSON_ARRAY:
return cast(list, self.value)
raise TypeError(f"{self.name} is not an array")
@define(init=False, kw_only=True)
class EventState(State):
"""State variant used when parsing event payloads (casts string values)."""
def __init__(
self,
name: str,
type: int,
value: str | None = None,
**_: Any,
):
"""Initialize EventState and cast string values based on declared data type."""
super().__init__(name, type, value, **_)
# Overkiz (cloud) returns all state values as a string
# We cast them here based on the data type provided by Overkiz
# Overkiz (local) returns all state values in the right format
if not isinstance(self.value, str) or self.type not in DATA_TYPE_TO_PYTHON:
return
caster = DATA_TYPE_TO_PYTHON[self.type]
if self.type in (DataType.JSON_ARRAY, DataType.JSON_OBJECT):
self.value = self._cast_json_value(self.value)
return
self.value = caster(self.value)
def _cast_json_value(self, raw_value: str) -> StateType:
"""Cast JSON event state values; raise on decode errors."""
try:
return json.loads(raw_value)
except json.JSONDecodeError as err:
raise ValueError(
f"Invalid JSON for event state `{self.name}` ({self.type.name}): {err}"
) from err
@define(init=False)
class States:
"""Container of State objects providing lookup and mapping helpers."""
_states: list[State]
def __init__(self, states: list[dict[str, Any]] | None = None) -> None:
"""Create a container of State objects from raw state dicts or an empty list."""
if states:
self._states = [State(**state) for state in states]
else:
self._states = []
def __iter__(self) -> Iterator[State]:
"""Return an iterator over contained State objects."""
return self._states.__iter__()
def __contains__(self, name: str) -> bool:
"""Return True if a state with the given name exists in the container."""
return self.__getitem__(name) is not None
def __getitem__(self, name: str) -> State | None:
"""Return the State with the given name or None if missing."""
return next((state for state in self._states if state.name == name), None)
def __setitem__(self, name: str, state: State) -> None:
"""Set or append a State identified by name."""
found = self.__getitem__(name)
if found is None:
self._states.append(state)
else:
self._states[self._states.index(found)] = state
def __len__(self) -> int:
"""Return number of states in the container."""
return len(self._states)
get = __getitem__
def select(self, names: list[str]) -> State | None:
"""Return the first State that exists and has a non-None value, or None."""
for name in names:
if (state := self[name]) and state.value is not None:
return state
return None
def select_value(self, names: list[str]) -> StateType:
"""Return the value of the first State that exists with a non-None value."""
if state := self.select(names):
return state.value
return None
def has_any(self, names: list[str]) -> bool:
"""Return True if any of the given state names exist with a non-None value."""
return self.select(names) is not None
@define(init=False, kw_only=True)
class Command:
"""Represents an OverKiz Command."""
type: int | None = None
name: str | OverkizCommand
parameters: list[str | int | float | OverkizCommandParam] | None
def __init__(
self,
name: str | OverkizCommand,
parameters: list[str | int | float | OverkizCommandParam] | None = None,
type: int | None = None,
**_: Any,
):
"""Initialize a command instance and mirror fields into dict base class."""
self.name = name
self.parameters = parameters
self.type = type
def to_payload(self) -> dict[str, object]:
"""Return a JSON-serializable payload for this command.
The payload uses snake_case keys; the client will convert to camelCase
and apply small key fixes (like `deviceURL`) before sending.
"""
payload: dict[str, object] = {"name": str(self.name)}
if self.type is not None:
payload["type"] = self.type
if self.parameters is not None:
payload["parameters"] = [
p if isinstance(p, (str, int, float, bool)) else str(p)
for p in self.parameters
]
return payload
@define(init=False, kw_only=True)
class Event:
"""Represents an Overkiz event containing metadata and device states."""
name: EventName
timestamp: int | None
setupoid: str | None = field(repr=obfuscate_id, default=None)
owner_key: str | None = field(repr=obfuscate_id, default=None)
type: int | None = None
sub_type: int | None = None
time_to_next_state: int | None = None
failed_commands: list[dict[str, Any]] | None = None
failure_type_code: FailureType | None = None
failure_type: str | None = None
condition_groupoid: str | None = None
place_oid: str | None = None
label: str | None = None
metadata: Any | None = None
camera_id: str | None = None
deleted_raw_devices_count: Any | None = None
protocol_type: Any | None = None
gateway_id: str | None = field(repr=obfuscate_id, default=None)
exec_id: str | None = None
device_url: str | None = field(repr=obfuscate_id, default=None)
device_states: list[EventState]
old_state: ExecutionState | None = None
new_state: ExecutionState | None = None
def __init__(
self,
name: EventName,
timestamp: int | None = None,
setupoid: str | None = field(repr=obfuscate_id, default=None),
owner_key: str | None = None,
type: int | None = None,
sub_type: int | None = None,
time_to_next_state: int | None = None,
failed_commands: list[dict[str, Any]] | None = None,
failure_type_code: FailureType | None = None,
failure_type: str | None = None,
condition_groupoid: str | None = None,
place_oid: str | None = None,
label: str | None = None,
metadata: Any | None = None,
camera_id: str | None = None,
deleted_raw_devices_count: Any | None = None,
protocol_type: Any | None = None,
gateway_id: str | None = None,
exec_id: str | None = None,
device_url: str | None = None,
device_states: list[dict[str, Any]] | None = None,
old_state: ExecutionState | None = None,
new_state: ExecutionState | None = None,
**_: Any,
):
"""Initialize Event from raw Overkiz payload fields."""
self.timestamp = timestamp
self.gateway_id = gateway_id
self.exec_id = exec_id
self.device_url = device_url
self.device_states = (
[EventState(**s) for s in device_states] if device_states else []
)
self.old_state = ExecutionState(old_state) if old_state else None
self.new_state = ExecutionState(new_state) if new_state else None
self.setupoid = setupoid
self.owner_key = owner_key
self.type = type
self.sub_type = sub_type
self.time_to_next_state = time_to_next_state
self.failed_commands = failed_commands
self.failure_type = failure_type
self.condition_groupoid = condition_groupoid
self.place_oid = place_oid
self.label = label
self.metadata = metadata
self.camera_id = camera_id
self.deleted_raw_devices_count = deleted_raw_devices_count
self.protocol_type = protocol_type
self.name = EventName(name)
self.failure_type_code = (
None if failure_type_code is None else FailureType(failure_type_code)
)
@define(init=False, kw_only=True)
class Execution:
"""Execution occurrence with owner, state and action group metadata."""
id: str
description: str
owner: str = field(repr=obfuscate_email)
state: str
action_group: ActionGroup
def __init__(
self,
id: str,
description: str,
owner: str,
state: str,
action_group: dict[str, Any],
**_: Any,
):
"""Initialize Execution object from API fields."""
self.id = id
self.description = description
self.owner = owner
self.state = state
self.action_group = ActionGroup(**action_group)
@define(init=False, kw_only=True)
class Action:
"""An action consists of multiple commands related to a single device, identified by its device URL."""
device_url: str
commands: list[Command]
def __init__(self, device_url: str, commands: list[dict[str, Any] | Command]):
"""Initialize Action from API data and convert nested commands."""
self.device_url = device_url
self.commands = [
c if isinstance(c, Command) else Command(**c) for c in commands
]
def to_payload(self) -> dict[str, object]:
"""Return a JSON-serializable payload for this action (snake_case).
The final camelCase conversion is handled by the client.
"""
return {
"device_url": self.device_url,
"commands": [c.to_payload() for c in self.commands],
}
@define(init=False, kw_only=True)
class ActionGroup:
"""An action group is composed of one or more actions.
Each action is related to a single setup device (designated by its device URL) and
is composed of one or more commands to be executed on that device.
"""
id: str = field(repr=obfuscate_id)
creation_time: int | None = None
last_update_time: int | None = None
label: str = field(repr=obfuscate_string)
metadata: str | None = None
shortcut: bool | None = None
notification_type_mask: int | None = None
notification_condition: str | None = None
notification_text: str | None = None
notification_title: str | None = None
actions: list[Action]
oid: str = field(repr=obfuscate_id)
def __init__(
self,
actions: list[dict[str, Any]],
creation_time: int | None = None,
metadata: str | None = None,
oid: str | None = None,
id: str | None = None,
last_update_time: int | None = None,
label: str | None = None,
shortcut: bool | None = None,
notification_type_mask: int | None = None,
notification_condition: str | None = None,
notification_text: str | None = None,
notification_title: str | None = None,
**_: Any,
) -> None:
"""Initialize ActionGroup from API data and convert nested actions."""
if oid is None and id is None:
raise ValueError("Either 'oid' or 'id' must be provided")
self.id = cast(str, oid or id)
self.creation_time = creation_time
self.last_update_time = last_update_time
self.label = (
label or ""
) # for backwards compatibility we set label to empty string if None
self.metadata = metadata
self.shortcut = shortcut
self.notification_type_mask = notification_type_mask
self.notification_condition = notification_condition
self.notification_text = notification_text
self.notification_title = notification_title
self.actions = [Action(**action) for action in actions]
self.oid = cast(str, oid or id)
@define(init=False, kw_only=True)
class Partner:
"""Partner details for a gateway or service provider."""
activated: bool
name: str
id: str = field(repr=obfuscate_id)
status: str
def __init__(self, activated: bool, name: str, id: str, status: str, **_: Any):
"""Initialize Partner information."""
self.activated = activated
self.name = name
self.id = id
self.status = status
@define(init=False, kw_only=True)
class Connectivity:
"""Connectivity metadata for a gateway update box."""
status: str
protocol_version: str
def __init__(self, status: str, protocol_version: str, **_: Any):
"""Initialize Connectivity information."""
self.status = status
self.protocol_version = protocol_version
@define(init=False, kw_only=True)
class Gateway:
"""Representation of a gateway, including connectivity and partner info."""
partners: list[Partner]
functions: str | None = None
sub_type: GatewaySubType | None = None
id: str = field(repr=obfuscate_id)
gateway_id: str = field(repr=obfuscate_id)
alive: bool | None = None
mode: str | None = None
place_oid: str | None = None
time_reliable: bool | None = None
connectivity: Connectivity
up_to_date: bool | None = None
update_status: UpdateBoxStatus | None = None
sync_in_progress: bool | None = None
type: GatewayType | None = None
def __init__(
self,
*,
partners: list[dict[str, Any]] | None = None,
functions: str | None = None,
sub_type: GatewaySubType | None = None,
gateway_id: str,
alive: bool | None = None,
mode: str | None = None,
place_oid: str | None = None,
time_reliable: bool | None = None,
connectivity: dict[str, Any],
up_to_date: bool | None = None,
update_status: UpdateBoxStatus | None = None,
sync_in_progress: bool | None = None,
type: GatewayType | None = None,
**_: Any,
) -> None:
"""Initialize Gateway from API data and child objects."""
self.id = gateway_id
self.gateway_id = gateway_id
self.functions = functions
self.alive = alive
self.mode = mode
self.place_oid = place_oid
self.time_reliable = time_reliable
self.connectivity = Connectivity(**connectivity)
self.up_to_date = up_to_date
self.update_status = UpdateBoxStatus(update_status) if update_status else None
self.sync_in_progress = sync_in_progress
self.partners = [Partner(**p) for p in partners] if partners else []
self.type = GatewayType(type) if type else None
self.sub_type = GatewaySubType(sub_type) if sub_type else None
@define(init=False, kw_only=True)
class HistoryExecutionCommand:
"""A command within a recorded historical execution, including its status and parameters."""
device_url: str = field(repr=obfuscate_id)
command: str
rank: int