python-ring 0.10.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.
python_ring/generic.py ADDED
@@ -0,0 +1,267 @@
1
+ # vim:sw=4:ts=4:et:
2
+ """Python Ring RingGeneric wrapper."""
3
+
4
+ # pylint: disable=useless-object-inheritance
5
+ from __future__ import annotations
6
+
7
+ import logging
8
+ from typing import TYPE_CHECKING, Any, ClassVar
9
+
10
+ import pytz
11
+
12
+ from python_ring.const import URL_DOORBELL_HISTORY, RingCapability
13
+ from python_ring.util import (
14
+ parse_datetime,
15
+ )
16
+
17
+ _LOGGER = logging.getLogger(__name__)
18
+
19
+
20
+ class RingGeneric:
21
+ """Generic Implementation for Ring Chime/Doorbell."""
22
+
23
+ if TYPE_CHECKING:
24
+ from python_ring.ring import Ring
25
+
26
+ def __init__(self, ring: Ring, device_api_id: int) -> None:
27
+ """Initialize Ring Generic."""
28
+ self._ring = ring
29
+ # This is the account ID of the device.
30
+ # Not the same as device ID.
31
+ self.device_api_id = device_api_id
32
+ self.capability = False
33
+ self.alert = None
34
+ self._health_attrs: dict[str, Any] = {}
35
+ self._last_history: list[dict[str, Any]] = []
36
+
37
+ # alerts notifications
38
+ self.alert_expires_at = None
39
+
40
+ def __repr__(self) -> str:
41
+ """Return __repr__."""
42
+ return f"<{self.__class__.__name__}: {self.name}>"
43
+
44
+ def __str__(self) -> str:
45
+ """Return string representation of device."""
46
+ return f"{self.name} ({self.kind})"
47
+
48
+ async def async_update(self) -> None:
49
+ """Update this device info."""
50
+ await self.async_update_health_data()
51
+
52
+ async def async_update_health_data(self) -> None:
53
+ """Update the health data."""
54
+ raise NotImplementedError
55
+
56
+ @property
57
+ def _attrs(self) -> dict[str, Any]:
58
+ """Return attributes."""
59
+ return self._ring.devices_data[self.family][self.device_api_id]
60
+
61
+ @property
62
+ def id(self) -> int:
63
+ """Return ID."""
64
+ return self.device_api_id
65
+
66
+ @property
67
+ def name(self) -> str:
68
+ """Return name."""
69
+ return self._attrs["description"]
70
+
71
+ @property
72
+ def device_id(self) -> str:
73
+ """Return device ID.
74
+
75
+ This is the device_id returned by the api, usually the MAC.
76
+ Not to be confused with the id for the device
77
+ """
78
+ return self._attrs["device_id"]
79
+
80
+ @property
81
+ def location_id(self) -> str | None:
82
+ """Return location id."""
83
+ return self._attrs.get("location_id", None)
84
+
85
+ @property
86
+ def family(self) -> str:
87
+ """Return Ring device family type."""
88
+ raise NotImplementedError
89
+
90
+ @property
91
+ def model(self) -> str:
92
+ """Return Ring device model name."""
93
+ raise NotImplementedError
94
+
95
+ @property
96
+ def battery_life(self) -> int | None:
97
+ """Return battery life."""
98
+ raise NotImplementedError
99
+
100
+ def has_capability(self, capability: RingCapability | str) -> bool: # noqa: ARG002
101
+ """Return if device has specific capability."""
102
+ return self.capability
103
+
104
+ @property
105
+ def address(self) -> str | None:
106
+ """Return address."""
107
+ return self._attrs.get("address")
108
+
109
+ @property
110
+ def firmware(self) -> str | None:
111
+ """Return firmware."""
112
+ return self._attrs.get("firmware_version")
113
+
114
+ @property
115
+ def latitude(self) -> float | None:
116
+ """Return latitude attr."""
117
+ return self._attrs.get("latitude")
118
+
119
+ @property
120
+ def longitude(self) -> float | None:
121
+ """Return longitude attr."""
122
+ return self._attrs.get("longitude")
123
+
124
+ @property
125
+ def kind(self) -> str:
126
+ """Return kind attr."""
127
+ return self._attrs["kind"]
128
+
129
+ @property
130
+ def timezone(self) -> str | None:
131
+ """Return timezone."""
132
+ return self._attrs.get("time_zone")
133
+
134
+ @property
135
+ def wifi_name(self) -> str | None:
136
+ """Return wifi ESSID name.
137
+
138
+ Requires health data to be updated.
139
+ """
140
+ return self._health_attrs.get("wifi_name")
141
+
142
+ @property
143
+ def wifi_signal_strength(self) -> int | None:
144
+ """Return wifi RSSI.
145
+
146
+ Requires health data to be updated.
147
+ """
148
+ return self._health_attrs.get("latest_signal_strength")
149
+
150
+ @property
151
+ def wifi_signal_category(self) -> str | None:
152
+ """Return wifi signal category.
153
+
154
+ Requires health data to be updated.
155
+ """
156
+ return self._health_attrs.get("latest_signal_category")
157
+
158
+ @property
159
+ def last_history(self) -> list[dict[str, Any]]:
160
+ """Return the result of the last history query."""
161
+ return self._last_history
162
+
163
+ async def async_history( # noqa: C901, PLR0913, PLR0912
164
+ self,
165
+ *,
166
+ limit: int = 30,
167
+ timezone: str | None = None,
168
+ kind: str | None = None,
169
+ enforce_limit: bool = False,
170
+ older_than: int | None = None,
171
+ retry: int = 8,
172
+ convert_timezone: bool = True,
173
+ ) -> list[dict[str, Any]]:
174
+ """
175
+ Return history with datetime objects.
176
+
177
+ :param limit: specify number of objects to be returned
178
+ :param timezone: determine which timezone to convert data objects
179
+ :param kind: filter by kind (ding, motion, on_demand)
180
+ :param enforce_limit: when True, this will enforce the limit and kind
181
+ :param older_than: return older objects than the passed event_id
182
+ :param retry: determine the max number of attempts to archive the limit
183
+ """
184
+ if not self.has_capability("history"):
185
+ return []
186
+
187
+ queries = 0
188
+ original_limit = limit
189
+
190
+ # set cap for max queries
191
+ # pylint:disable=consider-using-min-builtin
192
+ retry = min(retry, 10)
193
+
194
+ while True:
195
+ params = {"limit": limit}
196
+ if older_than:
197
+ params["older_than"] = older_than
198
+
199
+ url = URL_DOORBELL_HISTORY.format(self.device_api_id)
200
+ resp = await self._ring.async_query(url, extra_params=params)
201
+ response = resp.json()
202
+
203
+ # cherrypick only the selected kind events
204
+ if kind:
205
+ response = list(filter(lambda array: array["kind"] == kind, response))
206
+
207
+ if convert_timezone:
208
+ # convert for specific timezone
209
+ if timezone:
210
+ mytz = pytz.timezone(timezone)
211
+
212
+ for entry in response:
213
+ utc_dt = parse_datetime(entry["created_at"])
214
+ if timezone:
215
+ tz_dt = utc_dt.astimezone(mytz)
216
+ entry["created_at"] = tz_dt
217
+ else:
218
+ entry["created_at"] = utc_dt
219
+
220
+ if enforce_limit:
221
+ # return because already matched the number
222
+ # of events by kind
223
+ if len(response) >= original_limit:
224
+ return response[:original_limit]
225
+
226
+ # ensure the loop will exit after max queries
227
+ queries += 1
228
+ if queries == retry:
229
+ _LOGGER.debug(
230
+ "Could not find total of %s of kind %s", original_limit, kind
231
+ )
232
+ break
233
+
234
+ # ensure the kind objects returned to match limit
235
+ limit = limit * 2
236
+
237
+ else:
238
+ break
239
+
240
+ self._last_history = response
241
+ return self._last_history
242
+
243
+ DEPRECATED_API_QUERIES: ClassVar = {
244
+ "history",
245
+ "update",
246
+ "update_health_data",
247
+ }
248
+ DEPRECATED_API_PROPERTY_GETTERS: ClassVar[set[str]] = set()
249
+ DEPRECATED_API_PROPERTY_SETTERS: ClassVar[set[str]] = set()
250
+
251
+ if not TYPE_CHECKING:
252
+
253
+ def __getattr__(self, name: str) -> Any:
254
+ """Get a deprecated attribute or raise an error."""
255
+ if name in self.DEPRECATED_API_QUERIES:
256
+ return self._ring.auth._dep_handler.get_api_query(self, name) # noqa: SLF001
257
+ if name in self.DEPRECATED_API_PROPERTY_GETTERS:
258
+ return self._ring.auth._dep_handler.get_api_property(self, name) # noqa: SLF001
259
+ msg = f"{self.__class__.__name__} has no attribute {name!r}"
260
+ raise AttributeError(msg)
261
+
262
+ def __setattr__(self, name: str, value: Any) -> None:
263
+ """Set a deprecated attribute or raise an error."""
264
+ if name in self.DEPRECATED_API_PROPERTY_SETTERS:
265
+ self._ring.auth._dep_handler.set_api_property(self, name, value) # noqa: SLF001
266
+ else:
267
+ super().__setattr__(name, value)
python_ring/group.py ADDED
@@ -0,0 +1,145 @@
1
+ # vim:sw=4:ts=4:et:
2
+ """Python Ring light group wrapper."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import logging
7
+ import warnings
8
+ from typing import TYPE_CHECKING, Any, ClassVar
9
+
10
+ from python_ring.const import (
11
+ GROUP_DEVICES_ENDPOINT,
12
+ MSG_ALLOWED_VALUES,
13
+ RingCapability,
14
+ )
15
+ from python_ring.exceptions import RingError
16
+
17
+ _LOGGER = logging.getLogger(__name__)
18
+
19
+
20
+ class RingLightGroup:
21
+ """Implementation for RingLightGroup."""
22
+
23
+ if TYPE_CHECKING:
24
+ from python_ring.ring import Ring
25
+
26
+ def __init__(self, ring: Ring, group_id: str) -> None:
27
+ """Initialize Ring Light Group."""
28
+ self._ring = ring
29
+ self.group_id = group_id # pylint:disable=invalid-name
30
+ self._health_attrs: dict[str, Any] = {}
31
+ self._health_attrs_fetched = False
32
+
33
+ def __repr__(self) -> str:
34
+ """Return __repr__."""
35
+ return f"<{self.__class__.__name__}: {self.name}>"
36
+
37
+ async def async_update(self) -> None:
38
+ """Update this device info."""
39
+ url = GROUP_DEVICES_ENDPOINT.format(self.location_id, self.group_id)
40
+ resp = await self._ring.async_query(url)
41
+ self._health_attrs = resp.json()
42
+ self._health_attrs_fetched = True
43
+
44
+ @property
45
+ def _attrs(self) -> dict[str, Any]:
46
+ """Return attributes."""
47
+ return self._ring.groups_data[self.group_id]
48
+
49
+ @property
50
+ def id(self) -> str:
51
+ """Return ID."""
52
+ return self.group_id
53
+
54
+ @property
55
+ def name(self) -> str:
56
+ """Return name."""
57
+ return self._attrs["name"]
58
+
59
+ @property
60
+ def family(self) -> str:
61
+ """Return Ring device family type."""
62
+ return "group"
63
+
64
+ @property
65
+ def device_id(self) -> str:
66
+ """Return group ID. Deprecated."""
67
+ warnings.warn(
68
+ "RingLightGroup.device_id is deprecated; use group_id",
69
+ DeprecationWarning,
70
+ stacklevel=1,
71
+ )
72
+ return self.group_id
73
+
74
+ @property
75
+ def location_id(self) -> str:
76
+ """Return group location ID."""
77
+ return self._attrs["location_id"]
78
+
79
+ @property
80
+ def model(self) -> str:
81
+ """Return Ring device model name."""
82
+ return "Light Group"
83
+
84
+ def has_capability(self, capability: RingCapability | str) -> bool:
85
+ """Return if device has specific capability."""
86
+ capability = (
87
+ capability
88
+ if isinstance(capability, RingCapability)
89
+ else RingCapability.from_name(capability)
90
+ )
91
+ return capability == RingCapability.LIGHT
92
+
93
+ @property
94
+ def lights(self) -> bool:
95
+ """Return lights status."""
96
+ if not self._health_attrs_fetched:
97
+ msg = (
98
+ "You need to call update on the "
99
+ "group before accessing the lights property."
100
+ )
101
+ raise RingError(msg)
102
+ return self._health_attrs["lights_on"]
103
+
104
+ async def async_set_lights(
105
+ self,
106
+ state: bool | tuple[bool, int],
107
+ duration: int | None = None,
108
+ ) -> None:
109
+ """Control the lights."""
110
+ values = ["True", "False"]
111
+ if isinstance(state, tuple):
112
+ state, duration = state
113
+
114
+ if not isinstance(state, bool):
115
+ raise RingError(MSG_ALLOWED_VALUES.format(", ".join(values)))
116
+
117
+ url = GROUP_DEVICES_ENDPOINT.format(self.location_id, self.group_id)
118
+ payload: dict[str, dict[str, bool | int]] = {"lights_on": {"enabled": state}}
119
+ if duration is not None:
120
+ payload["lights_on"]["duration_seconds"] = duration
121
+ await self._ring.async_query(url, method="POST", json=payload)
122
+ await self.async_update()
123
+
124
+ DEPRECATED_API_QUERIES: ClassVar = {
125
+ "update",
126
+ }
127
+ DEPRECATED_API_PROPERTY_SETTERS: ClassVar = {
128
+ "lights",
129
+ }
130
+
131
+ if not TYPE_CHECKING:
132
+
133
+ def __getattr__(self, name: str) -> Any:
134
+ """Get a deprecated attribute or raise an error."""
135
+ if name in self.DEPRECATED_API_QUERIES:
136
+ return self._ring.auth._dep_handler.get_api_query(self, name) # noqa: SLF001
137
+ msg = f"{self.__class__.__name__} has no attribute {name!r}"
138
+ raise AttributeError(msg)
139
+
140
+ def __setattr__(self, name: str, value: Any) -> None:
141
+ """Set a deprecated attribute or raise an error."""
142
+ if name in self.DEPRECATED_API_PROPERTY_SETTERS:
143
+ self._ring.auth._dep_handler.set_api_property(self, name, value) # noqa: SLF001
144
+ else:
145
+ super().__setattr__(name, value)
@@ -0,0 +1,13 @@
1
+ """Package for listener modules."""
2
+
3
+ from .eventlistener import RingEventListener
4
+ from .listenerconfig import RingEventListenerConfig
5
+
6
+ # can_listen used to be checkable to see if the optional listen extra installed.
7
+ # Now installed as default.
8
+ can_listen = True
9
+
10
+ __all__ = [
11
+ "RingEventListener",
12
+ "RingEventListenerConfig",
13
+ ]