PyFlumeNG 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyflume/models.py ADDED
@@ -0,0 +1,681 @@
1
+ """Portal-shaped Flume resource models.
2
+
3
+ The portal models are deliberately open rather than restrictive. Flume adds
4
+ fields over time, so known fields get typed/defaulted while every unrecognised
5
+ field is retained in the model and included by :meth:`to_dict`.
6
+ """
7
+
8
+ from copy import deepcopy
9
+ from typing import (
10
+ Any,
11
+ Callable,
12
+ ClassVar,
13
+ Dict,
14
+ Generic,
15
+ ItemsView,
16
+ KeysView,
17
+ List,
18
+ Mapping,
19
+ Optional,
20
+ Type,
21
+ TypeVar,
22
+ Union,
23
+ cast,
24
+ overload,
25
+ )
26
+
27
+ from .types import JSONDict, JSONValue, ResourceId
28
+
29
+ ModelT = TypeVar("ModelT", bound="FlumeModel")
30
+ ResponseT = TypeVar("ResponseT")
31
+ ModelFactory = Callable[[Mapping[str, Any]], "FlumeModel"]
32
+
33
+
34
+ class FlumeModel:
35
+ """Open resource model compatible with both attributes and mappings."""
36
+
37
+ defaults: ClassVar[Dict[str, Any]] = {}
38
+ nested: ClassVar[Dict[str, ModelFactory]] = {}
39
+
40
+ def __init__(
41
+ self,
42
+ value: Optional[Mapping[str, Any]] = None,
43
+ **fields: Any,
44
+ ) -> None:
45
+ source = dict(value or {})
46
+ source.update(fields)
47
+ for key, default in self.defaults.items():
48
+ setattr(self, key, deepcopy(default))
49
+ for key, item in source.items():
50
+ model = self.nested.get(key)
51
+ if model is not None and item is not None:
52
+ if isinstance(item, list):
53
+ item = [
54
+ model(value) if isinstance(value, Mapping) else value
55
+ for value in item
56
+ ]
57
+ elif isinstance(item, Mapping):
58
+ item = model(item)
59
+ setattr(self, key, item)
60
+
61
+ def __getitem__(self, key: str) -> Any:
62
+ return getattr(self, key)
63
+
64
+ def __setitem__(self, key: str, value: Any) -> None:
65
+ setattr(self, key, value)
66
+
67
+ def get(self, key: str, default: Any = None) -> Any:
68
+ return getattr(self, key, default)
69
+
70
+ def __eq__(self, other: object) -> bool:
71
+ if isinstance(other, FlumeModel):
72
+ return self.to_dict() == other.to_dict()
73
+ return NotImplemented
74
+
75
+ def keys(self) -> KeysView[str]:
76
+ return self.to_dict().keys()
77
+
78
+ def items(self) -> ItemsView[str, JSONValue]:
79
+ return self.to_dict().items()
80
+
81
+ def to_dict(self) -> JSONDict:
82
+ result: Dict[str, Any] = {}
83
+ for key, value in self.__dict__.items():
84
+ if key.startswith("_"):
85
+ continue
86
+ if isinstance(value, FlumeModel):
87
+ value = value.to_dict()
88
+ elif isinstance(value, list):
89
+ value = [
90
+ item.to_dict() if isinstance(item, FlumeModel) else item
91
+ for item in value
92
+ ]
93
+ result[key] = deepcopy(value)
94
+ return cast(JSONDict, result)
95
+
96
+ def update(self: ModelT, values: Mapping[str, Any]) -> ModelT:
97
+ """Update model fields from a mapping and return the model."""
98
+ for key, value in values.items():
99
+ setattr(self, key, value)
100
+ return self
101
+
102
+ def __repr__(self) -> str:
103
+ return "{0}({1!r})".format(type(self).__name__, self.to_dict())
104
+
105
+
106
+ class FlumeResponse(FlumeModel, Generic[ResponseT]):
107
+ """Flume response envelope with typed data and preserved metadata."""
108
+
109
+ success: bool
110
+ code: Optional[int]
111
+ message: Optional[str]
112
+ http_code: Optional[int]
113
+ http_message: Optional[str]
114
+ detailed: JSONValue
115
+ data: Union[ResponseT, List[ResponseT], JSONValue]
116
+ count: int
117
+ pagination: Optional[JSONDict]
118
+
119
+ defaults = {
120
+ "success": False,
121
+ "code": None,
122
+ "message": None,
123
+ "http_code": None,
124
+ "http_message": None,
125
+ "detailed": None,
126
+ "data": [],
127
+ "count": 0,
128
+ "pagination": None,
129
+ }
130
+
131
+ def __init__(
132
+ self,
133
+ value: Optional[Mapping[str, Any]] = None,
134
+ model: Optional[Type[FlumeModel]] = None,
135
+ ) -> None:
136
+ super().__init__(value)
137
+ if model is not None and isinstance(self.data, list):
138
+ self.data = cast(
139
+ Any,
140
+ modelize(cast(List[Mapping[str, Any]], self.data), model),
141
+ )
142
+ elif model is not None and isinstance(self.data, Mapping):
143
+ self.data = cast(Any, modelize(self.data, model))
144
+
145
+ @property
146
+ def next_url(self) -> Optional[str]:
147
+ pagination = self.pagination or {}
148
+ value = pagination.get("next")
149
+ return value if isinstance(value, str) else None
150
+
151
+ @property
152
+ def previous_url(self) -> Optional[str]:
153
+ pagination = self.pagination or {}
154
+ value = pagination.get("prev")
155
+ return value if isinstance(value, str) else None
156
+
157
+
158
+ class User(FlumeModel):
159
+ """Portal user resource."""
160
+
161
+ id: Optional[ResourceId]
162
+ email_address: str
163
+ first_name: str
164
+ last_name: str
165
+ type: Optional[str]
166
+ phone: Optional[str]
167
+ status: Optional[str]
168
+ signup_datetime: Optional[str]
169
+
170
+ defaults = {
171
+ "id": None,
172
+ "email_address": "",
173
+ "first_name": "",
174
+ "last_name": "",
175
+ "type": None,
176
+ "phone": None,
177
+ "status": None,
178
+ "signup_datetime": None,
179
+ }
180
+
181
+ @property
182
+ def name(self) -> str:
183
+ return " ".join(
184
+ part for part in (self.first_name, self.last_name) if part
185
+ ).strip()
186
+
187
+
188
+ class Location(FlumeModel):
189
+ """Flume location/home resource."""
190
+
191
+ id: Optional[ResourceId]
192
+ user_id: Optional[ResourceId]
193
+ name: str
194
+ primary_location: bool
195
+ address: Optional[str]
196
+ address_2: Optional[str]
197
+ city: Optional[str]
198
+ state: Optional[str]
199
+ postal_code: Optional[str]
200
+ country: Optional[str]
201
+ tz: Optional[str]
202
+ installation: JSONValue
203
+ insurer_id: Optional[ResourceId]
204
+ building_type: Optional[str]
205
+ away_mode: bool
206
+ usage_profile: JSONValue
207
+
208
+ defaults = {
209
+ "id": None,
210
+ "user_id": None,
211
+ "name": "",
212
+ "primary_location": False,
213
+ "address": None,
214
+ "address_2": None,
215
+ "city": None,
216
+ "state": None,
217
+ "postal_code": None,
218
+ "country": None,
219
+ "tz": None,
220
+ "installation": None,
221
+ "insurer_id": None,
222
+ "building_type": None,
223
+ "away_mode": False,
224
+ "usage_profile": None,
225
+ }
226
+
227
+
228
+ class Device(FlumeModel):
229
+ """Flume bridge or water-sensor device."""
230
+
231
+ id: Optional[ResourceId]
232
+ type: Optional[int]
233
+ location_id: Optional[ResourceId]
234
+ user_id: Optional[ResourceId]
235
+ bridge_id: Optional[ResourceId]
236
+ name: Optional[str]
237
+ description: Optional[str]
238
+ registered: Optional[bool]
239
+ added_datetime: Optional[str]
240
+ oriented: bool
241
+ last_seen: str
242
+ connected: bool
243
+ battery_level: Optional[float]
244
+ product: JSONValue
245
+ user: Optional[User]
246
+ location: Optional[Location]
247
+
248
+ defaults = {
249
+ "id": None,
250
+ "type": None,
251
+ "location_id": None,
252
+ "user_id": None,
253
+ "bridge_id": None,
254
+ "name": None,
255
+ "description": None,
256
+ "registered": None,
257
+ "added_datetime": None,
258
+ "oriented": False,
259
+ "last_seen": "",
260
+ "connected": False,
261
+ "battery_level": None,
262
+ "product": None,
263
+ "user": None,
264
+ "location": None,
265
+ }
266
+ nested = {"user": User, "location": Location}
267
+
268
+
269
+ class Notification(FlumeModel):
270
+ """Portal notification resource."""
271
+
272
+ id: Optional[ResourceId]
273
+ device_id: Optional[ResourceId]
274
+ user_id: Optional[ResourceId]
275
+ type: Optional[str]
276
+ message: str
277
+ created_datetime: Optional[str]
278
+ title: str
279
+ read: bool
280
+ extra: JSONValue
281
+ event_rule: JSONValue
282
+
283
+ defaults = {
284
+ "id": None,
285
+ "device_id": None,
286
+ "user_id": None,
287
+ "type": None,
288
+ "message": "",
289
+ "created_datetime": None,
290
+ "title": "",
291
+ "read": False,
292
+ "extra": None,
293
+ "event_rule": None,
294
+ }
295
+
296
+
297
+ class UsageAlert(FlumeModel):
298
+ """Triggered usage-alert event."""
299
+
300
+ id: Optional[ResourceId]
301
+ device_id: Optional[ResourceId]
302
+ triggered_datetime: Optional[str]
303
+ flume_leak: bool
304
+ query: JSONValue
305
+ event_rule_name: Optional[str]
306
+
307
+ defaults = {
308
+ "id": None,
309
+ "device_id": None,
310
+ "triggered_datetime": None,
311
+ "flume_leak": False,
312
+ "query": None,
313
+ "event_rule_name": None,
314
+ }
315
+
316
+
317
+ class QueryResult(FlumeModel):
318
+ """Query result whose keys are the caller-supplied request IDs."""
319
+
320
+
321
+ class CurrentFlow(FlumeModel):
322
+ """Current flow-rate reading."""
323
+
324
+ active: bool
325
+ gpm: float
326
+ datetime: Optional[str]
327
+
328
+ defaults = {"active": False, "gpm": 0.0, "datetime": None}
329
+
330
+
331
+ class ShutoffConfig(FlumeModel):
332
+ """Usage-alert shutoff configuration."""
333
+
334
+ active: bool
335
+
336
+ defaults = {"active": False}
337
+
338
+
339
+ class UsageAlertRule(FlumeModel):
340
+ """Portal usage-alert rule, including portal-derived display helpers."""
341
+
342
+ id: Optional[ResourceId]
343
+ device_id: Optional[ResourceId]
344
+ name: str
345
+ active: bool
346
+ flow_rate: float
347
+ duration: int
348
+ notify_every: int
349
+ advanced_low_flow: bool
350
+ shutoff_config: Optional[ShutoffConfig]
351
+ schedules: List["DoNotAlertSchedule"]
352
+ expected_usage_config: JSONValue
353
+ descHTML: str
354
+ notifyHTML: str
355
+
356
+ defaults = {
357
+ "id": None,
358
+ "device_id": None,
359
+ "name": "",
360
+ "active": False,
361
+ "flow_rate": 0.0,
362
+ "duration": 0,
363
+ "notify_every": 0,
364
+ "advanced_low_flow": False,
365
+ "shutoff_config": None,
366
+ "schedules": [],
367
+ "expected_usage_config": None,
368
+ "descHTML": "",
369
+ "notifyHTML": "",
370
+ }
371
+ nested = {"shutoff_config": ShutoffConfig}
372
+
373
+ @property
374
+ def duration_hour_min(self) -> Dict[str, int]:
375
+ return {"hour": self.duration // 60, "min": self.duration % 60}
376
+
377
+ @duration_hour_min.setter
378
+ def duration_hour_min(self, value: Mapping[str, int]) -> None:
379
+ self.duration = 60 * value["hour"] + value["min"]
380
+
381
+ @property
382
+ def notify_every_day_hour(self) -> Dict[str, int]:
383
+ return {
384
+ "day": self.notify_every // (60 * 24),
385
+ "hour": (self.notify_every // 60) % 24,
386
+ }
387
+
388
+ @notify_every_day_hour.setter
389
+ def notify_every_day_hour(self, value: Mapping[str, int]) -> None:
390
+ self.notify_every = 24 * value["day"] * 60 + 60 * value["hour"]
391
+
392
+
393
+ class Budget(FlumeModel):
394
+ """Daily, weekly, or monthly water budget."""
395
+
396
+ id: Optional[ResourceId]
397
+ name: str
398
+ type: Optional[str]
399
+ value: float
400
+ thresholds: List[JSONValue]
401
+ actual: Optional[float]
402
+
403
+ defaults = {
404
+ "id": None,
405
+ "name": "",
406
+ "type": None,
407
+ "value": 0.0,
408
+ "thresholds": [],
409
+ "actual": None,
410
+ }
411
+
412
+
413
+ class Subscription(FlumeModel):
414
+ """Notification subscription or emergency contact."""
415
+
416
+ id: Optional[ResourceId]
417
+ user_id: Optional[ResourceId]
418
+ alert_type: Optional[str]
419
+ alert_info: JSONValue
420
+ device_id: Optional[ResourceId]
421
+ notification_types: int
422
+ created_datetime: Optional[str]
423
+ updated_datetime: Optional[str]
424
+ emergency_contact: bool
425
+ contact_name: Optional[str]
426
+
427
+ defaults = {
428
+ "id": None,
429
+ "user_id": None,
430
+ "alert_type": None,
431
+ "alert_info": None,
432
+ "device_id": None,
433
+ "notification_types": 0,
434
+ "created_datetime": None,
435
+ "updated_datetime": None,
436
+ "emergency_contact": False,
437
+ "contact_name": None,
438
+ }
439
+
440
+ def has_notification_type(self, notification_type: int) -> bool:
441
+ return bool(self.notification_types & notification_type)
442
+
443
+ def enable_notification_type(self, notification_type: int) -> None:
444
+ self.notification_types |= notification_type
445
+
446
+ def disable_notification_type(self, notification_type: int) -> None:
447
+ self.notification_types &= ~notification_type
448
+
449
+
450
+ class DoNotAlertSchedule(FlumeModel):
451
+ """Portal Do Not Alert schedule."""
452
+
453
+ id: Optional[ResourceId]
454
+ device_id: Optional[ResourceId]
455
+ name: str
456
+ description: str
457
+ currently_active: bool
458
+ start_time: str
459
+ end_time: str
460
+ last_start: str
461
+ last_end: str
462
+ next_start: str
463
+ next_end: str
464
+ span_types: List[JSONValue]
465
+ rrule_str: str
466
+ rrule_obj: JSONDict
467
+ created_datetime: str
468
+ updated_datetime: str
469
+
470
+ defaults = {
471
+ "id": None,
472
+ "device_id": None,
473
+ "name": "",
474
+ "description": "",
475
+ "currently_active": False,
476
+ "start_time": "",
477
+ "end_time": "",
478
+ "last_start": "",
479
+ "last_end": "",
480
+ "next_start": "",
481
+ "next_end": "",
482
+ "span_types": [],
483
+ "rrule_str": "",
484
+ "rrule_obj": {
485
+ "tzid": "",
486
+ "dtstart": "",
487
+ "freq": "",
488
+ "interval": 0,
489
+ "byweekday": [],
490
+ "byhour": 0,
491
+ "byminute": 0,
492
+ "bysecond": 0,
493
+ },
494
+ "created_datetime": "",
495
+ "updated_datetime": "",
496
+ }
497
+
498
+
499
+ class LocationAccess(FlumeModel):
500
+ """Shared location access record."""
501
+
502
+ id: Optional[ResourceId]
503
+ user_id: Optional[ResourceId]
504
+ location_id: Optional[ResourceId]
505
+ email_address: Optional[str]
506
+
507
+ defaults = {
508
+ "id": None,
509
+ "user_id": None,
510
+ "location_id": None,
511
+ "email_address": None,
512
+ }
513
+
514
+
515
+ class Integration(FlumeModel):
516
+ """External device integration, including shutoff valves."""
517
+
518
+ id: Optional[ResourceId]
519
+ type: Optional[str]
520
+ state: JSONValue
521
+ status: JSONValue
522
+ device_id: Optional[ResourceId]
523
+
524
+ defaults = {
525
+ "id": None,
526
+ "type": None,
527
+ "state": None,
528
+ "status": None,
529
+ "device_id": None,
530
+ }
531
+
532
+
533
+ class Span(FlumeModel):
534
+ """Water-usage span/appliance classification."""
535
+
536
+ id: Optional[ResourceId]
537
+ device_id: Optional[ResourceId]
538
+ type: Optional[str]
539
+ start_datetime: Optional[str]
540
+ end_datetime: Optional[str]
541
+
542
+ defaults = {
543
+ "id": None,
544
+ "device_id": None,
545
+ "type": None,
546
+ "start_datetime": None,
547
+ "end_datetime": None,
548
+ }
549
+
550
+
551
+ class SpanType(FlumeModel):
552
+ """Available span classification metadata."""
553
+
554
+ id: Optional[ResourceId]
555
+ name: Optional[str]
556
+ type: Optional[str]
557
+ display: JSONValue
558
+
559
+ defaults = {"id": None, "name": None, "type": None, "display": None}
560
+
561
+
562
+ class Leak(FlumeModel):
563
+ """Leak status or leak event."""
564
+
565
+ id: Optional[ResourceId]
566
+ device_id: Optional[ResourceId]
567
+ active: bool
568
+ created_datetime: Optional[str]
569
+
570
+ defaults = {
571
+ "id": None,
572
+ "device_id": None,
573
+ "active": False,
574
+ "created_datetime": None,
575
+ }
576
+
577
+
578
+ class PurchaseOption(FlumeModel):
579
+ """Device purchase option exposed by the customer portal."""
580
+
581
+ id: Optional[ResourceId]
582
+ type: Optional[str]
583
+ link: Optional[str]
584
+ price: JSONValue
585
+
586
+ defaults = {
587
+ "id": None,
588
+ "type": None,
589
+ "link": None,
590
+ "price": None,
591
+ }
592
+
593
+
594
+ class Contact(FlumeModel):
595
+ """Flume support contact information."""
596
+
597
+ id: Optional[ResourceId]
598
+ category: Optional[str]
599
+ type: Optional[str]
600
+ detail: JSONValue
601
+
602
+ defaults = {"id": None, "category": None, "type": None, "detail": None}
603
+
604
+
605
+ class Insurer(FlumeModel):
606
+ """Undocumented insurer metadata; all returned fields remain accessible."""
607
+
608
+
609
+ class ApiClient(FlumeModel):
610
+ """Undocumented API-client metadata; all returned fields remain accessible."""
611
+
612
+
613
+ class ProService(FlumeModel):
614
+ """Local professional service listing displayed by the portal."""
615
+
616
+ name: Optional[str]
617
+ url: Optional[str]
618
+
619
+ defaults = {"name": None, "url": None}
620
+
621
+
622
+ class AccuracyResult(FlumeModel):
623
+ """Meter-accuracy precheck or comparison result."""
624
+
625
+ type: Optional[str]
626
+ title: Optional[str]
627
+ description: Optional[str]
628
+ accuracy: Optional[float]
629
+ since_url: Optional[str]
630
+ until_url: Optional[str]
631
+ reading_diff: Optional[float]
632
+ queried_diff: Optional[float]
633
+
634
+ defaults = {
635
+ "type": None,
636
+ "title": None,
637
+ "description": None,
638
+ "accuracy": None,
639
+ "since_url": None,
640
+ "until_url": None,
641
+ "reading_diff": None,
642
+ "queried_diff": None,
643
+ }
644
+
645
+
646
+ class LocationProfiles(FlumeModel):
647
+ """Appliance/profile metadata returned by ``/location-profiles``."""
648
+
649
+ residents: JSONValue
650
+ bathrooms: JSONValue
651
+ indoor: List[JSONValue]
652
+ outdoor: List[JSONValue]
653
+
654
+ defaults = {"residents": None, "bathrooms": None, "indoor": [], "outdoor": []}
655
+
656
+
657
+ @overload
658
+ def modelize(value: List[Mapping[str, Any]], model: Type[ModelT]) -> List[ModelT]: ...
659
+
660
+
661
+ @overload
662
+ def modelize(value: Mapping[str, Any], model: Type[ModelT]) -> ModelT: ...
663
+
664
+
665
+ @overload
666
+ def modelize(value: JSONValue, model: None) -> JSONValue: ...
667
+
668
+
669
+ def modelize(value: Any, model: Optional[Type[ModelT]]) -> Any:
670
+ """Convert API data to one model or a list of models."""
671
+ if model is None:
672
+ return value
673
+ if isinstance(value, list):
674
+ return [model(item) if not isinstance(item, model) else item for item in value]
675
+ if isinstance(value, Mapping):
676
+ return model(value)
677
+ return value
678
+
679
+
680
+ # The portal constructs schedules as concrete models nested on usage rules.
681
+ UsageAlertRule.nested["schedules"] = DoNotAlertSchedule