-
Notifications
You must be signed in to change notification settings - Fork 229
/
core.py
executable file
·2911 lines (2450 loc) · 102 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pylint: disable=fixme, protected-access
"""The core module contains the SoCo class that implements
the main entry to the SoCo functionality
"""
import datetime
import logging
import re
import socket
from functools import wraps
import urllib.parse
from xml.sax.saxutils import escape
from xml.parsers.expat import ExpatError
from typing import Optional
import warnings
import xmltodict
import requests
from requests.exceptions import ConnectionError as RequestsConnectionError
from requests.exceptions import ConnectTimeout, ReadTimeout
from . import config
from .data_structures import (
DidlObject,
DidlPlaylistContainer,
DidlResource,
Queue,
to_didl_string,
)
from .cache import Cache
from .data_structures_entry import from_didl_string
from .exceptions import (
SoCoSlaveException,
SoCoUPnPException,
NotSupportedException,
SoCoNotVisibleException,
)
from .groups import ZoneGroup
from .music_library import MusicLibrary
from .services import (
DeviceProperties,
ContentDirectory,
RenderingControl,
AVTransport,
ZoneGroupTopology,
AlarmClock,
SystemProperties,
MusicServices,
AudioIn,
GroupRenderingControl,
)
from .utils import really_utf8, camel_to_underscore, deprecated
from .xml import XML
_LOG = logging.getLogger(__name__)
class _ArgsSingleton(type):
"""A metaclass which permits only a single instance of each derived class
sharing the same `_class_group` class attribute to exist for any given set
of positional arguments.
Attempts to instantiate a second instance of a derived class, or another
class with the same `_class_group`, with the same args will return the
existing instance.
For example:
>>> class ArgsSingletonBase(object):
... __metaclass__ = _ArgsSingleton
...
>>> class First(ArgsSingletonBase):
... _class_group = "greeting"
... def __init__(self, param):
... pass
...
>>> class Second(ArgsSingletonBase):
... _class_group = "greeting"
... def __init__(self, param):
... pass
>>> assert First('hi') is First('hi')
>>> assert First('hi') is First('bye')
AssertionError
>>> assert First('hi') is Second('hi')
"""
_instances = {}
def __call__(cls, *args, **kwargs):
key = cls._class_group if hasattr(cls, "_class_group") else cls
if key not in cls._instances:
cls._instances[key] = {}
if args not in cls._instances[key]:
cls._instances[key][args] = super().__call__(*args, **kwargs)
return cls._instances[key][args]
class _SocoSingletonBase( # pylint: disable=too-few-public-methods,no-init
_ArgsSingleton("ArgsSingletonMeta", (object,), {})
):
"""The base class for the SoCo class.
Uses a Python 2 and 3 compatible method of declaring a metaclass. See, eg,
here: http://www.artima.com/weblogs/viewpost.jsp?thread=236234 and
here: http://mikewatkins.ca/2008/11/29/python-2-and-3-metaclasses/
"""
def only_on_master(function):
"""Decorator that raises SoCoSlaveException on master call on slave."""
@wraps(function)
def inner_function(self, *args, **kwargs):
"""Master checking inner function."""
if not self.is_coordinator:
message = (
'The method or property "{}" can only be called/used '
"on the coordinator in a group".format(function.__name__)
)
raise SoCoSlaveException(message)
return function(self, *args, **kwargs)
return inner_function
def only_on_soundbars(function):
"""Decorator to raise an exception on soundbar property access on non-soundbars."""
@wraps(function)
def inner_function(self, *args, **kwargs):
if not self.is_soundbar:
raise NotSupportedException(
"The device is not a soundbar and doesn't support %s."
% function.__name__
)
return function(self, *args, **kwargs)
return inner_function
# pylint: disable=R0904,too-many-instance-attributes
class SoCo(_SocoSingletonBase):
"""A simple class for controlling a Sonos speaker.
For any given set of arguments to __init__, only one instance of this class
may be created. Subsequent attempts to create an instance with the same
arguments will return the previously created instance. This means that all
SoCo instances created with the same ip address are in fact the *same* SoCo
instance, reflecting the real world position.
.. rubric:: Basic Methods
.. autosummary::
play_from_queue
play
play_uri
pause
stop
end_direct_control_session
seek
next
previous
mute
volume
play_mode
shuffle
repeat
cross_fade
ramp_to_volume
set_relative_volume
get_current_track_info
get_current_media_info
get_speaker_info
get_current_transport_info
.. rubric:: Queue Management
.. autosummary::
get_queue
queue_size
add_to_queue
add_uri_to_queue
add_multiple_to_queue
remove_from_queue
clear_queue
.. rubric:: Group Management
.. autosummary::
group
partymode
join
unjoin
all_groups
all_zones
visible_zones
.. rubric:: Player Identity and Settings
.. autosummary::
player_name
uid
household_id
is_visible
is_bridge
is_coordinator
is_soundbar
is_satellite
has_satellites
sub_enabled
is_subwoofer
has_subwoofer
channel
bass
treble
loudness
balance
night_mode
dialog_mode
surround_enabled
surround_music_playback
surround_volume_tv
surround_volume_music
soundbar_audio_input_format
supports_fixed_volume
fixed_volume
soundbar_audio_input_format
soundbar_audio_input_format_code
trueplay
status_light
buttons_enabled
.. rubric:: Playlists and Favorites
.. autosummary::
get_sonos_playlists
create_sonos_playlist
create_sonos_playlist_from_queue
remove_sonos_playlist
add_item_to_sonos_playlist
reorder_sonos_playlist
clear_sonos_playlist
move_in_sonos_playlist
remove_from_sonos_playlist
get_sonos_playlist_by_attr
get_favorite_radio_shows
get_favorite_radio_stations
get_sonos_favorites
.. rubric:: Miscellaneous
.. autosummary::
music_source
music_source_from_uri
is_playing_radio
is_playing_tv
is_playing_line_in
switch_to_line_in
switch_to_tv
available_actions
set_sleep_timer
get_sleep_timer
create_stereo_pair
separate_stereo_pair
get_battery_info
boot_seqnum
.. warning::
Properties on this object are not generally cached and may obtain
information over the network, so may take longer than expected to set
or return a value. It may be a good idea for you to cache the value in
your own code.
.. note::
Since all methods/properties on this object will result in an UPnP
request, they might result in an exception without it being mentioned
in the Raises section.
In most cases, the exception will be a
:class:`soco.exceptions.SoCoUPnPException`
(if the player returns an UPnP error code), but in special cases
it might also be another :class:`soco.exceptions.SoCoException`
or even a `requests` exception.
"""
_class_group = "SoCo"
# pylint: disable=super-on-old-class
def __init__(self, ip_address):
# Note: Creation of a SoCo instance should be as cheap and quick as
# possible. Do not make any network calls here
super().__init__()
# Check if ip_address is a valid IPv4 representation.
# Sonos does not (yet) support IPv6
try:
socket.inet_aton(ip_address)
except OSError as error:
raise ValueError("Not a valid IP address string") from error
#: The speaker's ip address
self.ip_address = ip_address
self.speaker_info = {} # Stores information about the current speaker
# The services which we use
# pylint: disable=invalid-name
self.avTransport = AVTransport(self)
self.contentDirectory = ContentDirectory(self)
self.deviceProperties = DeviceProperties(self)
self.renderingControl = RenderingControl(self)
self.groupRenderingControl = GroupRenderingControl(self)
self.zoneGroupTopology = ZoneGroupTopology(self)
self.alarmClock = AlarmClock(self)
self.systemProperties = SystemProperties(self)
self.musicServices = MusicServices(self)
self.audioIn = AudioIn(self)
self.music_library = MusicLibrary(self)
# Some private attributes
self._all_zones = set()
self._boot_seqnum = None
self._groups = set()
self._channel_map = None
self._ht_sat_chan_map = None
self._is_bridge = None
self._is_coordinator = False
self._is_satellite = False
self._has_satellites = False
self._channel = None
self._is_soundbar = None
self._player_name = None
self._uid = None
self._household_id = None
self._visible_zones = set()
self._zgs_cache = Cache(default_timeout=5)
self._zgs_result = None
_LOG.debug("Created SoCo instance for ip: %s", ip_address)
def __str__(self):
return "<{} object at ip {}>".format(self.__class__.__name__, self.ip_address)
def __repr__(self):
return '{}("{}")'.format(self.__class__.__name__, self.ip_address)
@property
def boot_seqnum(self):
"""int: The boot sequence number."""
self._parse_zone_group_state()
return int(self._boot_seqnum)
@property
def player_name(self):
"""str: The speaker's name."""
# We could get the name like this:
# result = self.deviceProperties.GetZoneAttributes()
# return result["CurrentZoneName"]
# but it is probably quicker to get it from the group topology
# and take advantage of any caching
self._parse_zone_group_state()
return self._player_name
@player_name.setter
def player_name(self, playername):
"""Set the speaker's name."""
self.deviceProperties.SetZoneAttributes(
[
("DesiredZoneName", playername),
("DesiredIcon", ""),
("DesiredConfiguration", ""),
]
)
@property
def uid(self):
"""str: A unique identifier.
Looks like: ``'RINCON_000XXXXXXXXXX1400'``
"""
# Since this does not change over time (?) check whether we already
# know the answer. If so, there is no need to go further
if self._uid is not None:
return self._uid
# if not, we have to get it from the zone topology, which
# is probably quicker than any alternative, since the zgt is probably
# cached. This will set self._uid for us for next time, so we won't
# have to do this again
self._parse_zone_group_state()
return self._uid
# An alternative way of getting the uid is as follows:
# self.device_description_url = \
# 'http://{0}:1400/xml/device_description.xml'.format(
# self.ip_address)
# response = requests.get(self.device_description_url).text
# tree = XML.fromstring(response.encode('utf-8'))
# udn = tree.findtext('.//{urn:schemas-upnp-org:device-1-0}UDN')
# # the udn has a "uuid:" prefix before the uid, so we need to strip it
# self._uid = uid = udn[5:]
# return uid
@property
def household_id(self):
"""str: A unique identifier for all players in a household.
Looks like: ``'Sonos_asahHKgjgJGjgjGjggjJgjJG34'``
"""
# Since this does not change over time (?) check whether we already
# know the answer. If so, return the cached version
if self._household_id is None:
self._household_id = self.deviceProperties.GetHouseholdID()[
"CurrentHouseholdID"
]
return self._household_id
@property
def is_visible(self):
"""bool: Is this zone visible?
A zone might be invisible if, for example, it is a bridge, or the slave
part of stereo pair.
"""
# We could do this:
# invisible = self.deviceProperties.GetInvisible()['CurrentInvisible']
# but it is better to do it in the following way, which uses the
# zone group topology, to capitalise on any caching.
return self in self.visible_zones
@property
def is_bridge(self):
"""bool: Is this zone a bridge?"""
# Since this does not change over time (?) check whether we already
# know the answer. If so, there is no need to go further
if self._is_bridge is not None:
return self._is_bridge
# if not, we have to get it from the zone topology. This will set
# self._is_bridge for us for next time, so we won't have to do this
# again
self._parse_zone_group_state()
return self._is_bridge
@property
def is_coordinator(self):
"""bool: Is this zone a group coordinator?"""
# We could do this:
# invisible = self.deviceProperties.GetInvisible()['CurrentInvisible']
# but it is better to do it in the following way, which uses the
# zone group topology, to capitalise on any caching.
self._parse_zone_group_state()
return self._is_coordinator
@property
def is_satellite(self):
"""bool: Is this zone a satellite in a home theater setup?"""
self._parse_zone_group_state()
return self._is_satellite
@property
def has_satellites(self):
"""bool: Is this zone configured with satellites in a home theater setup?
Will only return True on the primary device in a home theater configuration.
"""
self._parse_zone_group_state()
return self._has_satellites
@property
def is_subwoofer(self):
"""bool: Is this zone a subwoofer?"""
if self.channel == "SW":
return True
return False
@property
def has_subwoofer(self):
"""bool: Is this zone configured with a subwoofer?
Only provides reliable results when called on the soundbar
or subwoofer devices if configured in a home theater setup.
"""
self._parse_zone_group_state()
channel_map = self._channel_map or self._ht_sat_chan_map
if not channel_map:
return False
if ":SW" in channel_map: # pylint: disable=E1135
return True
return False
@property
def channel(self):
"""str: Location of this zone in a home theater or paired configuration.
Can be one of "LF,RF", "LF", "RF", "LR", "RR", "SW", or None.
"""
self._parse_zone_group_state()
# Omit repeated channel entries (e.g., "RF,RF" -> "RF")
if self._channel:
channels = set(self._channel.split(","))
if len(channels) == 1:
return channels.pop()
return self._channel
@property
def is_soundbar(self):
"""bool: Is this zone a soundbar (i.e. has night mode etc.)?"""
if self._is_soundbar is None:
if not self.speaker_info:
self.get_speaker_info()
model_name = self.speaker_info["model_name"].lower()
self._is_soundbar = any(model_name.endswith(s) for s in SOUNDBARS)
return self._is_soundbar
@property
def play_mode(self):
"""str: The queue's play mode.
Case-insensitive options are:
* ``'NORMAL'`` -- Turns off shuffle and repeat.
* ``'REPEAT_ALL'`` -- Turns on repeat and turns off shuffle.
* ``'SHUFFLE'`` -- Turns on shuffle *and* repeat. (It's
strange, I know.)
* ``'SHUFFLE_NOREPEAT'`` -- Turns on shuffle and turns off
repeat.
* ``'REPEAT_ONE'`` -- Turns on repeat one and turns off shuffle.
* ``'SHUFFLE_REPEAT_ONE'`` -- Turns on shuffle *and* repeat one. (It's
strange, I know.)
"""
result = self.avTransport.GetTransportSettings(
[
("InstanceID", 0),
]
)
return result["PlayMode"]
@play_mode.setter
def play_mode(self, playmode):
"""Set the speaker's mode."""
playmode = playmode.upper()
if playmode not in PLAY_MODES:
raise KeyError("'%s' is not a valid play mode" % playmode)
self.avTransport.SetPlayMode([("InstanceID", 0), ("NewPlayMode", playmode)])
@property
def shuffle(self):
"""bool: The queue's shuffle option.
True if enabled, False otherwise.
"""
return PLAY_MODES[self.play_mode][0]
@shuffle.setter
def shuffle(self, shuffle):
"""Set the queue's shuffle option."""
repeat = self.repeat
self.play_mode = PLAY_MODE_BY_MEANING[(shuffle, repeat)]
@property
def repeat(self):
"""bool: The queue's repeat option.
True if enabled, False otherwise.
Can also be the string ``'ONE'`` for play mode
``'REPEAT_ONE'``.
"""
return PLAY_MODES[self.play_mode][1]
@repeat.setter
def repeat(self, repeat):
"""Set the queue's repeat option"""
shuffle = self.shuffle
self.play_mode = PLAY_MODE_BY_MEANING[(shuffle, repeat)]
@property
@only_on_master # Only for symmetry with the setter
def cross_fade(self):
"""bool: The speaker's cross fade state.
True if enabled, False otherwise
"""
response = self.avTransport.GetCrossfadeMode(
[
("InstanceID", 0),
]
)
cross_fade_state = response["CrossfadeMode"]
return bool(int(cross_fade_state))
@cross_fade.setter
@only_on_master
def cross_fade(self, crossfade):
"""Set the speaker's cross fade state."""
crossfade_value = "1" if crossfade else "0"
self.avTransport.SetCrossfadeMode(
[("InstanceID", 0), ("CrossfadeMode", crossfade_value)]
)
def ramp_to_volume(self, volume, ramp_type="SLEEP_TIMER_RAMP_TYPE"):
"""Smoothly change the volume.
There are three ramp types available:
* ``'SLEEP_TIMER_RAMP_TYPE'`` (default): Linear ramp from the
current volume up or down to the new volume. The ramp rate is
1.25 steps per second. For example: To change from volume 50 to
volume 30 would take 16 seconds.
* ``'ALARM_RAMP_TYPE'``: Resets the volume to zero, waits for about
30 seconds, and then ramps the volume up to the desired value at
a rate of 2.5 steps per second. For example: Volume 30 would take
12 seconds for the ramp up (not considering the wait time).
* ``'AUTOPLAY_RAMP_TYPE'``: Resets the volume to zero and then
quickly ramps up at a rate of 50 steps per second. For example:
Volume 30 will take only 0.6 seconds.
The ramp rate is selected by Sonos based on the chosen ramp type and
the resulting transition time returned.
This method is non blocking and has no network overhead once sent.
Args:
volume (int): The new volume.
ramp_type (str, optional): The desired ramp type, as described
above.
Returns:
int: The ramp time in seconds, rounded down. Note that this does
not include the wait time.
"""
response = self.renderingControl.RampToVolume(
[
("InstanceID", 0),
("Channel", "Master"),
("RampType", ramp_type),
("DesiredVolume", volume),
("ResetVolumeAfter", False),
("ProgramURI", ""),
]
)
return int(response["RampTime"])
def set_relative_volume(self, relative_volume):
"""Adjust the volume up or down by a relative amount.
If the adjustment causes the volume to overshoot the maximum value
of 100, the volume will be set to 100. If the adjustment causes the
volume to undershoot the minimum value of 0, the volume will be set
to 0.
Note that this method is an alternative to using addition and
subtraction assignment operators (+=, -=) on the `volume` property
of a `SoCo` instance. These operators perform the same function as
`set_relative_volume` but require two network calls per operation
instead of one.
Args:
relative_volume (int): The relative volume adjustment. Can be
positive or negative.
Returns:
int: The new volume setting.
Raises:
ValueError: If ``relative_volume`` cannot be cast as an integer.
"""
relative_volume = int(relative_volume)
# Sonos will automatically handle out-of-range adjustments
response = self.renderingControl.SetRelativeVolume(
[("InstanceID", 0), ("Channel", "Master"), ("Adjustment", relative_volume)]
)
return int(response["NewVolume"])
@only_on_master
def play_from_queue(self, index, start=True):
"""Play a track from the queue by index.
The index number is required as an argument, where the first index
is 0.
Args:
index (int): 0-based index of the track to play
start (bool): If the item that has been set should start playing
"""
# Grab the speaker's information if we haven't already since we'll need
# it in the next step.
if not self.speaker_info:
self.get_speaker_info()
# first, set the queue itself as the source URI
uri = "x-rincon-queue:{}#0".format(self.uid)
self.avTransport.SetAVTransportURI(
[("InstanceID", 0), ("CurrentURI", uri), ("CurrentURIMetaData", "")]
)
# second, set the track number with a seek command
self.avTransport.Seek(
[("InstanceID", 0), ("Unit", "TRACK_NR"), ("Target", index + 1)]
)
# finally, just play what's set if needed
if start:
self.play()
@only_on_master
def play(self):
"""Play the currently selected track."""
self.avTransport.Play([("InstanceID", 0), ("Speed", 1)])
@only_on_master
# pylint: disable=too-many-arguments
def play_uri(self, uri="", meta="", title="", start=True, force_radio=False):
"""Play a URI.
Playing a URI will replace what was playing with the stream
given by the URI. For some streams at least a title is
required as metadata. This can be provided using the ``meta``
argument or the ``title`` argument. If the ``title`` argument
is provided minimal metadata will be generated. If ``meta``
argument is provided the ``title`` argument is ignored.
Args:
uri (str): URI of the stream to be played.
meta (str): The metadata to show in the player, DIDL format.
title (str): The title to show in the player (if no meta).
start (bool): If the URI that has been set should start playing.
force_radio (bool): forces a uri to play as a radio stream.
On a Sonos controller music is shown with one of the following display
formats and controls:
* Radio format: Shows the name of the radio station and other available
data. No seek, next, previous, or voting capability.
Examples: TuneIn, radioPup
* Smart Radio: Shows track name, artist, and album. Limited seek, next
and sometimes voting capability depending on the Music Service.
Examples: Amazon Prime Stations, Pandora Radio Stations.
* Track format: Shows track name, artist, and album the same as when
playing from a queue. Full seek, next and previous capabilities.
Examples: Spotify, Napster, Rhapsody.
How it is displayed is determined by the URI prefix:
``x-sonosapi-stream:``, ``x-sonosapi-radio:``,
``x-rincon-mp3radio:``, ``hls-radio:`` default to radio or
smart radio format depending on the stream. Others default to
track format: ``x-file-cifs:``, ``aac:``, ``http:``,
``https:``, ``x-sonos-spotify:`` (used by Spotify),
``x-sonosapi-hls-static:`` (Amazon Prime), ``x-sonos-http:``
(Google Play & Napster).
Some URIs that default to track format could be radio streams,
typically ``http:``, ``https:`` or ``aac:``. To force display
and controls to Radio format set ``force_radio=True``
.. note:: Other URI prefixes exist but are less common.
If you have information on these please add to this doc string.
.. note:: A change in Sonos® (as of at least version 6.4.2)
means that the devices no longer accepts ordinary ``http:``
and ``https:`` URIs for radio stations. This method has the
option to replaces these prefixes with the one that Sonos®
expects: ``x-rincon-mp3radio:`` by using the
"force_radio=True" parameter. A few streams may fail if
not forced to to Radio format.
"""
if meta == "" and title != "":
meta_template = (
'<DIDL-Lite xmlns:dc="http://purl.org/dc/elements'
'/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" '
'xmlns:r="urn:schemas-rinconnetworks-com:metadata-1-0/" '
'xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/">'
'<item id="R:0/0/0" parentID="R:0/0" restricted="true">'
"<dc:title>{title}</dc:title><upnp:class>"
"object.item.audioItem.audioBroadcast</upnp:class><desc "
'id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:'
'metadata-1-0/">{service}</desc></item></DIDL-Lite>'
)
tunein_service = "SA_RINCON65031_"
# Radio stations need to have at least a title to play
meta = meta_template.format(title=escape(title), service=tunein_service)
# change uri prefix to force radio style display and commands
if force_radio:
colon = uri.find(":")
if colon > 0:
uri = "x-rincon-mp3radio{}".format(uri[colon:])
self.avTransport.SetAVTransportURI(
[("InstanceID", 0), ("CurrentURI", uri), ("CurrentURIMetaData", meta)]
)
# The track is enqueued, now play it if needed
if start:
return self.play()
return False
@only_on_master
def pause(self):
"""Pause the currently playing track."""
self.avTransport.Pause([("InstanceID", 0), ("Speed", 1)])
@only_on_master
def stop(self):
"""Stop the currently playing track."""
self.avTransport.Stop([("InstanceID", 0), ("Speed", 1)])
@only_on_master
def end_direct_control_session(self):
"""Ends all third-party controlled streaming sessions."""
self.avTransport.EndDirectControlSession([("InstanceID", 0)])
@only_on_master
def seek(self, position=None, track=None):
"""Seek to a given position.
You can seek both a relative position in the current track and a track
number in the queue.
It is even possible to seek to a tuple or dict containing the absolute
position (relative pos. and track nr.)::
t = ('0:00:00', 0)
player.seek(*t)
d = {'position': '0:00:00', 'track': 0}
player.seek(**d)
Args:
position (str): The desired timestamp in the current track,
specified in the format of HH:MM:SS or H:MM:SS
track (int): The (zero-based) track index in the queue
Raises:
ValueError: If neither position nor track are specified.
SoCoUPnPException: UPnP Error 701 if seeking is not supported,
UPnP Error 711 if the target is invalid.
Note:
The 'track' parameter can only be used if the queue is currently
playing. If not, use :py:meth:`play_from_queue`.
This is currently faster than :py:meth:`play_from_queue` if already
using the queue, as it does not reinstate the queue.
If speaker is already playing it will continue to play after
seek. If paused it will remain paused.
"""
if track is None and position is None:
raise ValueError("No position or track information given")
if track is not None:
self.avTransport.Seek(
[("InstanceID", 0), ("Unit", "TRACK_NR"), ("Target", track + 1)]
)
if position is not None:
if not re.match(r"^[0-9][0-9]?:[0-9][0-9]:[0-9][0-9]$", position):
raise ValueError("invalid timestamp, use HH:MM:SS format")
self.avTransport.Seek(
[("InstanceID", 0), ("Unit", "REL_TIME"), ("Target", position)]
)
@only_on_master
def next(self):
"""Go to the next track.
Keep in mind that next() can return errors
for a variety of reasons. For example, if the Sonos is streaming
Pandora and you call next() several times in quick succession an error
code will likely be returned (since Pandora has limits on how many
songs can be skipped).
"""
self.avTransport.Next([("InstanceID", 0), ("Speed", 1)])
@only_on_master
def previous(self):
"""Go back to the previously played track.
Keep in mind that previous() can return errors
for a variety of reasons. For example, previous() will return an error
code (error code 701) if the Sonos is streaming Pandora since you can't
go back on tracks.
"""
self.avTransport.Previous([("InstanceID", 0), ("Speed", 1)])
@property
def mute(self):
"""bool: The speaker's mute state.
True if muted, False otherwise.
"""
response = self.renderingControl.GetMute(
[("InstanceID", 0), ("Channel", "Master")]
)
mute_state = response["CurrentMute"]
return bool(int(mute_state))
@mute.setter
def mute(self, mute):
"""Mute (or unmute) the speaker."""
mute_value = "1" if mute else "0"
self.renderingControl.SetMute(
[("InstanceID", 0), ("Channel", "Master"), ("DesiredMute", mute_value)]
)
@property
def volume(self):
"""int: The speaker's volume.
An integer between 0 and 100.
"""
response = self.renderingControl.GetVolume(
[
("InstanceID", 0),
("Channel", "Master"),
]
)
volume = response["CurrentVolume"]
return int(volume)
@volume.setter
def volume(self, volume):
"""Set the speaker's volume."""
volume = int(volume)
volume = max(0, min(volume, 100)) # Coerce in range
self.renderingControl.SetVolume(
[("InstanceID", 0), ("Channel", "Master"), ("DesiredVolume", volume)]
)
@property
def bass(self):
"""int: The speaker's bass EQ.
An integer between -10 and 10.
"""
response = self.renderingControl.GetBass(
[
("InstanceID", 0),
("Channel", "Master"),
]
)
bass = response["CurrentBass"]
return int(bass)
@bass.setter
def bass(self, bass):
"""Set the speaker's bass."""
bass = int(bass)
bass = max(-10, min(bass, 10)) # Coerce in range
self.renderingControl.SetBass([("InstanceID", 0), ("DesiredBass", bass)])
@property
def treble(self):
"""int: The speaker's treble EQ.
An integer between -10 and 10.
"""
response = self.renderingControl.GetTreble(
[
("InstanceID", 0),
("Channel", "Master"),
]
)
treble = response["CurrentTreble"]
return int(treble)
@treble.setter
def treble(self, treble):
"""Set the speaker's treble."""
treble = int(treble)
treble = max(-10, min(treble, 10)) # Coerce in range
self.renderingControl.SetTreble([("InstanceID", 0), ("DesiredTreble", treble)])
@property
def loudness(self):
"""bool: The speaker's loudness compensation.
True if on, False otherwise.
Loudness is a complicated topic. You can read about it on
Wikipedia: https://en.wikipedia.org/wiki/Loudness
"""
response = self.renderingControl.GetLoudness(
[