devialet 1.4.4__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,13 +1,13 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: devialet
3
- Version: 1.4.4
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
7
7
  Author: fwestenberg
8
8
  Author-email:
9
9
  License: MIT
10
- Keywords: Reolink,Home-Assistant
10
+ Keywords: Devialet,Home-Assistant
11
11
  Classifier: Development Status :: 4 - Beta
12
12
  Classifier: Intended Audience :: Developers
13
13
  Classifier: Topic :: Software Development :: Build Tools
@@ -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."""
@@ -168,8 +193,9 @@ class DevialetApi:
168
193
  source_type = source["type"]
169
194
  device_id = source["deviceId"]
170
195
 
171
- if self.device_role in SPEAKER_POSITIONS and (
172
- source_type == "optical" or source_type == "opticaljack"
196
+ if self.device_role in SPEAKER_POSITIONS and source_type in (
197
+ "optical",
198
+ "opticaljack",
173
199
  ):
174
200
  # Stereo devices have the role FrontLeft or FrontRight.
175
201
  # Add a suffix to the source to recognize the device.
@@ -189,7 +215,7 @@ class DevialetApi:
189
215
  def available_options(self) -> any | None:
190
216
  """Return the list of available options for this source."""
191
217
  try:
192
- return self._source_state["availableOptions"]
218
+ return self._source_state["availableOperations"]
193
219
  except (KeyError, TypeError):
194
220
  return None
195
221
 
@@ -264,16 +290,16 @@ class DevialetApi:
264
290
  source_type == "optical" or source_type == "opticaljack"
265
291
  ) and self.device_role in SPEAKER_POSITIONS:
266
292
  for role, position in SPEAKER_POSITIONS.items():
267
- if (device_id == self.device_id and role == self.device_role) or (
293
+ if (
294
+ device_id == self.device_id and role == self.device_role
295
+ ) or (
268
296
  device_id != self.device_id and role != self.device_role
269
297
  ):
270
298
  source_type = source_type + "_" + position
271
-
272
- break
299
+ return source_type
273
300
  except (KeyError, TypeError):
274
301
  return None
275
-
276
- return source_type
302
+ return None
277
303
 
278
304
  @property
279
305
  def night_mode(self) -> bool | None:
@@ -304,56 +330,57 @@ class DevialetApi:
304
330
  "equalizer": self._equalizer,
305
331
  "source_list": self.source_list,
306
332
  "source": self.source,
333
+ "upnp_device_info": self._upnp_device.device_info
307
334
  }
308
335
 
309
336
  async def async_volume_up(self) -> None:
310
337
  """Volume up media player."""
311
- await self.post_request(UrlSuffix.VOLUME_UP, {})
338
+ await self._async_post_request(UrlSuffix.VOLUME_UP)
312
339
 
313
340
  async def async_volume_down(self) -> None:
314
341
  """Volume down media player."""
315
- await self.post_request(UrlSuffix.VOLUME_DOWN, {})
342
+ await self._async_post_request(UrlSuffix.VOLUME_DOWN)
316
343
 
317
344
  async def async_set_volume_level(self, volume: float) -> None:
318
345
  """Set volume level, range 0..1."""
319
- await self.post_request(
346
+ await self._async_post_request(
320
347
  UrlSuffix.VOLUME_SET,
321
- {"volume": volume * 100},
348
+ json_body={"volume": volume * 100},
322
349
  )
323
350
 
324
351
  async def async_mute_volume(self, mute: bool) -> None:
325
352
  """Mute (true) or unmute (false) media player."""
326
353
  if mute:
327
- await self.post_request(UrlSuffix.MUTE, {})
354
+ await self._async_post_request(UrlSuffix.MUTE)
328
355
  else:
329
- await self.post_request(UrlSuffix.UNMUTE, {})
356
+ await self._async_post_request(UrlSuffix.UNMUTE)
330
357
 
331
358
  async def async_media_play(self) -> None:
332
359
  """Play media player."""
333
- await self.post_request(UrlSuffix.PLAY, {})
360
+ await self._async_post_request(UrlSuffix.PLAY)
334
361
 
335
362
  async def async_media_pause(self) -> None:
336
363
  """Pause media player."""
337
- await self.post_request(UrlSuffix.PAUSE, {})
364
+ await self._async_post_request(UrlSuffix.PAUSE)
338
365
 
339
366
  async def async_media_stop(self) -> None:
340
367
  """Pause media player."""
341
- await self.post_request(UrlSuffix.PAUSE, {})
368
+ await self._async_post_request(UrlSuffix.PAUSE)
342
369
 
343
370
  async def async_media_next_track(self) -> None:
344
371
  """Send the next track command."""
345
- await self.post_request(UrlSuffix.NEXT_TRACK, {})
372
+ await self._async_post_request(UrlSuffix.NEXT_TRACK)
346
373
 
347
374
  async def async_media_previous_track(self) -> None:
348
375
  """Send the previous track command."""
349
- await self.post_request(UrlSuffix.PREVIOUS_TRACK, {})
376
+ await self._async_post_request(UrlSuffix.PREVIOUS_TRACK)
350
377
 
351
378
  async def async_media_seek(self, position: float) -> None:
352
379
  """Send seek command."""
353
380
 
354
- await self.post_request(
381
+ await self._async_post_request(
355
382
  UrlSuffix.SEEK,
356
- {"position": int(position)},
383
+ json_body={"position": int(position)},
357
384
  )
358
385
 
359
386
  async def async_set_night_mode(self, night_mode: bool) -> None:
@@ -363,22 +390,21 @@ class DevialetApi:
363
390
  else:
364
391
  mode = "off"
365
392
 
366
- await self.post_request(
393
+ await self._async_post_request(
367
394
  UrlSuffix.NIGHT_MODE,
368
- {"nightMode": mode},
395
+ json_body={"nightMode": mode},
369
396
  )
370
397
 
371
398
  async def async_set_equalizer(self, preset: str) -> None:
372
399
  """Set the equalizer preset."""
373
-
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."""
@@ -394,24 +420,26 @@ class DevialetApi:
394
420
  name_split = name.split("_")
