File: v3.py

package info (click to toggle)
simplisafe-python 2024.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,268 kB
  • sloc: python: 5,252; sh: 50; makefile: 19
file content (634 lines) | stat: -rw-r--r-- 20,295 bytes parent folder | download
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
"""Define a V3 (new) SimpliSafe system."""
from __future__ import annotations

from datetime import datetime, timedelta
from enum import Enum
from typing import TYPE_CHECKING, Any, Final, cast

import voluptuous as vol

from simplipy.const import LOGGER
from simplipy.device import DeviceTypes, get_device_type_from_data
from simplipy.device.camera import Camera
from simplipy.device.lock import Lock
from simplipy.device.sensor.v3 import SensorV3
from simplipy.system import (
    CONF_DURESS_PIN,
    CONF_MASTER_PIN,
    DEFAULT_MAX_USER_PINS,
    System,
    SystemStates,
    guard_from_missing_data,
)
from simplipy.util.dt import utcnow

if TYPE_CHECKING:
    from simplipy.api import API

CONF_ALARM_DURATION = "alarm_duration"
CONF_ALARM_VOLUME = "alarm_volume"
CONF_CHIME_VOLUME = "chime_volume"
CONF_ENTRY_DELAY_AWAY = "entry_delay_away"
CONF_ENTRY_DELAY_HOME = "entry_delay_home"
CONF_EXIT_DELAY_AWAY = "exit_delay_away"
CONF_EXIT_DELAY_HOME = "exit_delay_home"
CONF_LIGHT = "light"
CONF_VOICE_PROMPT_VOLUME = "voice_prompt_volume"

DEFAULT_LOCK_STATE_CHANGE_WINDOW = timedelta(seconds=15)

SYSTEM_PROPERTIES_VALUE_MAP = {
    CONF_ALARM_DURATION: "alarmDuration",
    CONF_ALARM_VOLUME: "alarmVolume",
    CONF_CHIME_VOLUME: "doorChime",
    CONF_ENTRY_DELAY_AWAY: "entryDelayAway",
    CONF_ENTRY_DELAY_HOME: "entryDelayHome",
    CONF_EXIT_DELAY_AWAY: "exitDelayAway",
    CONF_EXIT_DELAY_HOME: "exitDelayHome",
    CONF_LIGHT: "light",
    CONF_VOICE_PROMPT_VOLUME: "voicePrompts",
}

MIN_ALARM_DURATION: Final = 30
MAX_ALARM_DURATION: Final = 480
MIN_ENTRY_DELAY_AWAY: Final = 30
MAX_ENTRY_DELAY_AWAY: Final = 255
MIN_ENTRY_DELAY_HOME: Final = 0
MAX_ENTRY_DELAY_HOME: Final = 255
MIN_EXIT_DELAY_AWAY: Final = 45
MAX_EXIT_DELAY_AWAY: Final = 255
MIN_EXIT_DELAY_HOME: Final = 0
MAX_EXIT_DELAY_HOME: Final = 255


class Volume(Enum):
    """Define a representation of a SimpliSafe volume level."""

    OFF = 0
    LOW = 1
    MEDIUM = 2
    HIGH = 3


SYSTEM_PROPERTIES_PAYLOAD_SCHEMA = vol.Schema(
    {
        vol.Optional(CONF_ALARM_DURATION): vol.All(
            vol.Coerce(int), vol.Range(min=MIN_ALARM_DURATION, max=MAX_ALARM_DURATION)
        ),
        vol.Optional(CONF_ALARM_VOLUME): vol.All(Volume, lambda volume: volume.value),
        vol.Optional(CONF_CHIME_VOLUME): vol.All(Volume, lambda volume: volume.value),
        vol.Optional(CONF_ENTRY_DELAY_AWAY): vol.All(
            vol.Coerce(int),
            vol.Range(min=MIN_ENTRY_DELAY_AWAY, max=MAX_ENTRY_DELAY_AWAY),
        ),
        vol.Optional(CONF_ENTRY_DELAY_HOME): vol.All(
            vol.Coerce(int),
            vol.Range(min=MIN_ENTRY_DELAY_HOME, max=MAX_ENTRY_DELAY_HOME),
        ),
        vol.Optional(CONF_EXIT_DELAY_AWAY): vol.All(
            vol.Coerce(int), vol.Range(min=MIN_EXIT_DELAY_AWAY, max=MAX_EXIT_DELAY_AWAY)
        ),
        vol.Optional(CONF_EXIT_DELAY_HOME): vol.All(
            vol.Coerce(int), vol.Range(min=MIN_EXIT_DELAY_HOME, max=MAX_EXIT_DELAY_HOME)
        ),
        vol.Optional(CONF_LIGHT): bool,
        vol.Optional(CONF_VOICE_PROMPT_VOLUME): vol.All(
            Volume, lambda volume: volume.value
        ),
    }
)


