devialet 1.4.5__tar.gz → 1.5.1__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: devialet
3
- Version: 1.4.5
3
+ Version: 1.5.1
4
4
  Summary: Devialet API
5
5
  Home-page: https://github.com/fwestenberg/devialet
6
6
  Download-URL: https://github.com/fwestenberg/devialet/releases/latest
@@ -20,5 +20,6 @@ Classifier: Programming Language :: Python :: 3.9
20
20
  Description-Content-Type: text/markdown
21
21
  License-File: LICENSE
22
22
  Requires-Dist: aiohttp
23
+ Requires-Dist: async_upnp_client
23
24
 
24
25
  Devialet API
@@ -0,0 +1,25 @@
1
+ # Devialet
2
+ Devialet Python package
3
+
4
+ Please find the documentation Home Assistant documentation [here:](https://www.home-assistant.io/integrations/devialet)
5
+
6
+ **Example:**
7
+
8
+ ```python
9
+ import asyncio
10
+ import aiohttp
11
+
12
+ from devialet import DevialetApi
13
+
14
+
15
+ async def main():
16
+ session = async with aiohttp.ClientSession() as session:
17
+ client = DevialetApi('192.168.1.10', session)
18
+ await client.async_update()
19
+ await client.async_set_volume_level(20)
20
+ await client.async_media_next_track()
21
+ await client.async_turn_off()
22
+
23
+ asyncio.run(main())
24
+
25
+ ```
@@ -27,6 +27,8 @@ SPEAKER_POSITIONS = {
27
27
  "FrontRight": "right",
28
28
  }
29
29
 
30
+ AV_TRANSPORT = "urn:schemas-upnp-org:service:AVTransport:2"
31
+ MEDIA_RENDERER = "urn:schemas-upnp-org:device:MediaRenderer:2"
30
32
 
31
33
  class UrlSuffix(Enum):
32
34
  GET_GENERAL_INFO = "/ipcontrol/v1/devices/current"
@@ -4,16 +4,26 @@ from __future__ import annotations
4
4
  import asyncio
5
5
  import datetime
6
6
  import json
7
+ import re
8
+ from typing import Mapping, Union
7
9
 
8
10
  import aiohttp
11
+ from async_upnp_client.aiohttp import AiohttpRequester
12
+ from async_upnp_client.client_factory import UpnpFactory
13
+ from async_upnp_client.exceptions import (UpnpActionResponseError,
14
+ UpnpXmlParseError)
15
+ from async_upnp_client.profiles.dlna import DmrDevice
16
+ from async_upnp_client.search import async_search
17
+ from async_upnp_client.utils import CaseInsensitiveDict
9
18
 
10
- from .const import LOGGER, NORMAL_INPUTS, SPEAKER_POSITIONS, UrlSuffix
19
+ from .const import AV_TRANSPORT, LOGGER, NORMAL_INPUTS, MEDIA_RENDERER, SPEAKER_POSITIONS, UrlSuffix
11
20
 
21
+ UPNP_SEARCH_INTERVAL = 120
12
22
 
13
23
  class DevialetApi:
14
24
  """Devialet API class."""
15
25
 
16
- def __init__(self, host, session):
26
+ def __init__(self, host:str, session:aiohttp.ClientSession):
17
27
  """Initialize the Devialet API."""
18
28
 
19
29
  self._host = host
@@ -32,27 +42,30 @@ class DevialetApi:
32
42
  self._media_duration = 0
33
43
  self._device_role = ""
34
44
  self._is_available = False
45
+ self._upnp_device = None
46
+ self._dmr_device = None
47
+ self._last_upnp_search: datetime.datetime = None
35
48
 
36
49
  async def async_update(self) -> bool | None:
37
50
  """Get the latest details from the device."""
38
51
  if self._general_info is None:
39
- self._general_info = await self.get_request(UrlSuffix.GET_GENERAL_INFO)
52
+ self._general_info = await self._async_get_request(UrlSuffix.GET_GENERAL_INFO)
40
53
 
41
54
  # Without general info the device has not been online yet
42
55
  if self._general_info is None:
43
56
  return False
44
57
 
45
- self._source_state = await self.get_request(UrlSuffix.GET_CURRENT_SOURCE)
46
- # the source state call if enough to find out if the device is available (On or Off)
58
+ self._source_state = await self._async_get_request(UrlSuffix.GET_CURRENT_SOURCE)
59
+ # The source state call is enough to find out if the device is available (On or Off)
47
60
  if not self._is_available:
48
61
  return True
49
62
 
50
63
  if self._sources is None:
51
- self._sources = await self.get_request(UrlSuffix.GET_SOURCES)
64
+ self._sources = await self._async_get_request(UrlSuffix.GET_SOURCES)
52
65
 
53
- self._volume = await self.get_request(UrlSuffix.GET_VOLUME)
54
- self._night_mode = await self.get_request(UrlSuffix.GET_NIGHT_MODE)
55
- self._equalizer = await self.get_request(UrlSuffix.GET_EQUALIZER)
66
+ self._volume = await self._async_get_request(UrlSuffix.GET_VOLUME)
67
+ self._night_mode = await self._async_get_request(UrlSuffix.GET_NIGHT_MODE)
68
+ self._equalizer = await self._async_get_request(UrlSuffix.GET_EQUALIZER)
56
69
 
57
70
  try:
58
71
  self._media_duration = self._source_state["metadata"]["duration"]
@@ -65,10 +78,10 @@ class DevialetApi:
65
78
  self._media_duration = None
66
79
 
67
80
  if self._media_duration is not None:
68
- position = await self.get_request(UrlSuffix.GET_CURRENT_POSITION)
81
+ position = await self._async_get_request(UrlSuffix.GET_CURRENT_POSITION)
69
82
  try:
70
83
  self._current_position = position["position"]
71
- self._position_updated_at = datetime.datetime.utcnow()
84
+ self._position_updated_at = datetime.datetime.now(tz=datetime.timezone.utc).replace(tzinfo=None)
72
85
  except (KeyError, TypeError):
73
86
  self._current_position = None
74
87
  self._position_updated_at = None
@@ -80,6 +93,11 @@ class DevialetApi:
80
93
  """Return available."""
81
94
  return self._is_available
82
95
 
96
+ @property
97
+ def upnp_available(self) -> bool | None:
98
+ """Return available."""
99
+ return self._upnp_device is not None
100
+
83
101
  @property
84
102
  def device_id(self) -> str | None:
85
103
  """Return the device id."""
@@ -88,6 +106,14 @@ class DevialetApi:
88
106
  except (KeyError, TypeError):
89
107
  return None
90
108
 
109
+ @property
110
+ def is_system_leader(self) -> bool | None:
111
+ """Return the boolean for system leader identification."""
112
+ try:
113
+ return self._general_info["isSystemLeader"]
114
+ except (KeyError, TypeError):
115
+ return None
116
+
91
117
  @property
92
118
  def serial(self) -> str | None:
93
119
  """Return the serial."""
@@ -157,6 +183,11 @@ class DevialetApi:
157
183
  except (KeyError, TypeError):
158
184
  return None
159
185
 
186
+ @property
187
+ def dmr_device(self) -> DmrDevice | None:
188
+ """Return DMR device class."""
189
+ return self._dmr_device
190
+
160
191
  @property
161
192
  def source_list(self) -> list | None:
162
193
  """Return the list of available input sources."""
@@ -187,10 +218,10 @@ class DevialetApi:
187
218
  return sorted(self._source_list)
188
219
 
189
220
  @property
190
- def available_options(self) -> any | None:
191
- """Return the list of available options for this source."""
221
+ def available_operations(self) -> any | None:
222
+ """Return the list of available operations for this source."""
192
223
  try:
193
- return self._source_state["availableOptions"]
224
+ return self._source_state["availableOperations"]
194
225
  except (KeyError, TypeError):
195
226
  return None
196
227
 
@@ -241,14 +272,6 @@ class DevialetApi:
241
272
  """When was the position of the current playing media valid."""
242
273
  return self._position_updated_at
243
274
 
244
- @property
245
- def supported_features(self) -> any | None:
246
- """Flag media player features that are supported."""
247
- try:
248
- return self._source_state["availableOptions"]
249
- except (KeyError, TypeError):
250
- return None
251
-
252
275
  @property
253
276
  def source(self) -> str | None:
254
277
  """Return the current input source."""
@@ -305,56 +328,58 @@ class DevialetApi:
305
328
  "equalizer": self._equalizer,
306
329
  "source_list": self.source_list,
307
330
  "source": self.source,
331
+ "upnp_device_type": getattr(self._upnp_device.device_info, 'device_type') if self._upnp_device else "Not available",
332
+ "upnp_device_url": getattr(self._upnp_device.device_info, 'url') if self._upnp_device else "Not available",
308
333
  }
