-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcore.py
1939 lines (1610 loc) · 72 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
# -*- coding: utf-8 -*-
# pylint: disable=C0302,fixme, protected-access
""" The core module contains the SoCo class that implements
the main entry to the SoCo functionality
"""
from __future__ import unicode_literals
import socket
import logging
import re
import requests
from functools import wraps
from .services import DeviceProperties, ContentDirectory
from .services import RenderingControl, AVTransport, ZoneGroupTopology
from .services import AlarmClock
from .groups import ZoneGroup
from .exceptions import SoCoUPnPException, SoCoSlaveException
from .data_structures import DidlPlaylistContainer,\
SearchResult, Queue, DidlObject, DidlMusicAlbum,\
from_didl_string, to_didl_string, DidlResource
from .utils import really_utf8, camel_to_underscore, really_unicode,\
url_escape_path
from .xml import XML
from soco import config
_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(_ArgsSingleton, cls).__call__(
*args, **kwargs)
return cls._instances[key][args]
class _SocoSingletonBase( # pylint: disable=too-few-public-methods,no-init
_ArgsSingleton(str('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/
"""
pass
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 "{0}" 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
# 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.
Public functions::
play -- Plays the current item.
play_uri -- Plays a track or a music stream by URI.
play_from_queue -- Plays an item in the queue.
pause -- Pause the currently playing track.
stop -- Stop the currently playing track.
seek -- Move the currently playing track a given elapsed time.
next -- Go to the next track.
previous -- Go back to the previous track.
switch_to_line_in -- Switch the speaker's input to line-in.
switch_to_tv -- Switch the playbar speaker's input to TV.
get_current_track_info -- Get information about the currently playing
track.
get_speaker_info -- Get information about the Sonos speaker.
partymode -- Put all the speakers in the network in the same group.
join -- Join this speaker to another "master" speaker.
unjoin -- Remove this speaker from a group.
get_queue -- Get information about the queue.
get_artists -- Get artists from the music library
get_album_artists -- Get album artists from the music library
get_albums -- Get albums from the music library
get_genres -- Get genres from the music library
get_composers -- Get composers from the music library
get_tracks -- Get tracks from the music library
get_playlists -- Get playlists from the music library
get_music_library_information -- Get information from the music library
get_current_transport_info -- get speakers playing state
browse_by_idstring -- Browse (get sub-elements) a given type
add_uri_to_queue -- Adds an URI to the queue
add_to_queue -- Add a track to the end of the queue
remove_from_queue -- Remove a track from the queue
clear_queue -- Remove all tracks from queue
get_favorite_radio_shows -- Get favorite radio shows from Sonos'
Radio app.
get_favorite_radio_stations -- Get favorite radio stations.
create_sonos_playlist -- Create a new empty Sonos playlist
create_sonos_playlist_from_queue -- Create a new Sonos playlist
from the current queue.
add_item_to_sonos_playlist -- Adds a queueable item to a Sonos'
playlist
get_item_album_art_uri -- Get an item's Album Art absolute URI.
search_track -- Search for an artist, artist's albums, or track.
get_albums_for_artist -- Get albums for an artist.
get_tracks_for_album -- Get tracks for an artist's album.
start_library_update -- Trigger an update of the music library.
Properties::
uid -- The speaker's unique identifier
mute -- The speaker's mute status.
volume -- The speaker's volume.
bass -- The speaker's bass EQ.
treble -- The speaker's treble EQ.
loudness -- The status of the speaker's loudness compensation.
cross_fade -- The status of the speaker's crossfade.
status_light -- The state of the Sonos status light.
player_name -- The speaker's name.
play_mode -- The queue's repeat/shuffle settings.
queue_size -- Get size of queue.
library_updating -- Whether music library update is in progress.
album_artist_display_option -- album artist display option
is_playing_tv -- Is the playbar speaker input from TV?
is_playing_radio -- Is the speaker input from radio?
is_playing_line_in -- Is the speaker input from line-in?
.. warning::
These properties are not cached and will 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.
"""
_class_group = 'SoCo'
# Key words used when performing searches
SEARCH_TRANSLATION = {'artists': 'A:ARTIST',
'album_artists': 'A:ALBUMARTIST',
'albums': 'A:ALBUM',
'genres': 'A:GENRE',
'composers': 'A:COMPOSER',
'tracks': 'A:TRACKS',
'playlists': 'A:PLAYLISTS',
'share': 'S:',
'sonos_playlists': 'SQ:',
'categories': 'A:'}
# 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(SoCo, self).__init__()
# Check if ip_address is a valid IPv4 representation.
# Sonos does not (yet) support IPv6
try:
socket.inet_aton(ip_address)
except socket.error:
raise ValueError("Not a valid IP address string")
#: 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.zoneGroupTopology = ZoneGroupTopology(self)
self.alarmClock = AlarmClock(self)
# Some private attributes
self._all_zones = set()
self._groups = set()
self._is_bridge = None
self._is_coordinator = False
self._player_name = None
self._uid = None
self._visible_zones = set()
self._zgs_cache = None
_LOG.debug("Created SoCo instance for ip: %s", ip_address)
def __str__(self):
return "<{0} object at ip {1}>".format(
self.__class__.__name__, self.ip_address)
def __repr__(self):
return '{0}("{1}")'.format(self.__class__.__name__, self.ip_address)
@property
def player_name(self):
""" The speaker's name. A string. """
# 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):
""" 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 is_visible(self):
""" Is this zone visible? A zone might be invisible if, for example it
is a bridge, or the slave part of stereo pair.
return True or False
"""
# 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):
""" 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):
""" Return True if this zone is a group coordinator, otherwise False.
return True or False
"""
# 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 play_mode(self):
""" 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.
"""
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
@only_on_master # Only for symmetry with the setter
def cross_fade(self):
""" The speaker's cross fade state.
True if enabled, False otherwise """
response = self.avTransport.GetCrossfadeMode([
('InstanceID', 0),
])
cross_fade_state = response['CrossfadeMode']
return True if int(cross_fade_state) else False
@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)
])
@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.
index: the index of the track to play; first item in the queue is 0
start: If the item that has been set should start playing
Returns:
True if the Sonos speaker successfully started playing the track.
False if the track did not start (this may be because it was not
requested to start because "start=False")
Raises SoCoException (or a subclass) upon errors.
"""
# 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}#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:
return self.play()
return False
@only_on_master
def play(self):
"""Play the currently selected track.
Returns:
True if the Sonos speaker successfully started playing the track.
Raises SoCoException (or a subclass) upon errors.
"""
self.avTransport.Play([
('InstanceID', 0),
('Speed', 1)
])
@only_on_master
def play_uri(self, uri='', meta='', title='', start=True):
""" Play a given stream. Pauses the queue.
If there is no metadata passed in and there is a title set then a
metadata object will be created. This is often the case if you have
a custom stream, it will need at least the title in the metadata in
order to play.
Arguments:
uri -- URI of a stream to be played.
meta -- The track metadata to show in the player, DIDL format.
title -- The track title to show in the player
start -- If the URI that has been set should start playing
Returns:
True if the Sonos speaker successfully started playing the track.
False if the track did not start (this may be because it was not
requested to start because "start=False")
Raises SoCoException (or a subclass) upon errors.
"""
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=title, service=tunein_service)
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.
Returns:
True if the Sonos speaker successfully paused the track.
Raises SoCoException (or a subclass) upon errors.
"""
self.avTransport.Pause([
('InstanceID', 0),
('Speed', 1)
])
@only_on_master
def stop(self):
""" Stop the currently playing track.
Returns:
True if the Sonos speaker successfully stopped the playing track.
Raises SoCoException (or a subclass) upon errors.
"""
self.avTransport.Stop([
('InstanceID', 0),
('Speed', 1)
])
@only_on_master
def seek(self, timestamp):
""" Seeks to a given timestamp in the current track, specified in the
format of HH:MM:SS or H:MM:SS.
Returns:
True if the Sonos speaker successfully seeked to the timecode.
Raises SoCoException (or a subclass) upon errors.
"""
if not re.match(r'^[0-9][0-9]?:[0-9][0-9]:[0-9][0-9]$', timestamp):
raise ValueError('invalid timestamp, use HH:MM:SS format')
self.avTransport.Seek([
('InstanceID', 0),
('Unit', 'REL_TIME'),
('Target', timestamp)
])
@only_on_master
def next(self):
""" Go to the next track.
Returns:
True if the Sonos speaker successfully skipped to the next track.
Raises SoCoException (or a subclass) upon errors.
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.
Returns:
True if the Sonos speaker successfully went to the previous track.
Raises SoCoException (or a subclass) upon errors.
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):
""" The speaker's mute state. True if muted, False otherwise """
response = self.renderingControl.GetMute([
('InstanceID', 0),
('Channel', 'Master')
])
mute_state = response['CurrentMute']
return True if int(mute_state) else False
@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):
""" 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):
""" 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):
""" 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):
""" The Sonos speaker's loudness compensation. True if on, otherwise
False.
Loudness is a complicated topic. You can find a nice summary about this
feature here: http://forums.sonos.com/showthread.php?p=4698#post4698
"""
response = self.renderingControl.GetLoudness([
('InstanceID', 0),
('Channel', 'Master'),
])
loudness = response["CurrentLoudness"]
return True if int(loudness) else False
@loudness.setter
def loudness(self, loudness):
""" Switch on/off the speaker's loudness compensation """
loudness_value = '1' if loudness else '0'
self.renderingControl.SetLoudness([
('InstanceID', 0),
('Channel', 'Master'),
('DesiredLoudness', loudness_value)
])
def _parse_zone_group_state(self):
""" The Zone Group State contains a lot of useful information. Retrieve
and parse it, and populate the relevant properties. """
# zoneGroupTopology.GetZoneGroupState()['ZoneGroupState'] returns XML like
# this:
#
# <ZoneGroups>
# <ZoneGroup Coordinator="RINCON_000XXX1400" ID="RINCON_000XXXX1400:0">
# <ZoneGroupMember
# BootSeq="33"
# Configuration="1"
# Icon="x-rincon-roomicon:zoneextender"
# Invisible="1"
# IsZoneBridge="1"
# Location="http://192.168.1.100:1400/xml/device_description.xml"
# MinCompatibleVersion="22.0-00000"
# SoftwareVersion="24.1-74200"
# UUID="RINCON_000ZZZ1400"
# ZoneName="BRIDGE"/>
# </ZoneGroup>
# <ZoneGroup Coordinator="RINCON_000XXX1400" ID="RINCON_000XXX1400:46">
# <ZoneGroupMember
# BootSeq="44"
# Configuration="1"
# Icon="x-rincon-roomicon:living"
# Location="http://192.168.1.101:1400/xml/device_description.xml"
# MinCompatibleVersion="22.0-00000"
# SoftwareVersion="24.1-74200"
# UUID="RINCON_000XXX1400"
# ZoneName="Living Room"/>
# <ZoneGroupMember
# BootSeq="52"
# Configuration="1"
# Icon="x-rincon-roomicon:kitchen"
# Location="http://192.168.1.102:1400/xml/device_description.xml"
# MinCompatibleVersion="22.0-00000"
# SoftwareVersion="24.1-74200"
# UUID="RINCON_000YYY1400"
# ZoneName="Kitchen"/>
# </ZoneGroup>
# </ZoneGroups>
#
def parse_zone_group_member(member_element):
""" Parse a ZoneGroupMember or Satellite element from Zone Group
State, create a SoCo instance for the member, set basic attributes
and return it. """
# Create a SoCo instance for each member. Because SoCo
# instances are singletons, this is cheap if they have already
# been created, and useful if they haven't. We can then
# update various properties for that instance.
member_attribs = member_element.attrib
ip_addr = member_attribs['Location'].\
split('//')[1].split(':')[0]
zone = config.SOCO_CLASS(ip_addr)
# uid doesn't change, but it's not harmful to (re)set it, in case
# the zone is as yet unseen.
zone._uid = member_attribs['UUID']
zone._player_name = member_attribs['ZoneName']
# add the zone to the set of all members, and to the set
# of visible members if appropriate
is_visible = False if member_attribs.get(
'Invisible') == '1' else True
if is_visible:
self._visible_zones.add(zone)
self._all_zones.add(zone)
return zone
# This is called quite frequently, so it is worth optimising it.
# Maintain a private cache. If the zgt has not changed, there is no
# need to repeat all the XML parsing. In addition, switch on network
# caching for a short interval (5 secs).
zgs = self.zoneGroupTopology.GetZoneGroupState(
cache_timeout=5)['ZoneGroupState']
if zgs == self._zgs_cache:
return
self._zgs_cache = zgs
tree = XML.fromstring(zgs.encode('utf-8'))
# Empty the set of all zone_groups
self._groups.clear()
# and the set of all members
self._all_zones.clear()
self._visible_zones.clear()
# Loop over each ZoneGroup Element
#for group_element in tree.findall('ZoneGroup'):
for group_element in tree.find('ZoneGroups').findall('ZoneGroup'):
coordinator_uid = group_element.attrib['Coordinator']
group_uid = group_element.attrib['ID']
group_coordinator = None
members = set()
for member_element in group_element.findall('ZoneGroupMember'):
zone = parse_zone_group_member(member_element)
# Perform extra processing relevant to direct zone group
# members
#
# If this element has the same UUID as the coordinator, it is
# the coordinator
if zone._uid == coordinator_uid:
group_coordinator = zone
zone._is_coordinator = True
else:
zone._is_coordinator = False
# is_bridge doesn't change, but it does no real harm to
# set/reset it here, just in case the zone has not been seen
# before
zone._is_bridge = True if member_element.attrib.get(
'IsZoneBridge') == '1' else False
# add the zone to the members for this group
members.add(zone)
# Loop over Satellite elements if present, and process as for
# ZoneGroup elements
for satellite_element in member_element.findall('Satellite'):
zone = parse_zone_group_member(satellite_element)
# Assume a satellite can't be a bridge or coordinator, so
# no need to check.
#
# Add the zone to the members for this group.
members.add(zone)
# Now create a ZoneGroup with this info and add it to the list
# of groups
self._groups.add(ZoneGroup(group_uid, group_coordinator, members))
@property
def all_groups(self):
""" Return a set of all the available groups"""
self._parse_zone_group_state()
return self._groups
@property
def group(self):
"""The Zone Group of which this device is a member.
group will be None if this zone is a slave in a stereo pair."""
for group in self.all_groups:
if self in group:
return group
return None
# To get the group directly from the network, try the code below
# though it is probably slower than that above
# current_group_id = self.zoneGroupTopology.GetZoneGroupAttributes()[
# 'CurrentZoneGroupID']
# if current_group_id:
# for group in self.all_groups:
# if group.uid == current_group_id:
# return group
# else:
# return None
@property
def all_zones(self):
""" Return a set of all the available zones"""
self._parse_zone_group_state()
return self._all_zones
@property
def visible_zones(self):
""" Return an set of all visible zones"""
self._parse_zone_group_state()
return self._visible_zones
def partymode(self):
""" Put all the speakers in the network in the same group, a.k.a Party
Mode.
This blog shows the initial research responsible for this:
http://blog.travelmarx.com/2010/06/exploring-sonos-via-upnp.html
The trick seems to be (only tested on a two-speaker setup) to tell each
speaker which to join. There's probably a bit more to it if multiple
groups have been defined.
"""
# Tell every other visible zone to join this one
# pylint: disable = expression-not-assigned
[zone.join(self) for zone in self.visible_zones if zone is not self]
def join(self, master):
""" Join this speaker to another "master" speaker.
.. note:: The signature of this method has changed in 0.8. It now
requires a SoCo instance to be passed as `master`, not an IP
address
"""
self.avTransport.SetAVTransportURI([
('InstanceID', 0),
('CurrentURI', 'x-rincon:{0}'.format(master.uid)),
('CurrentURIMetaData', '')
])
def unjoin(self):
""" Remove this speaker from a group.
Seems to work ok even if you remove what was previously the group
master from it's own group. If the speaker was not in a group also
returns ok.
Returns:
True if this speaker has left the group.
Raises SoCoException (or a subclass) upon errors.
"""
self.avTransport.BecomeCoordinatorOfStandaloneGroup([
('InstanceID', 0)
])
def switch_to_line_in(self):
""" Switch the speaker's input to line-in.
Returns:
True if the Sonos speaker successfully switched to line-in.
If an error occurs, we'll attempt to parse the error and return a UPnP
error code. If that fails, the raw response sent back from the Sonos
speaker will be returned.
Raises SoCoException (or a subclass) upon errors.
"""
self.avTransport.SetAVTransportURI([
('InstanceID', 0),
('CurrentURI', 'x-rincon-stream:{0}'.format(self.uid)),
('CurrentURIMetaData', '')
])
@property
def is_playing_radio(self):
""" Is the speaker playing radio?
return True or False
"""
response = self.avTransport.GetPositionInfo([
('InstanceID', 0),
('Channel', 'Master')
])
track_uri = response['TrackURI']
return re.match(r'^x-rincon-mp3radio:', track_uri) is not None
@property
def is_playing_line_in(self):
""" Is the speaker playing line-in?
return True or False
"""
response = self.avTransport.GetPositionInfo([
('InstanceID', 0),
('Channel', 'Master')
])
track_uri = response['TrackURI']
return re.match(r'^x-rincon-stream:', track_uri) is not None
@property
def is_playing_tv(self):
""" Is the playbar speaker input from TV?
return True or False
"""
response = self.avTransport.GetPositionInfo([
('InstanceID', 0),
('Channel', 'Master')
])
track_uri = response['TrackURI']
return re.match(r'^x-sonos-htastream:', track_uri) is not None
def switch_to_tv(self):
""" Switch the playbar speaker's input to TV.
Returns:
True if the Sonos speaker successfully switched to TV.
If an error occurs, we'll attempt to parse the error and return a UPnP
error code. If that fails, the raw response sent back from the Sonos
speaker will be returned.
Raises SoCoException (or a subclass) upon errors.
"""
self.avTransport.SetAVTransportURI([
('InstanceID', 0),
('CurrentURI', 'x-sonos-htastream:{0}:spdif'.format(self.uid)),
('CurrentURIMetaData', '')
])
@property
def status_light(self):
""" The white Sonos status light between the mute button and the volume
up button on the speaker. True if on, otherwise False.
"""
result = self.deviceProperties.GetLEDState()
LEDState = result["CurrentLEDState"] # pylint: disable=invalid-name
return True if LEDState == "On" else False
@status_light.setter
def status_light(self, led_on):
""" Switch on/off the speaker's status light """
led_state = 'On' if led_on else 'Off'
self.deviceProperties.SetLEDState([
('DesiredLEDState', led_state),
])
def _build_album_art_full_uri(self, url):
""" Ensure an Album Art URI is an absolute URI
:param url: The album art URI
"""
# Add on the full album art link, as the URI version
# does not include the ipaddress
if not url.startswith(('http:', 'https:')):
url = 'http://' + self.ip_address + ':1400' + url
return url
def get_current_track_info(self):
""" Get information about the currently playing track.