def create_pin_payload(pins: dict) -> dict[str, dict[str, dict[str, str]]]:
    """Create the request payload to send for updating PINs.

    Args:
        pins: A dictionary of pins.

    Returns:
        A SimpliSafe V3 PIN payload.
    """
    duress_pin = pins.pop(CONF_DURESS_PIN)
    master_pin = pins.pop(CONF_MASTER_PIN)

    payload = {
        "pins": {
            CONF_DURESS_PIN: {"pin": duress_pin},
            CONF_MASTER_PIN: {"pin": master_pin},
        }
    }

    user_pins = {}
    for idx, (label, pin) in enumerate(pins.items()):
        user_pins[str(idx)] = {"name": label, "pin": pin}

    empty_user_index = len(pins)
    for idx in range(DEFAULT_MAX_USER_PINS - empty_user_index):
        user_pins[str(idx + empty_user_index)] = {
            "name": "",
            "pin": "",
        }

    payload["pins"]["users"] = user_pins

    LOGGER.debug("PIN payload: %s", payload)

    return payload


class SystemV3(System):  # pylint: disable=too-many-public-methods
    """Define a V3 (new) system.

    Note that this class shouldn't be instantiated directly; it will be instantiated as
    appropriate via :meth:`simplipy.API.async_get_systems`.

    Args:
        api: A :meth:`simplipy.API` object.
        sid: A subscription ID.
    """

    def __init__(self, api: API, system_id: int) -> None:
        """Initialize.

        Args:
            api: A :meth:`simplipy.API` object.
            system_id: A system ID.
        """
        super().__init__(api, system_id)

        self._last_state_change_dt: datetime | None = None

        # This will be filled in by the appropriate data update methods:
        self.camera_data: dict[str, dict] = self._generate_camera_data()
        self.cameras: dict[str, Camera] = {}
        self.locks: dict[str, Lock] = {}
        self.settings_data: dict[str, dict] = {}

    @property
    @guard_from_missing_data()
    def alarm_duration(self) -> int | None:
        """Return the number of seconds an activated alarm will sound for.

        Returns:
            The alarm duration.
        """
        return cast(
            int,
            self.settings_data["settings"]["normal"][
                SYSTEM_PROPERTIES_VALUE_MAP["alarm_duration"]
            ],
        )

    @property
    @guard_from_missing_data()
    def alarm_volume(self) -> Volume:
        """Return the volume level of the alarm.

        Returns:
            The alarm volume.
        """
        return Volume(
            int(
                self.settings_data["settings"]["normal"][
                    SYSTEM_PROPERTIES_VALUE_MAP["alarm_volume"]
                ]
            )
        )

    @property
    @guard_from_missing_data()
    def battery_backup_power_level(self) -> int:
        """Return the power rating of the battery backup.

        Returns:
            The battery backup power rating.
        """
        return cast(int, self.settings_data["basestationStatus"]["backupBattery"])

    @property
    @guard_from_missing_data()
    def chime_volume(self) -> Volume:
        """Return the volume level of the door chime.

        Returns:
            The door chime volume.
        """
        return Volume(
            int(
                self.settings_data["settings"]["normal"][
                    SYSTEM_PROPERTIES_VALUE_MAP["chime_volume"]
                ]
            )
        )

    @property
    @guard_from_missing_data()
    def entry_delay_away(self) -> int:
        """Return the number of seconds to delay when returning to an "away" alarm.

        Returns:
            The entry delay when returning to an "away" alarm.
        """
        return cast(
            int,
            self.settings_data["settings"]["normal"][
                SYSTEM_PROPERTIES_VALUE_MAP["entry_delay_away"]
            ],
        )

    @property
    @guard_from_missing_data()
    def entry_delay_home(self) -> int:
        """Return the number of seconds to delay when returning to a "home" alarm.

        Returns:
            The entry delay when returning to a "home" alarm.
        """
        return cast(
            int,
            self.settings_data["settings"]["normal"][
                SYSTEM_PROPERTIES_VALUE_MAP["entry_delay_home"]
            ],
        )

    @property
    @guard_from_missing_data()
    def exit_delay_away(self) -> int:
        """Return the number of seconds to delay when exiting an "away" alarm.

        Returns:
            The exit delay when exiting an "away" alarm.
        """
        return cast(
            int,
            self.settings_data["settings"]["normal"][
                SYSTEM_PROPERTIES_VALUE_MAP["exit_delay_away"]
            ],
        )

    @property
    @guard_from_missing_data()
    def exit_delay_home(self) -> int:
        """Return the number of seconds to delay when exiting an "home" alarm.

        Returns:
            The exit delay when exiting a "home" alarm.
        """
        return cast(
            int,
            self.settings_data["settings"]["normal"][
                SYSTEM_PROPERTIES_VALUE_MAP["exit_delay_home"]
            ],
        )

    @property
    @guard_from_missing_data()
    def gsm_strength(self) -> int:
        """Return the signal strength of the cell antenna.

        Returns:
            The cell antenna strength.
        """
        return cast(int, self.settings_data["basestationStatus"]["gsmRssi"])

    @property
    @guard_from_missing_data()
    def light(self) -> bool:
        """Return whether the base station light is on.

        Returns:
            The light status.
        """
        return cast(
            bool,
            self.settings_data["settings"]["normal"][
                SYSTEM_PROPERTIES_VALUE_MAP["light"]
            ],
        )

    @property
    @guard_from_missing_data(default_value=False)
    def offline(self) -> bool:
        """Return whether the system is offline.

        Returns:
            The offline status.
        """
        return cast(
            bool,
            self._api.subscription_data[self._sid]["location"]["system"]["isOffline"],
        )

    @property
    @guard_from_missing_data(default_value=False)
    def power_outage(self) -> bool:
        """Return whether the system is experiencing a power outage.

        Returns:
            The power outage status.
        """
        return cast(
            bool,
            self._api.subscription_data[self._sid]["location"]["system"]["powerOutage"],
        )

    @property
    @guard_from_missing_data(default_value=False)
    def rf_jamming(self) -> bool:
        """Return whether the base station is noticing RF jamming.

        Returns:
            The RF jamming status.
        """
        return cast(bool, self.settings_data["basestationStatus"]["rfJamming"])

    @property
    @guard_from_missing_data()
    def voice_prompt_volume(self) -> Volume:
        """Return the volume level of the voice prompt.

        Returns:
            The voice prompt volume.
        """
        return Volume(
            int(
                self.settings_data["settings"]["normal"][
                    SYSTEM_PROPERTIES_VALUE_MAP["voice_prompt_volume"]
                ]
            )
        )

    @property
    @guard_from_missing_data()
    def wall_power_level(self) -> int:
        """Return the power rating of the A/C outlet.

        Returns:
            The A/C power rating.
        """
        return cast(int, self.settings_data["basestationStatus"]["wallPower"])

    @property
    @guard_from_missing_data()
    def wifi_ssid(self) -> str:
        """Return the ssid of the base station.

        Returns:
            The connected SSID.
        """
        return cast(str, self.settings_data["settings"]["normal"]["wifiSSID"])

    @property
    @guard_from_missing_data()
    def wifi_strength(self) -> int:
        """Return the signal strength of the wifi antenna.

        Returns:
            The WiFi strength.
        """
        return cast(int, self.settings_data["basestationStatus"]["wifiRssi"])

    async def _async_clear_notifications(self) -> None:
        """Clear active notifications."""
        await self._api.async_request(
            "delete", f"ss3/subscriptions/{self.system_id}/messages"
        )

    async def _async_set_state(self, value: SystemStates) -> None:
        """Set the state of the system.

        Args:
            value: A :meth:`simplipy.system.SystemStates` object.
        """
        await self._api.async_request(
            "post", f"ss3/subscriptions/{self.system_id}/state/{value.name.lower()}"
        )

        self._state = value
        self._last_state_change_dt = utcnow()

    async def _async_set_updated_pins(self, pins: dict[str, Any]) -> None:
        """Post new PINs.

        Args:
            pins: A dictionary of PINs.
        """
        self.settings_data = await self._api.async_request(
            "post",
            f"ss3/subscriptions/{self.system_id}/settings/pins",
            json=create_pin_payload(pins),
        )

    async def _async_update_device_data(self, cached: bool = True) -> None:
        """Update all device data.

        Args:
            cached: Whether to update with cached data.
        """
        sensor_resp = await self._api.async_request(
            "get",
            f"ss3/subscriptions/{self.system_id}/sensors",
            params={"forceUpdate": str(not cached).lower()},
        )
        self.sensor_data = {
            sensor["serial"]: sensor for sensor in sensor_resp.get("sensors", [])
        }

    async def _async_update_settings_data(self, cached: bool = True) -> None:
        """Update all settings data.

        Args:
            cached: Whether to update with cached data.
        """
        settings_resp = await self._api.async_request(
            "get",
            f"ss3/subscriptions/{self.system_id}/settings/normal",
            params={"forceUpdate": str(not cached).lower()},
        )

        if settings_resp:
            self.settings_data = settings_resp

    async def _async_update_subscription_data(self) -> None:
        """Update subscription data."""
        await super()._async_update_subscription_data()
        self.camera_data = self._generate_camera_data()

    def _generate_camera_data(self) -> dict[str, dict]:
        """Generate usable, hashable camera data from subscription data.

        This method exists because the SimpliSafe API includes camera data with the
        subscription (and not with other devices); by splitting this out, we can
        separate this action from updating the subscription data itself.

        Returns:
            A dictionary of camera UUID to camera data.
        """
        return {
            camera["uuid"]: camera
            for camera in self._api.subscription_data[self._sid]["location"][
                "system"
            ].get("cameras", [])
        }

    def as_dict(self) -> dict[str, Any]:
        """Return dictionary version of this device.

        Returns:
            A dict representation of this device.
        """
        data = {
            **super().as_dict(),
            "alarm_duration": self.alarm_duration,
            "battery_backup_power_level": self.battery_backup_power_level,
            "cameras": [camera.as_dict() for camera in self.cameras.values()],
            "entry_delay_away": self.entry_delay_away,
            "entry_delay_home": self.entry_delay_home,
            "exit_delay_away": self.exit_delay_away,
            "exit_delay_home": self.exit_delay_home,
            "gsm_strength": self.gsm_strength,
            "light": self.light,
            "locks": [lock.as_dict() for lock in self.locks.values()],
            "offline": self.offline,
            "power_outage": self.power_outage,
            "rf_jamming": self.rf_jamming,
            "wall_power_level": self.wall_power_level,
            "wifi_ssid": self.wifi_ssid,
            "wifi_strength": self.wifi_strength,
        }

        for key, volume_enum in (
            ("alarm_volume", self.alarm_volume),
            ("chime_volume", self.chime_volume),
            ("voice_prompt_volume", self.voice_prompt_volume),
        ):
            if volume_enum:
                data[key] = volume_enum.value

        return data

    def generate_device_objects(self) -> None:
        """Generate device objects for this system."""
        for serial, sensor in self.sensor_data.items():
            if (sensor_type := get_device_type_from_data(sensor)) == DeviceTypes.LOCK:
                self.locks[serial] = Lock(
                    self._api.async_request, self, sensor_type, serial
                )
            else:
                self.sensors[serial] = SensorV3(self, sensor_type, serial)

        for serial in self.camera_data:
            self.cameras[serial] = Camera(self, DeviceTypes.CAMERA, serial)

    async def async_get_pins(self, cached: bool = True) -> dict[str, str]:
        """Return all of the set PINs, including master and duress.

        The ``cached`` parameter determines whether the SimpliSafe Cloud uses the last
        known values retrieved from the base station (``True``) or retrieves new data.

        Args:
            cached: Whether to update with cached data.

        Returns:
            A dictionary of PINs.
        """
        await self._async_update_settings_data(cached)

        pins = {
            CONF_MASTER_PIN: self.settings_data["settings"]["pins"]["master"]["pin"],
            CONF_DURESS_PIN: self.settings_data["settings"]["pins"]["duress"]["pin"],
        }

        for user_pin in [
            p for p in self.settings_data["settings"]["pins"]["users"] if p["pin"]
        ]:
            pins[user_pin["name"]] = user_pin["pin"]

        return pins

    async def async_set_properties(
        self, properties: dict[str, bool | int | Volume]
    ) -> None:
        """Set various system properties.

        Volume properties should take values from :meth:`simplipy.system.v3.Volume`.

        The following properties can be set:
           1. alarm_duration (in seconds): 30-480
           2. alarm_volume: Volume.OFF, Volume.LOW, Volume.MEDIUM, Volume.HIGH
           3. chime_volume: Volume.OFF, Volume.LOW, Volume.MEDIUM, Volume.HIGH
           4. entry_delay_away (in seconds): 30-255
           5. entry_delay_home (in seconds): 0-255
           6. exit_delay_away (in seconds): 45-255
           7. exit_delay_home (in seconds): 0-255
           8. light: True or False
           9. voice_prompt_volume: Volume.OFF, Volume.LOW, Volume.MEDIUM, Volume.HIGH

        Args:
            properties: The system properties to set.

        Raises:
            ValueError: Raised on invalid properties.
        """
        try:
            parsed_properties = SYSTEM_PROPERTIES_PAYLOAD_SCHEMA(properties)
        except vol.Invalid as err:
            raise ValueError(
                f"Using invalid values for system properties ({properties}): {err}"
            ) from None

        settings_resp = await self._api.async_request(
            "post",
            f"ss3/subscriptions/{self.system_id}/settings/normal",
            json={
                "normal": {
                    SYSTEM_PROPERTIES_VALUE_MAP[prop]: value
                    for prop, value in parsed_properties.items()
                }
            },
        )

        if settings_resp:
            self.settings_data = settings_resp

    async def async_update(
        self,
        *,
        include_subscription: bool = True,
        include_settings: bool = True,
        include_devices: bool = True,
        cached: bool = True,
    ) -> None:
        """Get the latest system data.

        The ``cached`` parameter determines whether the SimpliSafe Cloud uses the last
        known values retrieved from the base station (``True``) or retrieves new data.

        Args:
            include_subscription: Whether system state/properties should be updated.
            include_settings: Whether system settings (like PINs) should be updated.
            include_devices: whether sensors/locks/etc. should be updated.
            cached: Whether to used cached data.
        """
        if (
            self.locks
            and self._last_state_change_dt
            and utcnow()
            <= self._last_state_change_dt + DEFAULT_LOCK_STATE_CHANGE_WINDOW
        ):
            # The SimpliSafe cloud API currently has a bug wherein systems with locks
            # will audible announce that those locks aren't responding when the system
            # is updated within a certain window (around 15 seconds) of the system
            # changing state. Oof. So, we refuse to update inside that window:
            LOGGER.info(
                "Skipping system update within %s seconds from last system arm/disarm",
                DEFAULT_LOCK_STATE_CHANGE_WINDOW,
            )
            return

        await super().async_update(
            include_subscription=include_subscription,
            include_settings=include_settings,
            include_devices=include_devices,
            cached=cached,
        )