Debian Codegraph @

async_upnp_client/client.py

raw symbols SCIP
1 """async_upnp_client.client module."""
2
3 from __future__ import annotations
4
5 import io
6 import logging
7 import urllib.parse
8 from abc import ABC
9 from datetime import datetime, timezone
10 from types import TracebackType
11 from typing import Any, Callable, Generic, Mapping, Sequence, Type, TypeVar
12 from xml.etree import ElementTree as ET
13 from xml.parsers import expat
14 from xml.sax.saxutils import escape
15
16 import defusedxml.ElementTree as DET
17 import voluptuous as vol
18
19 from async_upnp_client.const import (
20 NS,
21 ActionArgumentInfo,
22 ActionInfo,
23 DeviceIcon,
24 DeviceInfo,
25 HttpRequest,
26 HttpResponse,
27 ServiceInfo,
28 StateVariableInfo,
29 )
30 from async_upnp_client.exceptions import (
31 UpnpActionError,
32 UpnpActionResponseError,
33 UpnpError,
34 UpnpResponseError,
35 UpnpValueError,
36 UpnpXmlParseError,
37 )
38 from async_upnp_client.utils import CaseInsensitiveDict
39
40 # pylint: disable=too-many-lines
41
42
43 _LOGGER = logging.getLogger(__name__)
44
45
46 EventCallbackType = Callable[["UpnpService", Sequence["UpnpStateVariable"]], None]
47
48
49 def default_on_pre_receive_device_spec(request: HttpRequest) -> HttpRequest:
50 """Pre-receive device specification hook."""
51 # pylint: disable=unused-argument
52 return request
53
54
55 def default_on_post_receive_device_spec(response: HttpResponse) -> HttpResponse:
56 """Post-receive device specification hook."""
57 # pylint: disable=unused-argument
58 fixed_body = (response.body or "").rstrip(" \t\r\n\0")
59 return HttpResponse(response.status_code, response.headers, fixed_body)
60
61
62 def default_on_pre_receive_service_spec(request: HttpRequest) -> HttpRequest:
63 """Pre-receive service specification hook."""
64 # pylint: disable=unused-argument
65 return request
66
67
68 def default_on_post_receive_service_spec(response: HttpResponse) -> HttpResponse:
69 """Post-receive service specification hook."""
70 # pylint: disable=unused-argument
71 fixed_body = (response.body or "").rstrip(" \t\r\n\0")
72 return HttpResponse(response.status_code, response.headers, fixed_body)
73
74
75 def default_on_pre_call_action(action: "UpnpAction", args: Mapping[str, Any], request: HttpRequest) -> HttpRequest:
76 """Pre-action call hook."""
77 # pylint: disable=unused-argument
78 return request
79
80
81 def default_on_post_call_action(action: "UpnpAction", response: HttpResponse) -> HttpResponse:
82 """Post-action call hook."""
83 # pylint: disable=unused-argument
84 fixed_body = (response.body or "").rstrip(" \t\r\n\0")
85 return HttpResponse(response.status_code, response.headers, fixed_body)
86
87
88 class DisableXmlNamespaces:
89 """Context manager to disable XML namespace handling."""
90
91 def __enter__(self) -> None:
92 """Enter context manager."""
93 # pylint: disable=attribute-defined-outside-init
94 self._old_parser_create = expat.ParserCreate
95
96 def expat_parser_create(
97 encoding: str | None = None,
98 namespace_separator: str | None = None,
99 intern: dict[str, Any] | None = None,
100 ) -> expat.XMLParserType:
101 # pylint: disable=unused-argument
102 return self._old_parser_create(encoding, None, intern)
103
104 expat.ParserCreate = expat_parser_create
105
106 def __exit__(
107 self,
108 exc_type: Type[BaseException] | None,
109 exc_value: BaseException | None,
110 traceback: TracebackType | None,
111 ) -> None:
112 """Exit context manager."""
113 expat.ParserCreate = self._old_parser_create
114
115
116 class UpnpRequester(ABC):
117 """
118 Abstract base class used for performing async HTTP requests.
119
120 Implement method async_do_http_request() in your concrete class.
121 """
122
123 # pylint: disable=too-few-public-methods
124
125 async def async_http_request(
126 self,
127 http_request: HttpRequest,
128 ) -> HttpResponse:
129 """Do a HTTP request."""
130 raise NotImplementedError()
131
132
133 class UpnpDevice:
134 """UPnP Device representation."""
135
136 # pylint: disable=too-many-public-methods,too-many-instance-attributes
137
138 def __init__(
139 self,
140 requester: UpnpRequester,
141 device_info: DeviceInfo,
142 services: Sequence["UpnpService"],
143 embedded_devices: Sequence["UpnpDevice"],
144 on_pre_receive_device_spec: Callable[[HttpRequest], HttpRequest] = default_on_pre_receive_device_spec,
145 on_post_receive_device_spec: Callable[[HttpResponse], HttpResponse] = default_on_post_receive_device_spec,
146 ) -> None:
147 """Initialize."""
148 # pylint: disable=too-many-arguments,too-many-positional-arguments
149 self.requester = requester
150 self.device_info = device_info
151 self.services = {service.service_type: service for service in services}
152 self.embedded_devices = {embedded_device.device_type: embedded_device for embedded_device in embedded_devices}
153 self.on_pre_receive_device_spec = on_pre_receive_device_spec
154 self.on_post_receive_device_spec = on_post_receive_device_spec
155
156 self._parent_device: "UpnpDevice" | None = None
157
158 # bind services to ourselves
159 for service in services:
160 service.device = self
161
162 # bind devices to ourselves
163 for embedded_device in embedded_devices:
164 embedded_device.parent_device = self
165
166 # SSDP headers.
167 self.ssdp_headers: CaseInsensitiveDict = CaseInsensitiveDict()
168
169 # Just initialized, mark available.
170 self.available = True
171
172 @property
173 def parent_device(self) -> "UpnpDevice" | None:
174 """Get parent UpnpDevice, if any."""
175 return self._parent_device
176
177 @parent_device.setter
178 def parent_device(self, parent_device: "UpnpDevice") -> None:
179 """Set parent UpnpDevice."""
180 if self._parent_device is not None:
181 raise UpnpError("UpnpDevice already bound to UpnpDevice")
182
183 self._parent_device = parent_device
184
185 @property
186 def root_device(self) -> "UpnpDevice":
187 """Get the root device, or self if self is the root device."""
188 if self._parent_device is None:
189 return self
190
191 return self._parent_device.root_device
192
193 def find_device(self, device_type: str) -> "UpnpDevice" | None:
194 """Find a (embedded) device with the given device_type."""
195 if self.device_type == device_type:
196 return self
197
198 for embedded_device in self.embedded_devices.values():
199 device = embedded_device.find_device(device_type)
200 if device:
201 return device
202
203 return None
204
205 def find_service(self, service_type: str) -> "UpnpService" | None:
206 """Find a service with the give service_type."""
207 if service_type in self.services:
208 return self.services[service_type]
209
210 for embedded_device in self.embedded_devices.values():
211 service = embedded_device.find_service(service_type)
212 if service:
213 return service
214
215 return None
216
217 @property
218 def all_devices(self) -> list["UpnpDevice"]:
219 """Get all devices, self and embedded."""
220 devices = [self]
221
222 for embedded_device in self.embedded_devices.values():
223 devices += embedded_device.all_devices
224
225 return devices
226
227 def get_devices_matching_udn(self, udn: str) -> list["UpnpDevice"]:
228 """Get all devices matching udn."""
229 devices: list["UpnpDevice"] = []
230
231 if self.udn.lower() == udn:
232 devices.append(self)
233
234 for embedded_device in self.embedded_devices.values():
235 devices += embedded_device.get_devices_matching_udn(udn)
236
237 return devices
238
239 @property
240 def all_services(self) -> list["UpnpService"]:
241 """Get all services, from self and embedded devices."""
242 services: list["UpnpService"] = []
243
244 for device in self.all_devices:
245 services += device.services.values()
246
247 return services
248
249 def reinit(self, new_device: "UpnpDevice") -> None:
250 """Reinitialize self from another device."""
251 if self.device_type != new_device.device_type:
252 raise UpnpError(f"Mismatch in device_type: {self.device_type} vs {new_device.device_type}")
253
254 self.device_info = new_device.device_info
255
256 # reinit embedded devices
257 for device_type, embedded_device in self.embedded_devices.items():
258 new_embedded_device = new_device.embedded_devices[device_type]
259 embedded_device.reinit(new_embedded_device)
260
261 @property
262 def name(self) -> str:
263 """Get the name of this device."""
264 return self.device_info.friendly_name
265
266 @property
267 def friendly_name(self) -> str:
268 """Get the friendly name of this device, alias for name."""
269 return self.device_info.friendly_name
270
271 @property
272 def manufacturer(self) -> str:
273 """Get the manufacturer of this device."""
274 return self.device_info.manufacturer
275
276 @property
277 def manufacturer_url(self) -> str | None:
278 """Get the manufacturer URL of this device."""
279 return self.device_info.manufacturer_url
280
281 @property
282 def model_description(self) -> str | None:
283 """Get the model description of this device."""
284 return self.device_info.model_description
285
286 @property
287 def model_name(self) -> str:
288 """Get the model name of this device."""
289 return self.device_info.model_name
290
291 @property
292 def model_number(self) -> str | None:
293 """Get the model number of this device."""
294 return self.device_info.model_number
295
296 @property
297 def model_url(self) -> str | None:
298 """Get the model URL of this device."""
299 return self.device_info.model_url
300
301 @property
302 def serial_number(self) -> str | None:
303 """Get the serial number of this device."""
304 return self.device_info.serial_number
305
306 @property
307 def udn(self) -> str:
308 """Get UDN of this device."""
309 return self.device_info.udn
310
311 @property
312 def upc(self) -> str | None:
313 """Get UPC of this device."""
314 return self.device_info.upc
315
316 @property
317 def presentation_url(self) -> str | None:
318 """Get presentationURL of this device."""
319 return self.device_info.presentation_url
320
321 @property
322 def device_url(self) -> str:
323 """Get the URL of this device."""
324 return self.device_info.url
325
326 @property
327 def device_type(self) -> str:
328 """Get the device type of this device."""
329 return self.device_info.device_type
330
331 @property
332 def icons(self) -> Sequence[DeviceIcon]:
333 """Get the icons for this device."""
334 return self.device_info.icons
335
336 @property
337 def xml(self) -> ET.Element:
338 """Get the XML description for this device."""
339 return self.device_info.xml
340
341 def has_service(self, service_type: str) -> bool:
342 """Check if service by service_type is available."""
343 return service_type in self.services
344
345 def service(self, service_type: str) -> "UpnpService":
346 """Get service by service_type."""
347 return self.services[service_type]
348
349 def service_id(self, service_id: str) -> "UpnpService" | None:
350 """Get service by service_id."""
351 for service in self.services.values():
352 if service.service_id == service_id:
353 return service
354 return None
355
356 async def async_ping(self) -> None:
357 """Ping the device."""
358 bare_request = HttpRequest("GET", self.device_url, {}, None)
359 request = self.on_pre_receive_device_spec(bare_request)
360 await self.requester.async_http_request(request)
361
362 def __str__(self) -> str:
363 """To string."""
364 return f"<UpnpDevice({self.udn})>"
365
366
367 class UpnpService:
368 """UPnP Service representation."""
369
370 # pylint: disable=too-many-instance-attributes
371
372 def __init__(
373 self,
374 requester: UpnpRequester,
375 service_info: ServiceInfo,
376 state_variables: Sequence["UpnpStateVariable"],
377 actions: Sequence["UpnpAction"],
378 on_pre_call_action: Callable[
379 ["UpnpAction", Mapping[str, Any], HttpRequest], HttpRequest
380 ] = default_on_pre_call_action,
381 on_post_call_action: Callable[["UpnpAction", HttpResponse], HttpResponse] = default_on_post_call_action,
382 ) -> None:
383 """Initialize."""
384 # pylint: disable=too-many-arguments,too-many-positional-arguments
385 self.requester = requester
386 self._service_info = service_info
387 self.state_variables = {sv.name: sv for sv in state_variables}
388 self.actions = {ac.name: ac for ac in actions}
389 self.on_pre_call_action = on_pre_call_action
390 self.on_post_call_action = on_post_call_action
391
392 self.on_event: EventCallbackType | None = None
393 self._device: UpnpDevice | None = None
394
395 # bind state variables to ourselves
396 for state_var in state_variables:
397 state_var.service = self
398
399 # bind actions to ourselves
400 for action in actions:
401 action.service = self
402
403 @property
404 def device(self) -> UpnpDevice:
405 """Get parent UpnpDevice."""
406 if not self._device:
407 raise UpnpError("UpnpService not bound to UpnpDevice")
408
409 return self._device
410
411 @device.setter
412 def device(self, device: UpnpDevice) -> None:
413 """Set parent UpnpDevice."""
414 self._device = device
415
416 @property
417 def service_type(self) -> str:
418 """Get service type for this UpnpService."""
419 return self._service_info.service_type
420
421 @property
422 def service_id(self) -> str:
423 """Get service ID for this UpnpService."""
424 return self._service_info.service_id
425
426 @property
427 def scpd_url(self) -> str:
428 """Get full SCPD-url for this UpnpService."""
429 url: str = urllib.parse.urljoin(self.device.device_url, self._service_info.scpd_url)
430 return url
431
432 @property
433 def control_url(self) -> str:
434 """Get full control-url for this UpnpService."""
435 url: str = urllib.parse.urljoin(self.device.device_url, self._service_info.control_url)
436 return url
437
438 @property
439 def event_sub_url(self) -> str:
440 """Get full event sub-url for this UpnpService."""
441 url: str = urllib.parse.urljoin(self.device.device_url, self._service_info.event_sub_url)
442 return url
443
444 @property
445 def xml(self) -> ET.Element:
446 """Get the XML description for this service."""
447 return self._service_info.xml
448
449 def has_state_variable(self, name: str) -> bool:
450 """Check if self has state variable called name."""
451 if name not in self.state_variables and "}" in name:
452 # possibly messed up namespaces, try again without namespace
453 name = name.split("}")[1]
454
455 return name in self.state_variables
456
457 def state_variable(self, name: str) -> "UpnpStateVariable":
458 """Get UPnpStateVariable by name."""
459 state_var = self.state_variables.get(name, None)
460
461 # possibly messed up namespaces, try again without namespace
462 if not state_var and "}" in name:
463 name = name.split("}")[1]
464 state_var = self.state_variables.get(name, None)
465
466 if state_var is None:
467 raise KeyError(name)
468
469 return state_var
470
471 def has_action(self, name: str) -> bool:
472 """Check if self has action called name."""
473 return name in self.actions
474
475 def action(self, name: str) -> "UpnpAction":
476 """Get UPnpAction by name."""
477 return self.actions[name]
478
479 async def async_call_action(self, action: "UpnpAction" | str, **kwargs: Any) -> Mapping[str, Any]:
480 """
481 Call a UpnpAction.
482
483 Parameters are in Python-values and coerced automatically to UPnP values.
484 """
485 if isinstance(action, str):
486 action = self.actions[action]
487
488 result = await action.async_call(**kwargs)
489 return result
490
491 def notify_changed_state_variables(self, changes: Mapping[str, str]) -> None:
492 """Do callback on UpnpStateVariable.value changes."""
493 changed_state_variables = []
494
495 for name, value in changes.items():
496 if not self.has_state_variable(name):
497 _LOGGER.debug("State variable %s does not exist, ignoring", name)
498 continue
499
500 state_var = self.state_variable(name)
501 try:
502 state_var.upnp_value = value
503 changed_state_variables.append(state_var)
504 except UpnpValueError:
505 _LOGGER.error("Got invalid value for %s: %s", state_var, value)
506
507 if self.on_event:
508 # pylint: disable=not-callable
509 self.on_event(self, changed_state_variables)
510
511 def __str__(self) -> str:
512 """To string."""
513 udn = "unbound"
514 if self._device:
515 udn = self._device.udn
516 return f"<UpnpService({self.service_id}, {udn})>"
517
518 def __repr__(self) -> str:
519 """To repr."""
520 udn = "unbound"
521 if self._device:
522 udn = self._device.udn
523 return f"<UpnpService({self.service_id}, {udn})>"
524
525
526 class UpnpAction:
527 """Representation of an Action."""
528
529 class Argument:
530 """Representation of an Argument of an Action."""
531
532 def __init__(self, argument_info: ActionArgumentInfo, state_variable: "UpnpStateVariable") -> None:
533 """Initialize."""
534 self._argument_info = argument_info
535 self._related_state_variable = state_variable
536 self._value = None
537 self.raw_upnp_value: str | None = None
538
539 def validate_value(self, value: Any) -> None:
540 """Validate value against related UpnpStateVariable."""
541 self.related_state_variable.validate_value(value)
542
543 @property
544 def name(self) -> str:
545 """Get the name."""
546 return self._argument_info.name
547
548 @property
549 def direction(self) -> str:
550 """Get the direction."""
551 return self._argument_info.direction
552
553 @property
554 def related_state_variable(self) -> "UpnpStateVariable":
555 """Get the related state variable."""
556 return self._related_state_variable
557
558 @property
559 def xml(self) -> ET.Element:
560 """Get the XML description for this device."""
561 return self._argument_info.xml
562
563 @property
564 def value(self) -> Any:
565 """Get Python value for this argument."""
566 return self._value
567
568 @value.setter
569 def value(self, value: Any) -> None:
570 """Set Python value for this argument."""
571 self.validate_value(value)
572 self._value = value
573
574 @property
575 def upnp_value(self) -> str:
576 """Get UPnP value for this argument."""
577 return self.coerce_upnp(self.value)
578
579 @upnp_value.setter
580 def upnp_value(self, upnp_value: str) -> None:
581 """Set UPnP value for this argument."""
582 self._value = self.coerce_python(upnp_value)
583
584 def coerce_python(self, upnp_value: str) -> Any:
585 """Coerce UPnP value to Python."""
586 return self.related_state_variable.coerce_python(upnp_value)
587
588 def coerce_upnp(self, value: Any) -> str:
589 """Coerce Python value to UPnP value."""
590 return self.related_state_variable.coerce_upnp(value)
591
592 def __repr__(self) -> str:
593 """To repr."""
594 return f"<UpnpAction.Argument({self.name}, {self.direction})>"
595
596 def __init__(
597 self,
598 action_info: ActionInfo,
599 arguments: list["UpnpAction.Argument"],
600 non_strict: bool = False,
601 ) -> None:
602 """Initialize."""
603 self._action_info = action_info
604 self._arguments = arguments
605 self._service: UpnpService | None = None
606 self._non_strict = non_strict
607
608 @property
609 def name(self) -> str:
610 """Get the name."""
611 return self._action_info.name
612
613 @property
614 def arguments(self) -> list["UpnpAction.Argument"]:
615 """Get the arguments."""
616 return self._arguments
617
618 @property
619 def xml(self) -> ET.Element:
620 """Get the XML for this action."""
621 return self._action_info.xml
622
623 @property
624 def service(self) -> UpnpService:
625 """Get parent UpnpService."""
626 if not self._service:
627 raise UpnpError("UpnpAction not bound to UpnpService")
628
629 return self._service
630
631 @service.setter
632 def service(self, service: UpnpService) -> None:
633 """Set parent UpnpService."""
634 self._service = service
635
636 def __str__(self) -> str:
637 """To string."""
638 return f"<UpnpAction({self.name})>"
639
640 def __repr__(self) -> str:
641 """To repr."""
642 return f"<UpnpAction({self.name})({self.in_arguments()}) -> {self.out_arguments()}>"
643
644 def validate_arguments(self, **kwargs: Any) -> None:
645 """
646 Validate arguments against in-arguments of self.
647
648 The python type is expected.
649 """
650 for arg in self.in_arguments():
651 if arg.name not in kwargs:
652 raise UpnpError(f"Missing argument: {arg.name}")
653
654 value = kwargs[arg.name]
655 arg.validate_value(value)
656
657 def in_arguments(self) -> list["UpnpAction.Argument"]:
658 """Get all in-arguments."""
659 return [arg for arg in self.arguments if arg.direction == "in"]
660
661 def out_arguments(self) -> list["UpnpAction.Argument"]:
662 """Get all out-arguments."""
663 return [arg for arg in self.arguments if arg.direction == "out"]
664
665 def argument(self, name: str, direction: str | None = None) -> "UpnpAction.Argument" | None:
666 """Get an UpnpAction.Argument by name (and possibliy direction)."""
667 for arg in self.arguments:
668 if arg.name != name:
669 continue
670 if direction is not None and arg.direction != direction:
671 continue
672
673 return arg
674 return None
675
676 async def async_call(self, **kwargs: Any) -> Mapping[str, Any]:
677 """Call an action with arguments."""
678 # do request
679 _LOGGER.debug("Calling action: %s, args: %s", self.name, kwargs)
680 bare_request = self.create_request(**kwargs)
681 request = self.service.on_pre_call_action(self, kwargs, bare_request)
682 bare_response = await self.service.requester.async_http_request(request)
683 response = self.service.on_post_call_action(self, bare_response)
684 if not isinstance(response.body, str):
685 raise UpnpError(f"Did not receive a body when calling action: {self.name}, args: {kwargs}")
686
687 if response.status_code != 200:
688 try:
689 xml = DET.fromstring(response.body)
690 except ET.ParseError:
691 pass
692 else:
693 self._parse_fault(xml, response.status_code, response.headers)
694
695 # Couldn't parse body for fault details, raise generic response error
696 _LOGGER.debug(
697 "Error calling action, no information, action: %s, args: %s",
698 self.name,
699 kwargs,
700 )
701 raise UpnpResponseError(
702 status=response.status_code,
703 headers=response.headers,
704 message=f"Error during async_call(), "
705 f"action: {self.name}, "
706 f"args: {kwargs}, "
707 f"status: {response.status_code}, "
708 f"body: {response.body}",
709 )
710
711 # parse body
712 response_args = self.parse_response(self.service.service_type, response)
713 _LOGGER.debug(
714 "Called action: %s, args: %s, response_args: %s",
715 self.name,
716 kwargs,
717 response_args,
718 )
719 return response_args
720
721 def create_request(self, **kwargs: Any) -> HttpRequest:
722 """Create HTTP request for this to-be-called UpnpAction."""
723 # build URL
724 control_url = self.service.control_url
725
726 # construct SOAP body
727 service_type = self.service.service_type
728 soap_args = self._format_request_args(**kwargs)
729 body = (
730 f'<?xml version="1.0"?>'
731 f'<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"'
732 f' xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'
733 f"<s:Body>"
734 f'<u:{self.name} xmlns:u="{service_type}">'
735 f"{soap_args}"
736 f"</u:{self.name}>"
737 f"</s:Body>"
738 f"</s:Envelope>"
739 )
740
741 # construct SOAP header
742 soap_action = f"{service_type}#{self.name}"
743 headers = {
744 "SOAPAction": f'"{soap_action}"',
745 "Host": urllib.parse.urlparse(control_url).netloc,
746 "Content-Type": 'text/xml; charset="utf-8"',
747 }
748
749 return HttpRequest("POST", control_url, headers, body)
750
751 def _format_request_args(self, **kwargs: Any) -> str:
752 self.validate_arguments(**kwargs)
753 arg_strs = [
754 f"<{arg.name}>{escape(arg.coerce_upnp(kwargs[arg.name]))}</{arg.name}>" for arg in self.in_arguments()
755 ]
756 return "\n".join(arg_strs)
757
758 def parse_response(self, service_type: str, http_response: HttpResponse) -> Mapping[str, Any]:
759 """Parse response from called Action."""
760 # pylint: disable=unused-argument
761 stripped_response_body = http_response.body
762 try:
763 xml = DET.fromstring(stripped_response_body)
764 except ET.ParseError as err:
765 if self._non_strict:
766 # Try again ignoring namespaces.
767 try:
768 with DisableXmlNamespaces():
769 parser = DET.XMLParser()
770
771 source = io.StringIO(stripped_response_body)
772 it = DET.iterparse(source, parser=parser)
773 for _, el in it:
774 _, _, el.tag = el.tag.rpartition(":") # Strip namespace.
775 it_root = it.root # type: ET.Element
776 xml = it_root
777 except ET.ParseError as err2:
778 _LOGGER.debug("Unable to parse XML: %s\nXML:\n%s", err2, http_response.body)
779 raise UpnpXmlParseError(err2) from err2
780 else:
781 _LOGGER.debug("Unable to parse XML: %s\nXML:\n%s", err, http_response.body)
782 raise UpnpXmlParseError(err) from err
783
784 # Check if a SOAP fault occurred. It should have been caught earlier, by
785 # the device sending an HTTP 500 status, but not all devices do.
786 self._parse_fault(xml)
787
788 try:
789 return self._parse_response_args(service_type, xml)
790 except AttributeError:
791 _LOGGER.debug("Could not parse response: %s", http_response.body)
792 raise
793
794 def _parse_response_args(self, service_type: str, xml: ET.Element) -> Mapping[str, Any]:
795 """Parse response arguments."""
796 args = {}
797 query = f".//{{{service_type}}}{self.name}Response"
798 response = xml.find(query, NS)
799
800 # If no response was found, do a search ignoring namespaces when in non-strict mode.
801 if self._non_strict:
802 if response is None:
803 query = f".//{{*}}{self.name}Response"
804 response = xml.find(query, NS)
805
806 # Perhaps namespaces were removed/ignored, try searching again.
807 if response is None:
808 query = ".//*Response"
809 response = xml.find(query)
810
811 if response is None:
812 xml_str = ET.tostring(xml, encoding="unicode")
813 raise UpnpError(f"Invalid response: {xml_str}")
814
815 for arg_xml in response.findall("./"):
816 name = arg_xml.tag
817 arg = self.argument(name, "out")
818 if not arg:
819 if self._non_strict:
820 continue
821
822 xml_str = ET.tostring(xml, encoding="unicode")
823 raise UpnpError(f"Invalid response, unknown argument: {name}, {xml_str}")
824
825 arg.raw_upnp_value = arg_xml.text
826 arg.upnp_value = arg_xml.text or ""
827 args[name] = arg.value
828
829 return args
830
831 def _parse_fault(
832 self,
833 xml: ET.Element,
834 status_code: int | None = None,
835 response_headers: Mapping | None = None,
836 ) -> None:
837 """Parse SOAP fault and raise appropriate exception."""
838 # pylint: disable=too-many-branches
839 fault = xml.find(".//soap_envelope:Body/soap_envelope:Fault", NS)
840 if self._non_strict:
841 if fault is None:
842 fault = xml.find(".//{{*}}Body/{{*}}Fault", NS)
843
844 if fault is None:
845 fault = xml.find(".//{{*}}Body/{{*}}Fault")
846
847 if fault is None:
848 return
849
850 error_code_str = fault.findtext(".//control:errorCode", None, NS)
851 if self._non_strict:
852 if not error_code_str:
853 error_code_str = fault.findtext(".//{{*}}:errorCode", None, NS)
854
855 if not error_code_str:
856 error_code_str = fault.findtext(".//errorCode")
857
858 if error_code_str:
859 error_code: int | None = int(error_code_str)
860 else:
861 error_code = None
862
863 error_desc = fault.findtext(".//control:errorDescription", None, NS)
864 if self._non_strict:
865 if not error_desc:
866 error_desc = fault.findtext(".//{{*}}:errorDescription", None, NS)
867
868 if not error_desc:
869 error_desc = fault.findtext(".//errorDescription")
870 _LOGGER.debug(
871 "Error calling action: %s, error code: %s, error desc: %s",
872 self.name,
873 error_code,
874 error_desc,
875 )
876
877 if status_code is not None:
878 raise UpnpActionResponseError(
879 error_code=error_code,
880 error_desc=error_desc,
881 status=status_code,
882 headers=response_headers,
883 message=f"Error during async_call(), "
884 f"action: {self.name}, "
885 f"status: {status_code}, "
886 f"upnp error: {error_code} ({error_desc})",
887 )
888
889 raise UpnpActionError(
890 error_code=error_code,
891 error_desc=error_desc,
892 message=f"Error during async_call(), action: {self.name}, upnp error: {error_code} ({error_desc})",
893 )
894
895
896 T = TypeVar("T") # pylint: disable=invalid-name
897
898 _UNDEFINED = object()
899
900
901 class UpnpStateVariable(Generic[T]):
902 """Representation of a State Variable."""
903
904 # pylint: disable=too-many-instance-attributes
905
906 UPNP_VALUE_ERROR = object()
907
908 def __init__(self, state_variable_info: StateVariableInfo, schema: vol.Schema) -> None:
909 """Initialize."""
910 self._state_variable_info = state_variable_info
911 self._schema = schema
912
913 self._service: UpnpService | None = None
914 self._value: Any | None = None # None, T or UPNP_VALUE_ERROR
915 self._updated_at: datetime | None = None
916
917 # When py3.12 is the minimum version, we can switch
918 # these to be @cached_property
919 self._min_value: T | None = _UNDEFINED # type: ignore[assignment]
920 self._max_value: T | None = _UNDEFINED # type: ignore[assignment]
921 self._step_value: T | None = _UNDEFINED # type: ignore[assignment]
922 self._allowed_values: set[T] = _UNDEFINED # type: ignore[assignment]
923 self._normalized_allowed_values: set[str] = _UNDEFINED # type: ignore[assignment]
924
925 @property
926 def service(self) -> UpnpService:
927 """Get parent UpnpService."""
928 if not self._service:
929 raise UpnpError("UpnpStateVariable not bound to UpnpService")
930
931 return self._service
932
933 @service.setter
934 def service(self, service: UpnpService) -> None:
935 """Set parent UpnpService."""
936 self._service = service
937
938 @property
939 def xml(self) -> ET.Element:
940 """Get the XML for this State Variable."""
941 return self._state_variable_info.xml
942
943 @property
944 def data_type_mapping(self) -> Mapping[str, Callable]:
945 """Get the data type (coercer) for this State Variable."""
946 return self._state_variable_info.type_info.data_type_mapping
947
948 @property
949 def data_type_python(self) -> Callable[[str], Any]:
950 """Get the Python data type for this State Variable."""
951 return self.data_type_mapping["type"]
952
953 @property
954 def min_value(self) -> T | None:
955 """Min value for this UpnpStateVariable, if defined."""
956 if self._min_value is _UNDEFINED:
957 min_ = self._state_variable_info.type_info.allowed_value_range.get("min")
958 if min_ is not None:
959 self._min_value = self.coerce_python(min_)
960 else:
961 self._min_value = None
962 return self._min_value
963
964 @property
965 def max_value(self) -> T | None:
966 """Max value for this UpnpStateVariable, if defined."""
967 if self._max_value is _UNDEFINED:
968 max_ = self._state_variable_info.type_info.allowed_value_range.get("max")
969 if max_ is not None:
970 self._max_value = self.coerce_python(max_)
971 else:
972 self._max_value = None
973 return self._max_value
974
975 @property
976 def step_value(self) -> T | None:
977 """Step value for this UpnpStateVariable, if defined."""
978 if self._step_value is _UNDEFINED:
979 step = self._state_variable_info.type_info.allowed_value_range.get("step")
980 if step is not None:
981 self._step_value = self.coerce_python(step)
982 else:
983 self._step_value = None
984 return self._step_value
985
986 @property
987 def allowed_values(self) -> set[T]:
988 """Set with allowed values for this UpnpStateVariable, if defined."""
989 if self._allowed_values is _UNDEFINED:
990 allowed_values = self._state_variable_info.type_info.allowed_values or []
991 self._allowed_values = {self.coerce_python(allowed_value) for allowed_value in allowed_values}
992 return self._allowed_values
993
994 @property
995 def normalized_allowed_values(self) -> set[str]:
996 """Set with normalized allowed values for this UpnpStateVariable, if defined."""
997 if self._normalized_allowed_values is _UNDEFINED:
998 self._normalized_allowed_values = {
999 str(allowed_value).lower().strip() for allowed_value in self.allowed_values
1000 }
1001 return self._normalized_allowed_values
1002
1003 @property
1004 def send_events(self) -> bool:
1005 """Check if this UpnpStatevariable send events."""
1006 return self._state_variable_info.send_events
1007
1008 @property
1009 def name(self) -> str:
1010 """Name of the UpnpStatevariable."""
1011 return self._state_variable_info.name
1012
1013 @property
1014 def data_type(self) -> str:
1015 """UPNP data type of UpnpStateVariable."""
1016 return self._state_variable_info.type_info.data_type
1017
1018 @property
1019 def default_value(self) -> T | None:
1020 """Get default value for UpnpStateVariable, if defined."""
1021 type_info = self._state_variable_info.type_info
1022 default_value = type_info.default_value
1023 if default_value is not None:
1024 value: T = self.coerce_python(default_value)
1025 return value
1026
1027 return None
1028
1029 def validate_value(self, value: T) -> None:
1030 """Validate value."""
1031 try:
1032 self._schema(value)
1033 except vol.error.MultipleInvalid as ex:
1034 raise UpnpValueError(self.name, value) from ex
1035
1036 @property
1037 def value(self) -> T | None:
1038 """
1039 Get the value, python typed.
1040
1041 Invalid values are returned as None.
1042 """
1043 if self._value is UpnpStateVariable.UPNP_VALUE_ERROR:
1044 return None
1045
1046 return self._value
1047
1048 @value.setter
1049 def value(self, value: Any) -> None:
1050 """Set value, python typed."""
1051 self.validate_value(value)
1052 self._value = value
1053 self._updated_at = datetime.now(timezone.utc)
1054
1055 @property
1056 def value_unchecked(self) -> T | None:
1057 """
1058 Get the value, python typed.
1059
1060 If an event was received with an invalid value for this StateVariable
1061 (e.g., 'abc' for a 'ui4' StateVariable), then this will return
1062 UpnpStateVariable.UPNP_VALUE_ERROR instead of None.
1063 """
1064 return self._value
1065
1066 @property
1067 def upnp_value(self) -> str:
1068 """Get the value, UPnP typed."""
1069 return self.coerce_upnp(self.value)
1070
1071 @upnp_value.setter
1072 def upnp_value(self, upnp_value: str) -> None:
1073 """Set the value, UPnP typed."""
1074 try:
1075 self.value = self.coerce_python(upnp_value)
1076 except ValueError as err:
1077 _LOGGER.debug('Error setting upnp_value "%s", error: %s', upnp_value, err)
1078 self._value = UpnpStateVariable.UPNP_VALUE_ERROR
1079
1080 def coerce_python(self, upnp_value: str) -> Any:
1081 """Coerce value from UPNP to python."""
1082 coercer = self.data_type_mapping["in"]
1083 return coercer(upnp_value)
1084
1085 def coerce_upnp(self, value: Any) -> str:
1086 """Coerce value from python to UPNP."""
1087 coercer = self.data_type_mapping["out"]
1088 coerced_value: str = coercer(value)
1089 return coerced_value
1090
1091 @property
1092 def updated_at(self) -> datetime | None:
1093 """
1094 Get timestamp at which this UpnpStateVariable was updated.
1095
1096 Return time in UTC.
1097 """
1098 return self._updated_at
1099
1100 def __str__(self) -> str:
1101 """To string."""
1102 return f"<UpnpStateVariable({self.name}, {self.data_type})>"
1103
1104 def __repr__(self) -> str:
1105 """To repr."""
1106 return f"<UpnpStateVariable({self.name}: {self.data_type} = {self.value!r})>"