395
421
 
396
422
  for role, position in SPEAKER_POSITIONS.items():
397
- if position == name_split[1]:
398
- if role == self.device_role:
399
- for _source in self._sources["sources"]:
400
- if (
401
- _source["deviceId"] == self.device_id
402
- and _source["type"] == name_split[0]
403
- ):
404
- source_id = _source["sourceId"]
405
- break
406
- else:
407
- for _source in self._sources["sources"]:
408
- if (
409
- _source["deviceId"] != self.device_id
410
- and _source["type"] == name_split[0]
411
- ):
412
- source_id = _source["sourceId"]
413
- break
414
- break
423
+ if position != name_split[1]:
424
+ continue
425
+
426
+ if role == self.device_role:
427
+ for _source in self._sources["sources"]:
428
+ if (
429
+ _source["deviceId"] == self.device_id
430
+ and _source["type"] == name_split[0]
431
+ ):
432
+ source_id = _source["sourceId"]
433
+ break
434
+ else:
435
+ for _source in self._sources["sources"]:
436
+ if (
437
+ _source["deviceId"] != self.device_id
438
+ and _source["type"] == name_split[0]
439
+ ):
440
+ source_id = _source["sourceId"]
441
+ break
442
+ break
415
443
  else:
416
444
  for _source in self._sources["sources"]:
417
445
  if _source["type"] == name:
@@ -421,13 +449,12 @@ class DevialetApi:
421
449
  LOGGER.error("Source %s is not available", source)
422
450
  return
423
451
 
424
- await self.post_request(
425
- 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)
426
454
  )
427
455
 
428
- async def get_request(self, suffix=str) -> any | None:
456
+ async def _async_get_request(self, suffix: str) -> any | None:
429
457
  """Generic GET method."""
430
-
431
458
  url = "http://" + self._host + str(suffix)
432
459
 
433
460
  try:
@@ -453,12 +480,12 @@ class DevialetApi:
453
480
  except aiohttp.ClientConnectorError as conn_err:
454
481
  LOGGER.debug("Host %s: Connection error %s", self._host, str(conn_err))
455
482
  self._is_available = False
483
+ self._upnp_device = None
456
484
  return None
457
485
  except asyncio.TimeoutError:
486
+ LOGGER.debug("Devialet connection timeout exception. Please check the connection")
458
487
  self._is_available = False
459
- LOGGER.debug(
460
- "Devialet connection timeout exception. Please check the connection"
461
- )
488
+ self._upnp_device = None
462
489
  return None
463
490
  except (TypeError, json.JSONDecodeError):
464
491
  LOGGER.debug("Devialet: JSON error")
@@ -467,20 +494,20 @@ class DevialetApi:
467
494
  LOGGER.debug("Devialet: unknown exception occurred")
468
495
  return None
469
496
 
470
- 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:
471
498
  """Generic POST method."""
472
-
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,13 +1,13 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: devialet
3
- Version: 1.4.4
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
7
7
  Author: fwestenberg
8
8
  Author-email:
9
9
  License: MIT
10
- Keywords: Reolink,Home-Assistant
10
+ Keywords: Devialet,Home-Assistant
11
11
  Classifier: Development Status :: 4 - Beta
12
12
  Classifier: Intended Audience :: Developers
13
13
  Classifier: Topic :: Software Development :: Build Tools
@@ -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.4',
6
+ version='1.5.0',
7
7
  license='MIT',
8
8
  description='Devialet API',
9
9
  long_description_content_type="text/markdown",
@@ -12,9 +12,9 @@ setup(
12
12
  author_email='',
13
13
  url='https://github.com/fwestenberg/devialet',
14
14
  download_url='https://github.com/fwestenberg/devialet/releases/latest',
15
- keywords=['Reolink', 'Home-Assistant'],
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.4/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