devialet 1.4.5__tar.gz → 1.5.0__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.0
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(0.2)
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,25 @@ 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
 
12
21
 
13
22
  class DevialetApi:
14
23
  """Devialet API class."""
15
24
 
16
- def __init__(self, host, session):
25
+ def __init__(self, host:str, session:aiohttp.ClientSession):
17
26
  """Initialize the Devialet API."""
18
27
 
19
28
  self._host = host
@@ -32,27 +41,30 @@ class DevialetApi:
32
41
  self._media_duration = 0
33
42
  self._device_role = ""
34
43
  self._is_available = False
44
+ self._upnp_device = None
45
+ self._dmr_device = None
46
+ self._last_upnp_search: datetime.datetime = None
35
47
 
36
48
  async def async_update(self) -> bool | None:
37
49
  """Get the latest details from the device."""
38
50
  if self._general_info is None:
39
- self._general_info = await self.get_request(UrlSuffix.GET_GENERAL_INFO)
51
+ self._general_info = await self._async_get_request(UrlSuffix.GET_GENERAL_INFO)
40
52
 
41
53
  # Without general info the device has not been online yet
42
54
  if self._general_info is None:
43
55
  return False
44
56
 
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)
57
+ self._source_state = await self._async_get_request(UrlSuffix.GET_CURRENT_SOURCE)
58
+ # The source state call is enough to find out if the device is available (On or Off)
47
59
  if not self._is_available:
48
60
  return True
49
61
 
50
62
  if self._sources is None:
51
- self._sources = await self.get_request(UrlSuffix.GET_SOURCES)
63
+ self._sources = await self._async_get_request(UrlSuffix.GET_SOURCES)
52
64
 
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)
65
+ self._volume = await self._async_get_request(UrlSuffix.GET_VOLUME)
66
+ self._night_mode = await self._async_get_request(UrlSuffix.GET_NIGHT_MODE)
67
+ self._equalizer = await self._async_get_request(UrlSuffix.GET_EQUALIZER)
56
68
 
57
69
  try:
58
70
  self._media_duration = self._source_state["metadata"]["duration"]
@@ -65,10 +77,10 @@ class DevialetApi:
65
77
  self._media_duration = None
66
78
 
67
79
  if self._media_duration is not None:
68
- position = await self.get_request(UrlSuffix.GET_CURRENT_POSITION)
80
+ position = await self._async_get_request(UrlSuffix.GET_CURRENT_POSITION)
69
81
  try:
70
82
  self._current_position = position["position"]
71
- self._position_updated_at = datetime.datetime.utcnow()
83
+ self._position_updated_at = datetime.datetime.now(tz=datetime.timezone.utc).replace(tzinfo=None)
72
84
  except (KeyError, TypeError):
73
85
  self._current_position = None
74
86
  self._position_updated_at = None
@@ -80,6 +92,11 @@ class DevialetApi:
80
92
  """Return available."""
81
93
  return self._is_available
82
94
 
95
+ @property
96
+ def upnp_available(self) -> bool | None:
97
+ """Return available."""
98
+ return self._upnp_device is not None
99
+
83
100
  @property
84
101
  def device_id(self) -> str | None:
85
102
  """Return the device id."""
@@ -88,6 +105,14 @@ class DevialetApi:
88
105
  except (KeyError, TypeError):
89
106
  return None
90
107
 
108
+ @property
109
+ def is_system_leader(self) -> bool | None:
110
+ """Return the boolean for system leader identification."""
111
+ try:
112
+ return self._general_info["isSystemLeader"]
113
+ except (KeyError, TypeError):
114
+ return None
115
+
91
116
  @property
92
117
  def serial(self) -> str | None:
93
118
  """Return the serial."""
@@ -190,7 +215,7 @@ class DevialetApi:
190
215
  def available_options(self) -> any | None:
191
216
  """Return the list of available options for this source."""
192
217
  try:
193
- return self._source_state["availableOptions"]
218
+ return self._source_state["availableOperations"]
194
219
  except (KeyError, TypeError):
195
220
  return None
196
221
 
@@ -305,56 +330,57 @@ class DevialetApi:
305
330
  "equalizer": self._equalizer,
306
331
  "source_list": self.source_list,
307
332
  "source": self.source,
333
+ "upnp_device_info": self._upnp_device.device_info
308
334
  }
309
335
 
310
336
  async def async_volume_up(self) -> None:
311
337
  """Volume up media player."""
312
- await self.post_request(UrlSuffix.VOLUME_UP, {})
338
+ await self._async_post_request(UrlSuffix.VOLUME_UP)
313
339
 
314
340
  async def async_volume_down(self) -> None:
315
341
  """Volume down media player."""
316
- await self.post_request(UrlSuffix.VOLUME_DOWN, {})
342
+ await self._async_post_request(UrlSuffix.VOLUME_DOWN)
317
343
 