309
334
 
310
335
  async def async_volume_up(self) -> None:
311
336
  """Volume up media player."""
312
- await self.post_request(UrlSuffix.VOLUME_UP, {})
337
+ await self._async_post_request(UrlSuffix.VOLUME_UP)
313
338
 
314
339
  async def async_volume_down(self) -> None:
315
340
  """Volume down media player."""
316
- await self.post_request(UrlSuffix.VOLUME_DOWN, {})
341
+ await self._async_post_request(UrlSuffix.VOLUME_DOWN)
317
342
 
318
343
  async def async_set_volume_level(self, volume: float) -> None:
319
344
  """Set volume level, range 0..1."""
320
- await self.post_request(
345
+ await self._async_post_request(
321
346
  UrlSuffix.VOLUME_SET,
322
- {"volume": volume * 100},
347
+ json_body={"volume": volume * 100},
323
348
  )
324
349
 
325
350
  async def async_mute_volume(self, mute: bool) -> None:
326
351
  """Mute (true) or unmute (false) media player."""
327
352
  if mute:
328
- await self.post_request(UrlSuffix.MUTE, {})
353
+ await self._async_post_request(UrlSuffix.MUTE)
329
354
  else:
330
- await self.post_request(UrlSuffix.UNMUTE, {})
355
+ await self._async_post_request(UrlSuffix.UNMUTE)
331
356
 
332
357
  async def async_media_play(self) -> None:
333
358
  """Play media player."""
334
- await self.post_request(UrlSuffix.PLAY, {})
359
+ await self._async_post_request(UrlSuffix.PLAY)
335
360
 
336
361
  async def async_media_pause(self) -> None:
337
362
  """Pause media player."""
338
- await self.post_request(UrlSuffix.PAUSE, {})
363
+ await self._async_post_request(UrlSuffix.PAUSE)
339
364
 
340
365
  async def async_media_stop(self) -> None:
341
366
  """Pause media player."""
342
- await self.post_request(UrlSuffix.PAUSE, {})
367
+ await self._async_post_request(UrlSuffix.PAUSE)
343
368
 
344
369
  async def async_media_next_track(self) -> None:
345
370
  """Send the next track command."""
346
- await self.post_request(UrlSuffix.NEXT_TRACK, {})
371
+ await self._async_post_request(UrlSuffix.NEXT_TRACK)
347
372
 
348
373
  async def async_media_previous_track(self) -> None:
349
374
  """Send the previous track command."""
350
- await self.post_request(UrlSuffix.PREVIOUS_TRACK, {})
375
+ await self._async_post_request(UrlSuffix.PREVIOUS_TRACK)
351
376
 
352
377
  async def async_media_seek(self, position: float) -> None:
353
378
  """Send seek command."""
354
379
 
355
- await self.post_request(
380
+ await self._async_post_request(
356
381
  UrlSuffix.SEEK,
357
- {"position": int(position)},
382
+ json_body={"position": int(position)},
358
383
  )
359
384
 
360
385
  async def async_set_night_mode(self, night_mode: bool) -> None:
@@ -364,21 +389,21 @@ class DevialetApi:
364
389
  else:
365
390
  mode = "off"
366
391
 
367
- await self.post_request(
392
+ await self._async_post_request(
368
393
  UrlSuffix.NIGHT_MODE,
369
- {"nightMode": mode},
394
+ json_body={"nightMode": mode},
370
395
  )
371
396
 
372
397
  async def async_set_equalizer(self, preset: str) -> None:
373
398
  """Set the equalizer preset."""
374
- await self.post_request(
399
+ await self._async_post_request(
375
400
  UrlSuffix.EQUALIZER,
376
- {"preset": preset},
401
+ json_body={"preset": preset},
377
402
  )
378
403
 
379
404
  async def async_turn_off(self) -> None:
380
405
  """Turn off media player."""
381
- await self.post_request(UrlSuffix.TURN_OFF, {})
406
+ await self._async_post_request(UrlSuffix.TURN_OFF)
382
407
 
383
408
  async def async_select_source(self, source: str) -> None:
384
409
  """Select input source."""
@@ -423,11 +448,11 @@ class DevialetApi:
423
448
  LOGGER.error("Source %s is not available", source)
424
449
  return
425
450
 
426
- await self.post_request(
427
- str(UrlSuffix.SELECT_SOURCE).replace("%SOURCE_ID%", source_id), {}
451
+ await self._async_post_request(
452
+ str(UrlSuffix.SELECT_SOURCE).replace("%SOURCE_ID%", source_id)
428
453
  )
429
454
 
430
- async def get_request(self, suffix=str) -> any | None:
455
+ async def _async_get_request(self, suffix: str) -> any | None:
431
456
  """Generic GET method."""
432
457
  url = "http://" + self._host + str(suffix)
433
458
 
@@ -456,31 +481,30 @@ class DevialetApi:
456
481
  self._is_available = False
457
482
  return None
458
483
  except asyncio.TimeoutError:
484
+ LOGGER.debug("Devialet connection timeout exception. Please check the connection")
459
485
  self._is_available = False
460
- LOGGER.debug(
461
- "Devialet connection timeout exception. Please check the connection"
462
- )
463
486
  return None
464
487
  except (TypeError, json.JSONDecodeError):
465
- LOGGER.debug("Devialet: JSON error")
488
+ LOGGER.debug("Get request: JSON error")
466
489
  return None
467
490
  except Exception: # pylint: disable=bare-except
468
- LOGGER.debug("Devialet: unknown exception occurred")
491
+ LOGGER.debug("Get request: unknown exception occurred")
469
492
  return None
470
493
 
471
- async def post_request(self, suffix=str, body=str) -> any | None:
494
+ async def _async_post_request(self, suffix:str, json_body:str={}) -> bool | None:
472
495
  """Generic POST method."""
473
496
  url = "http://" + self._host + str(suffix)
474
497
 
475
498
  try:
476
499
  async with self._session.post(
477
- url=url, json=body, allow_redirects=False, timeout=2
500
+ url=url, json=json_body, allow_redirects=False, timeout=2
478
501
  ) as response:
479
- response = await response.read()
502
+ response_data = await response.text()
480
503
  LOGGER.debug(
481
- "Host %s: HTTP Response data: %s",
504
+ "Host %s: HTTP %s Response data: %s",
482
505
  self._host,
483
- response,
506
+ response.status,
507
+ response_data,
484
508
  )
485
509
 
486
510
  return True
@@ -490,12 +514,80 @@ class DevialetApi:
490
514
  return False
491
515
  except asyncio.TimeoutError:
492
516
  LOGGER.debug(
493
- "Devialet connection timeout exception. Please check the connection"
517
+ "Devialet connection timeout exception, please check the connection"
494
518
  )
495
519
  return False
496
520
  except (TypeError, json.JSONDecodeError):
497
- LOGGER.debug("Devialet: JSON error")
521
+ LOGGER.debug("Post request: unknown response type")
498
522
  return False
499
523
  except Exception: # pylint: disable=bare-except
500
- LOGGER.debug("Devialet: unknown exception occurred")
524
+ LOGGER.debug("Post request: unknown exception occurred")
501
525
  return False
526
+
527
+ async def _async_on_search_response(self, data: CaseInsensitiveDict) -> None:
528
+ """UPnP device detected."""
529
+ location = data['location']
530
+ location_regex = re.compile(f"(?<=Location:[ ])*http://{self._host}:(.*)/.*.xml", re.IGNORECASE)
531
+ location_result = location_regex.search(location)
532
+ if location_result:
533
+ requester = AiohttpRequester()
534
+ factory = UpnpFactory(requester)
535
+ self._upnp_device = await factory.async_create_device(location)
536
+ self._dmr_device = DmrDevice(self._upnp_device, None)
537
+
538
+ async def async_search_allowed(self) -> bool:
539
+ """Conditions to check if UPnP search is allowed."""
540
+ if (
541
+ self.is_available
542
+ and not self.upnp_available
543
+ and self.is_system_leader
544
+ and ( not self._last_upnp_search
545
+ or ( datetime.datetime.now() - self._last_upnp_search).total_seconds() >= UPNP_SEARCH_INTERVAL ) ):
546
+ return True
547
+ return False
548
+
549
+ async def async_discover_upnp_device(self) -> None:
550
+ """Discover the UPnP device."""
551
+ self._last_upnp_search = datetime.datetime.now()
552
+
553
+ await async_search(async_callback=self._async_on_search_response,
554
+ timeout=10,
555
+ search_target=MEDIA_RENDERER,
556
+ source=("0.0.0.0", 0))
557
+ LOGGER.debug("Discovering UPnP device for %s", self._host)
558
+
559
+ async def async_play_url_source(self, media_url: str, media_title: str, meta_data: Union[None, str, Mapping] = None) -> bool:
560
+ """Play media uri over UPnP."""
561
+ if not self.upnp_available:
562
+ LOGGER.error("No UPnP location discovered")
563
+ return
564
+
565
+ service = self._upnp_device.service(AV_TRANSPORT)
566
+ set_uri = service.action("SetAVTransportURI")
567
+
568
+ try:
569
+ result = await set_uri.async_call(InstanceID=0, CurrentURI=media_url, CurrentURIMetaData=meta_data)
570
+ LOGGER.debug("Action result: %s", str(result))
571
+ except UpnpActionResponseError as a:
572
+ LOGGER.error("Error playing %s: %s", media_title, a.error_desc)
573
+ except UpnpXmlParseError as x:
574
+ LOGGER.error("Error playing %s %s", media_title, x.text)
575
+
576
+ await self.async_upnp_play()
577
+
578
+ async def async_upnp_play(self) -> None:
579
+ """Send the play command over UPnP."""
580
+ if not self.upnp_available:
581
+ LOGGER.error("No UPnP location discovered")
582
+ return
583
+
584
+ service = self._upnp_device.service(AV_TRANSPORT)
585
+ set_uri = service.action("Play")
586
+
587
+ try:
588
+ await set_uri.async_call(InstanceID=0, Speed="1")
589
+ return
590
+ except UpnpActionResponseError:
591
+ return
592
+ except UpnpXmlParseError:
593
+ return
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: devialet
3
- Version: 1.4.5
3
+ Version: 1.5.1
4
4
  Summary: Devialet API
5
5
  Home-page: https://github.com/fwestenberg/devialet
6
6
  Download-URL: https://github.com/fwestenberg/devialet/releases/latest
@@ -20,5 +20,6 @@ Classifier: Programming Language :: Python :: 3.9
20
20
  Description-Content-Type: text/markdown
21
21
  License-File: LICENSE
22
22
  Requires-Dist: aiohttp
23
+ Requires-Dist: async_upnp_client
23
24
 
24
25
  Devialet API
@@ -0,0 +1,2 @@
1
+ aiohttp
2
+ async_upnp_client
@@ -3,7 +3,7 @@ from distutils.core import setup
3
3
  setup(
4
4
  name='devialet',
5
5
  packages=['devialet'],
6
- version='1.4.5',
6
+ version='1.5.1',
7
7
  license='MIT',
8
8
  description='Devialet API',
9
9
  long_description_content_type="text/markdown",
@@ -14,7 +14,7 @@ setup(
14
14
  download_url='https://github.com/fwestenberg/devialet/releases/latest',
15
15
  keywords=['Devialet', 'Home-Assistant'],
16
16
  install_requires=[
17
- 'aiohttp'
17
+ 'aiohttp', 'async_upnp_client'
18
18
  ],
19
19
  classifiers=[
20
20
  'Development Status :: 4 - Beta',
devialet-1.4.5/README.md DELETED
@@ -1,4 +0,0 @@
1
- # Devialet
2
- Devialet Home Assistant implementation
3
-
4
- The Home Assistant integration has moved [here:](https://github.com/fwestenberg/homeassistant-devialet)
@@ -1 +0,0 @@
1
- aiohttp
File without changes
File without changes
File without changes