Debian Codegraph @

async_upnp_client/profiles/profile.py

raw
1 """async_upnp_client.profiles.profile module."""
2
3 import asyncio
4 import logging
5 import time
6 from datetime import timedelta
7 from typing import Any, Sequence
8
9 from async_upnp_client.client import (
10 EventCallbackType,
11 UpnpAction,
12 UpnpDevice,
13 UpnpService,
14 UpnpStateVariable,
15 UpnpValueError,
16 )
17 from async_upnp_client.const import AddressTupleVXType
18 from async_upnp_client.event_handler import UpnpEventHandler
19 from async_upnp_client.exceptions import (
20 UpnpConnectionError,
21 UpnpError,
22 UpnpResponseError,
23 )
24 from async_upnp_client.search import async_search
25 from async_upnp_client.ssdp import SSDP_MX
26 from async_upnp_client.utils import CaseInsensitiveDict
27
28 _LOGGER = logging.getLogger(__name__)
29
30
31 SUBSCRIBE_TIMEOUT = timedelta(minutes=9)
32 RESUBSCRIBE_TOLERANCE = timedelta(minutes=1)
33 RESUBSCRIBE_TOLERANCE_SECS = RESUBSCRIBE_TOLERANCE.total_seconds()
34
35
36 def find_device_of_type(device: UpnpDevice, device_types: list[str]) -> UpnpDevice:
37 """Find the (embedded) UpnpDevice of any of the device types."""
38 for device_ in device.all_devices:
39 if device_.device_type in device_types:
40 return device_
41
42 raise UpnpError(f"Could not find device of type: {device_types}")
43
44
45 class UpnpProfileDevice:
46 """
47 Base class for UpnpProfileDevices.
48
49 Override _SERVICE_TYPES for aliases. Override SERVICE_IDS for required
50 service_id values.
51 """
52
53 DEVICE_TYPES: list[str] = []
54
55 SERVICE_IDS: frozenset[str] = frozenset()
56
57 _SERVICE_TYPES: dict[str, set[str]] = {}
58
59 @classmethod
60 async def async_search(
61 cls, source: AddressTupleVXType | None = None, timeout: int = SSDP_MX
62 ) -> set[CaseInsensitiveDict]:
63 """
64 Search for this device type.
65
66 This only returns search info, not a profile itself.
67
68 :param source_ip Source IP to scan from
69 :param timeout Timeout to use
70 :return: Set of devices (dicts) found
71 """
72 responses = set()
73
74 async def on_response(data: CaseInsensitiveDict) -> None:
75 if "st" in data and data["st"] in cls.DEVICE_TYPES:
76 responses.add(data)
77
78 await async_search(async_callback=on_response, source=source, timeout=timeout)
79
80 return responses
81
82 @classmethod
83 async def async_discover(cls) -> set[CaseInsensitiveDict]:
84 """Alias for async_search."""
85 return await cls.async_search()
86
87 @classmethod
88 def is_profile_device(cls, device: UpnpDevice) -> bool:
89 """Check for device's support of the profile defined in this (sub)class.
90
91 The device must be (or have an embedded device) that matches the class
92 device type, and it must provide all services that are defined by this
93 class.
94 """
95 try:
96 profile_device = find_device_of_type(device, cls.DEVICE_TYPES)
97 except UpnpError:
98 return False
99
100 # Check that every service required by the subclass is declared by the device
101 device_service_ids = {service.service_id for service in profile_device.all_services}
102 if not cls.SERVICE_IDS.issubset(device_service_ids):
103 return False
104
105 return True
106
107 def __init__(self, device: UpnpDevice, event_handler: UpnpEventHandler | None) -> None:
108 """Initialize."""
109 self.device = device
110 self.profile_device = find_device_of_type(device, self.DEVICE_TYPES)
111 self._event_handler = event_handler
112 self.on_event: EventCallbackType | None = None
113 self._icon: str | None = None
114 # Map of SID to renewal timestamp (monotonic clock seconds)
115 self._subscriptions: dict[str, float] = {}
116 self._resubscriber_task: asyncio.Task | None = None
117
118 @property
119 def name(self) -> str:
120 """Get the name of the device."""
121 return self.profile_device.name
122
123 @property
124 def manufacturer(self) -> str:
125 """Get the manufacturer of this device."""
126 return self.profile_device.manufacturer
127
128 @property
129 def model_description(self) -> str | None:
130 """Get the model description of this device."""
131 return self.profile_device.model_description
132
133 @property
134 def model_name(self) -> str:
135 """Get the model name of this device."""
136 return self.profile_device.model_name
137
138 @property
139 def model_number(self) -> str | None:
140 """Get the model number of this device."""
141 return self.profile_device.model_number
142
143 @property
144 def serial_number(self) -> str | None:
145 """Get the serial number of this device."""
146 return self.profile_device.serial_number
147
148 @property
149 def udn(self) -> str:
150 """Get the UDN of the device."""
151 return self.profile_device.udn
152
153 @property
154 def device_type(self) -> str:
155 """Get the device type of this device."""
156 return self.profile_device.device_type
157
158 @property
159 def icon(self) -> str | None:
160 """Get a URL for the biggest icon for this device."""
161 if not self.profile_device.icons:
162 return None
163
164 if not self._icon:
165 icon_mime_preference = {"image/png": 3, "image/jpeg": 2, "image/gif": 1}
166 icons = [icon for icon in self.profile_device.icons if icon.url]
167 icons = sorted(
168 icons,
169 # Sort by area, then colour depth, then preferred mimetype
170 key=lambda icon: (
171 icon.width * icon.height,
172 icon.depth,
173 icon_mime_preference.get(icon.mimetype, 0),
174 ),
175 reverse=True,
176 )
177 self._icon = icons[0].url
178
179 return self._icon
180
181 def _service(self, service_type_abbreviation: str) -> UpnpService | None:
182 """Get UpnpService by service_type or alias."""
183 if not self.profile_device:
184 return None
185
186 if service_type_abbreviation not in self._SERVICE_TYPES:
187 return None
188
189 for service_type in self._SERVICE_TYPES[service_type_abbreviation]:
190 service = self.profile_device.find_service(service_type)
191 if service:
192 return service
193
194 return None
195
196 def _state_variable(self, service_name: str, state_variable_name: str) -> UpnpStateVariable | None:
197 """Get state_variable from service."""
198 service = self._service(service_name)
199 if not service:
200 return None
201
202 if not service.has_state_variable(state_variable_name):
203 return None
204
205 return service.state_variable(state_variable_name)
206
207 def _action(self, service_name: str, action_name: str) -> UpnpAction | None:
208 """Check if service has action."""
209 service = self._service(service_name)
210 if not service:
211 return None
212
213 if not service.has_action(action_name):
214 return None
215
216 return service.action(action_name)
217
218 def _interesting_service(self, service: UpnpService) -> bool:
219 """Check if service is a service we're interested in."""
220 service_type = service.service_type
221 for service_types in self._SERVICE_TYPES.values():
222 if service_type in service_types:
223 return True
224
225 return False
226
227 async def _async_resubscribe_services(self, now: float | None = None, notify_errors: bool = False) -> None:
228 """Renew existing subscriptions.
229
230 :param now: time.monotonic reference for current time
231 :param notify_errors: Call on_event in case of error instead of raising
232 """
233 assert self._event_handler
234
235 if now is None:
236 now = time.monotonic()
237 renewal_threshold = now - RESUBSCRIBE_TOLERANCE_SECS
238
239 _LOGGER.debug("Resubscribing to services with threshold %f", renewal_threshold)
240
241 for sid, renewal_time in list(self._subscriptions.items()):
242 if renewal_time < renewal_threshold:
243 _LOGGER.debug("Dropping stale subscription %s with renewal_time %f", sid, renewal_time)
244 del self._subscriptions[sid]
245 service = self._event_handler.service_for_sid(sid)
246 if service and notify_errors:
247 self._on_event(service, [])
248 continue
249
250 _LOGGER.debug("Resubscribing to %s with renewal_time %f", sid, renewal_time)
251 # Subscription is going to be changed, no matter what
252 del self._subscriptions[sid]
253 # Determine service for on_event call in case of failure
254 service = self._event_handler.service_for_sid(sid)
255 if not service:
256 _LOGGER.error("Subscription for %s was lost", sid)
257 continue
258
259 try:
260 new_sid, timeout = await self._event_handler.async_resubscribe(sid, timeout=SUBSCRIBE_TIMEOUT)
261 except UpnpError as err:
262 if isinstance(err, UpnpConnectionError):
263 # Device has gone offline
264 self.profile_device.available = False
265 _LOGGER.warning("Failed (re-)subscribing to: %s, reason: %r", sid, err)
266 if notify_errors:
267 # Notify event listeners that something has changed
268 self._on_event(service, [])
269 else:
270 raise
271 else:
272 self._subscriptions[new_sid] = now + timeout.total_seconds()
273
274 async def _resubscribe_loop(self) -> None:
275 """Periodically resubscribes to current subscriptions."""
276 _LOGGER.debug("_resubscribe_loop started")
277 while self._subscriptions:
278 next_renewal = min(self._subscriptions.values())
279 wait_time = next_renewal - time.monotonic() - RESUBSCRIBE_TOLERANCE_SECS
280 _LOGGER.debug("Resubscribing in %f seconds", wait_time)
281 if wait_time > 0:
282 await asyncio.sleep(wait_time)
283
284 await self._async_resubscribe_services(notify_errors=True)
285
286 _LOGGER.debug("_resubscribe_loop ended because of no subscriptions")
287
288 async def _update_resubscriber_task(self) -> None:
289 """Start or stop the resubscriber task, depending on having subscriptions."""
290 # Clear out done task to make later logic easier
291 if self._resubscriber_task and self._resubscriber_task.cancelled():
292 self._resubscriber_task = None
293
294 if self._subscriptions and not self._resubscriber_task:
295 _LOGGER.debug("Creating resubscribe_task")
296 # pylint: disable=fixme
297 self._resubscriber_task = asyncio.create_task(
298 self._resubscribe_loop(),
299 name=f"UpnpProfileDevice({self.name})._resubscriber_task",
300 )
301
302 if not self._subscriptions and self._resubscriber_task:
303 _LOGGER.debug("Cancelling resubscribe_task")
304 self._resubscriber_task.cancel()
305 try:
306 await self._resubscriber_task
307 except asyncio.CancelledError:
308 pass
309 self._resubscriber_task = None
310
311 async def async_subscribe_services(self, auto_resubscribe: bool = False) -> timedelta | None:
312 """(Re-)Subscribe to services.
313
314 :param auto_resubscribe: Automatically resubscribe to subscriptions
315 before they expire. If this is enabled, failure to resubscribe will
316 be indicated by on_event being called with the failed service and an
317 empty state_variables list.
318 :return: time until this next needs to be called, or None if manual
319 resubscription is not needed.
320 :raise UpnpResponseError: Device rejected subscription request.
321 State variables will need to be polled.
322 :raise UpnpError or subclass: Failed to subscribe to all interesting
323 services.
324 """
325 if not self._event_handler:
326 _LOGGER.debug("No event_handler, event handling disabled")
327 return None
328
329 # Using time.monotonic to avoid problems with system clock changes
330 now = time.monotonic()
331
332 try:
333 if self._subscriptions:
334 # Resubscribe existing subscriptions
335 await self._async_resubscribe_services(now)
336 else:
337 # Subscribe to services we are interested in
338 for service in self.profile_device.all_services:
339 if not self._interesting_service(service):
340 continue
341
342 _LOGGER.debug("Subscribing to service: %s", service)
343 service.on_event = self._on_event
344 new_sid, timeout = await self._event_handler.async_subscribe(service, timeout=SUBSCRIBE_TIMEOUT)
345 self._subscriptions[new_sid] = now + timeout.total_seconds()
346 except UpnpError as err:
347 if isinstance(err, UpnpResponseError) and not self._subscriptions:
348 _LOGGER.debug("Device rejected subscription request: %r", err)
349 else:
350 _LOGGER.warning("Failed subscribing to service: %r", err)
351 # Unsubscribe anything that was subscribed, no half-done subscriptions
352 try:
353 await self.async_unsubscribe_services()
354 except UpnpError:
355 pass
356 raise
357
358 if not self._subscriptions:
359 return None
360
361 if auto_resubscribe:
362 await self._update_resubscriber_task()
363 return None
364
365 lowest_timeout_delta = min(self._subscriptions.values()) - now
366 resubcription_timeout = timedelta(seconds=lowest_timeout_delta) - RESUBSCRIBE_TOLERANCE
367 return max(resubcription_timeout, timedelta(seconds=0))
368
369 async def _async_unsubscribe_service(self, sid: str) -> None:
370 """Unsubscribe from one service, handling possible exceptions."""
371 assert self._event_handler
372
373 try:
374 await self._event_handler.async_unsubscribe(sid)
375 except UpnpError as err:
376 _LOGGER.debug("Failed unsubscribing from: %s, reason: %r", sid, err)
377 except KeyError:
378 _LOGGER.warning(
379 "%s was already unsubscribed. AiohttpNotifyServer was probably stopped before we could unsubscribe.",
380 sid,
381 )
382
383 async def async_unsubscribe_services(self) -> None:
384 """Unsubscribe from all of our subscribed services."""
385 # Delete list of subscriptions and cancel renewal before unsubscribing
386 # to avoid unsub-resub race.
387 sids = list(self._subscriptions)
388 self._subscriptions.clear()
389 await self._update_resubscriber_task()
390
391 await asyncio.gather(*(self._async_unsubscribe_service(sid) for sid in sids))
392
393 @property
394 def is_subscribed(self) -> bool:
395 """Get current service subscription state."""
396 return bool(self._subscriptions)
397
398 async def _async_poll_state_variables(
399 self, service_name: str, action_names: str | Sequence[str], **in_args: Any
400 ) -> None:
401 """Update state variables by polling actions that return their values.
402
403 Assumes that the actions's relatedStateVariable names the correct state
404 variable for updating.
405 """
406 service = self._service(service_name)
407 if not service:
408 _LOGGER.debug("Can't poll missing service %s", service_name)
409 return
410
411 if isinstance(action_names, str):
412 action_names = [action_names]
413
414 changed_state_variables: list[UpnpStateVariable] = []
415
416 for action_name in action_names:
417 try:
418 action = service.action(action_name)
419 except KeyError:
420 _LOGGER.debug(
421 "Can't poll missing action %s:%s for state variables",
422 service_name,
423 action_name,
424 )
425 continue
426 try:
427 result = await action.async_call(**in_args)
428 except UpnpResponseError as err:
429 _LOGGER.debug(
430 "Failed to call action %s:%s for state variables: %r",
431 service_name,
432 action_name,
433 err,
434 )
435 continue
436
437 for arg in action.arguments:
438 if arg.direction != "out":
439 continue
440 if arg.name not in result:
441 continue
442 if arg.related_state_variable.value == arg.value:
443 continue
444
445 try:
446 arg.related_state_variable.value = arg.value
447 except UpnpValueError:
448 continue
449 changed_state_variables.append(arg.related_state_variable)
450
451 if changed_state_variables:
452 self._on_event(service, changed_state_variables)
453
454 def _on_event(self, service: UpnpService, state_variables: Sequence[UpnpStateVariable]) -> None:
455 """
456 State variable(s) changed. Override to handle events.
457
458 :param service Service which sent the event.
459 :param state_variables State variables which have been changed.
460 """
461 if self.on_event:
462 self.on_event(service, state_variables) # pylint: disable=not-callable