318
344
  async def async_set_volume_level(self, volume: float) -> None:
319
345
  """Set volume level, range 0..1."""
320
- await self.post_request(
346
+ await self._async_post_request(
321
347
  UrlSuffix.VOLUME_SET,
322
- {"volume": volume * 100},
348
+ json_body={"volume": volume * 100},
323
349
  )
324
350
 
325
351
  async def async_mute_volume(self, mute: bool) -> None:
326
352
  """Mute (true) or unmute (false) media player."""
327
353
  if mute:
328
- await self.post_request(UrlSuffix.MUTE, {})
354
+ await self._async_post_request(UrlSuffix.MUTE)
329
355
  else:
330
- await self.post_request(UrlSuffix.UNMUTE, {})
356
+ await self._async_post_request(UrlSuffix.UNMUTE)
331
357
 
332
358
  async def async_media_play(self) -> None:
333
359
  """Play media player."""
334
- await self.post_request(UrlSuffix.PLAY, {})
360
+ await self._async_post_request(UrlSuffix.PLAY)
335
361
 
336
362
  async def async_media_pause(self) -> None:
337
363
  """Pause media player."""
338
- await self.post_request(UrlSuffix.PAUSE, {})
364
+ await self._async_post_request(UrlSuffix.PAUSE)
339
365
 
340
366
  async def async_media_stop(self) -> None:
341
367
  """Pause media player."""
342
- await self.post_request(UrlSuffix.PAUSE, {})
368
+ await self._async_post_request(UrlSuffix.PAUSE)
343
369
 
344
370
  async def async_media_next_track(self) -> None:
345
371
  """Send the next track command."""
346
- await self.post_request(UrlSuffix.NEXT_TRACK, {})
372
+ await self._async_post_request(UrlSuffix.NEXT_TRACK)
347
373
 
348
374
  async def async_media_previous_track(self) -> None:
349
375
  """Send the previous track command."""
350
- await self.post_request(UrlSuffix.PREVIOUS_TRACK, {})
376
+ await self._async_post_request(UrlSuffix.PREVIOUS_TRACK)
351
377
 
352
378
  async def async_media_seek(self, position: float) -> None:
353
379
  """Send seek command."""
354
380
 
355
- await self.post_request(
381
+ await self._async_post_request(
356
382
  UrlSuffix.SEEK,
357
- {"position": int(position)},
383
+ json_body={"position": int(position)},
358
384
  )
359
385
 
360
386
  async def async_set_night_mode(self, night_mode: bool) -> None:
@@ -364,21 +390,21 @@ class DevialetApi:
364
390
  else:
365
391
  mode = "off"
366
392
 
367
- await self.post_request(
393
+ await self._async_post_request(
368
394
  UrlSuffix.NIGHT_MODE,
369
- {"nightMode": mode},
395
+ json_body={"nightMode": mode},
370
396
  )
371
397
 
372
398
  async def async_set_equalizer(self, preset: str) -> None:
373
399
  """Set the equalizer preset."""
374
- await self.post_request(
400
+ await self._async_post_request(
375
401
  UrlSuffix.EQUALIZER,
376
- {"preset": preset},
402
+ json_body={"preset": preset},
377
403
  )
378
404
 
379
405
  async def async_turn_off(self) -> None:
380
406
  """Turn off media player."""
381
- await self.post_request(UrlSuffix.TURN_OFF, {})
407
+ await self._async_post_request(UrlSuffix.TURN_OFF)
382
408
 
383
409
  async def async_select_source(self, source: str) -> None:
384
410
  """Select input source."""
@@ -423,11 +449,11 @@ class DevialetApi:
423
449
  LOGGER.error("Source %s is not available", source)
424
450
  return
425
451
 
426
- await self.post_request(
427
- str(UrlSuffix.SELECT_SOURCE).replace("%SOURCE_ID%", source_id), {}
452
+ await self._async_post_request(
453
+ str(UrlSuffix.SELECT_SOURCE).replace("%SOURCE_ID%", source_id)
428
454
  )
429
455
 
430
- async def get_request(self, suffix=str) -> any | None:
456
+ async def _async_get_request(self, suffix: str) -> any | None:
431
457
  """Generic GET method."""
432
458
  url = "http://" + self._host + str(suffix)
433
459
 
@@ -454,12 +480,12 @@ class DevialetApi:
454
480
  except aiohttp.ClientConnectorError as conn_err:
455
481
  LOGGER.debug("Host %s: Connection error %s", self._host, str(conn_err))
456
482
  self._is_available = False
483
+ self._upnp_device = None
457
484
  return None
458
485
  except asyncio.TimeoutError:
486
+ LOGGER.debug("Devialet connection timeout exception. Please check the connection")
459
487
  self._is_available = False
460
- LOGGER.debug(
461
- "Devialet connection timeout exception. Please check the connection"
462
- )
488
+ self._upnp_device = None
463
489
  return None
464
490
  except (TypeError, json.JSONDecodeError):
465
491
  LOGGER.debug("Devialet: JSON error")
@@ -468,19 +494,20 @@ class DevialetApi:
468
494
  LOGGER.debug("Devialet: unknown exception occurred")
469
495
  return None
470
496
 
471
- async def post_request(self, suffix=str, body=str) -> any | None:
497
+ async def _async_post_request(self, suffix:str, json_body:str={}) -> bool | None:
472
498
  """Generic POST method."""
473
499
  url = "http://" + self._host + str(suffix)
474
500
 
475
501
  try:
476
502
  async with self._session.post(
477
- url=url, json=body, allow_redirects=False, timeout=2
503
+ url=url, json=json_body, allow_redirects=False, timeout=2
478
504
  ) as response:
479
- response = await response.read()
505
+ response_data = await response.text()
480
506
  LOGGER.debug(
481
- "Host %s: HTTP Response data: %s",
507
+ "Host %s: HTTP %s Response data: %s",
482
508
  self._host,
483
- response,
509
+ response.status,
510
+ response_data,
484
511
  )
485
512
 
486
513
  return True
@@ -490,12 +517,71 @@ class DevialetApi:
490
517
  return False
491
518
  except asyncio.TimeoutError:
492
519
  LOGGER.debug(
493
- "Devialet connection timeout exception. Please check the connection"
520
+ "Devialet connection timeout exception, please check the connection"
494
521
  )
495
522
  return False
496
523
  except (TypeError, json.JSONDecodeError):
497
- LOGGER.debug("Devialet: JSON error")
524
+ LOGGER.debug("Devialet: unknown response type")
498
525
  return False
499
526
  except Exception: # pylint: disable=bare-except
500
527
  LOGGER.debug("Devialet: unknown exception occurred")
501
528
  return False
529
+
530
+ async def _async_on_search_response(self, data: CaseInsensitiveDict) -> None:
531
+ """UPnP device detected."""
532
+ location = data['location']
533
+ location_regex = re.compile(f"(?<=Location:[ ])*http://{self._host}:(.*)/.*.xml", re.IGNORECASE)
534
+ location_result = location_regex.search(location)
535
+ if location_result:
536
+ requester = AiohttpRequester()
537
+ factory = UpnpFactory(requester)
538
+ self._upnp_device = await factory.async_create_device(location)
539
+ self._dmr_device = DmrDevice(self._upnp_device, None)
540
+
541
+ async def async_discover_upnp_device(self) -> None:
542
+ """Discover the UPnP device."""
543
+ if self._last_upnp_search is not None and (datetime.datetime.now() - self._last_upnp_search).total_seconds() < 60:
544
+ return
545
+ self._last_upnp_search = datetime.datetime.now()
546
+
547
+ await async_search(async_callback=self._async_on_search_response,
548
+ timeout=10,
549
+ search_target=MEDIA_RENDERER,
550
+ source=("0.0.0.0", 0))
551
+ LOGGER.debug("Discovering UPnP device for %s", self._host)
552
+
553
+ async def async_play_url_source(self, media_url: str, media_title: str, meta_data: Union[None, str, Mapping] = None) -> bool:
554
+ """Play media uri over UPnP."""
555
+ if not self.upnp_available:
556
+ LOGGER.error("No UPnP location discovered")
557
+ return
558
+
559
+ service = self._upnp_device.service(AV_TRANSPORT)
560
+ set_uri = service.action("SetAVTransportURI")
561
+
562
+ try:
563
+ result = await set_uri.async_call(InstanceID=0, CurrentURI=media_url, CurrentURIMetaData=meta_data)
564
+ LOGGER.debug("Action result: %s", str(result))
565
+ except UpnpActionResponseError as a:
566
+ LOGGER.error("Devialet: error playing %s: %s", media_title, a.error_desc)
567
+ except UpnpXmlParseError as x:
568
+ LOGGER.error("Devialet: error playing %s %s", media_title, x.text)
569
+
570
+ await self.async_upnp_play()
571
+
572
+ async def async_upnp_play(self) -> None:
573
+ """Send the play command over UPnP."""
574
+ if not self.upnp_available:
575
+ LOGGER.error("No UPnP location discovered")
576
+ return
577
+
578
+ service = self._upnp_device.service(AV_TRANSPORT)
579
+ set_uri = service.action("Play")
580
+
581
+ try:
582
+ await set_uri.async_call(InstanceID=0, Speed=1)
583
+ return
584
+ except UpnpActionResponseError:
585
+ return
586
+ except UpnpXmlParseError:
587
+ return
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: devialet
3
- Version: 1.4.5
3
+ Version: 1.5.0
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.0',
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