-
Notifications
You must be signed in to change notification settings - Fork 34
/
soco.py
executable file
·1147 lines (830 loc) · 49.1 KB
/
soco.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 -*-
""" SoCo (Sonos Controller) is a simple library to control Sonos speakers """
# Will be parsed by setup.py to determine package metadata
__author__ = 'Rahim Sonawalla <[email protected]>'
__version__ = '0.5'
__website__ = 'https://github.com/rahims/SoCo'
__license__ = 'MIT License'
import xml.etree.cElementTree as XML
import requests
import select
import socket
import logging, traceback
logger = logging.getLogger(__name__)
__all__ = ['SonosDiscovery', 'SoCo']
class SonosDiscovery(object):
"""A simple class for discovering Sonos speakers.
Public functions:
get_speaker_ips -- Get a list of IPs of all zoneplayers.
"""
def __init__(self):
self._sock = socket.socket(
socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self._sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
def get_speaker_ips(self):
speakers = []
self._sock.sendto(PLAYER_SEARCH, (MCAST_GRP, MCAST_PORT))
while True:
rs, _, _ = select.select([self._sock], [], [], 1)
if rs:
_, addr = self._sock.recvfrom(2048)
speakers.append(addr[0])
else:
break
return speakers
class SoCo(object):
"""A simple class for controlling a Sonos speaker.
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.
mute -- Get or Set Mute (or unmute) the speaker.
volume -- Get or set the volume of the speaker.
bass -- Get or set the speaker's bass EQ.
set_player_name -- set the name of the Sonos Speaker
treble -- Set the speaker's treble EQ.
set_play_mode -- Change repeat and shuffle settings on the queue.
set_loudness -- Turn on (or off) the speaker's loudness compensation.
switch_to_line_in -- Switch the speaker's input to line-in.
status_light -- Turn on (or off) the Sonos status light.
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_current_transport_info -- get speakers playing state
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.
"""
speakers_ip = [] # Stores the IP addresses of all the speakers in a network
def __init__(self, speaker_ip):
self.speaker_ip = speaker_ip
self.speaker_info = {} # Stores information about the current speaker
def set_player_name(self,playername=False):
""" Sets the name of the player
Returns:
True if the player name was successfully set.
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.
"""
if playername is not False:
body = SET_PLAYER_NAME_BODY_TEMPLATE.format(playername=playername)
response = self.__send_command(DEVICE_ENDPOINT,SET_PLAYER_NAME_ACTION,body)
if (response == SET_PLAYER_NAME_RESPONSE):
return True
else:
return self.__parse_error(response)
def set_play_mode(self, playmode):
""" Sets the play mode for the queue. 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.
Returns:
True if the play mode was successfully set.
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.
"""
modes = ('NORMAL','SHUFFLE_NOREPEAT','SHUFFLE','REPEAT_ALL')
playmode = playmode.upper()
if not playmode in modes: raise KeyError, "invalid play mode"
action = '"urn:schemas-upnp-org:service:AVTransport:1#SetPlayMode"'
body = '<u:SetPlayMode xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"><InstanceID>0</InstanceID><NewPlayMode>'+playmode+'</NewPlayMode></u:SetPlayMode>'
response = self.__send_command(TRANSPORT_ENDPOINT, action, body)
if "errorCode" in response:
return self.__parse_error(response)
else:
return True
def play_from_queue(self, queue_index):
""" Play an item from the queue. The track number is required as an
argument, where the first track is 0.
Returns:
True if the Sonos speaker successfully started playing the track.
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.
"""
# 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.speaker_info['uid'])
body = PLAY_FROM_QUEUE_BODY_TEMPLATE.format(uri=uri)
response = self.__send_command(TRANSPORT_ENDPOINT, SET_TRANSPORT_ACTION, body)
if not (response == PLAY_FROM_QUEUE_RESPONSE):
return self.__parse_error(response)
# second, set the track number with a seek command
body = SEEK_TRACK_BODY_TEMPLATE.format(track=queue_index+1)
response = self.__send_command(TRANSPORT_ENDPOINT, SEEK_ACTION, body)
if "errorCode" in response:
return self.__parse_error(response)
# finally, just play what's set
return self.play()
def play(self):
"""Play the currently selected track.
Returns:
True if the Sonos speaker successfully started playing the track.
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.
"""
response = self.__send_command(TRANSPORT_ENDPOINT, PLAY_ACTION, PLAY_BODY)
if (response == PLAY_RESPONSE):
return True
else:
return self.__parse_error(response)
def play_uri(self, uri='', meta=''):
""" Play a given stream. Pauses the queue.
Arguments:
uri -- URI of a stream to be played.
meta --- The track metadata to show in the player, DIDL format.
Returns:
True if the Sonos speaker successfully started playing the track.
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.
"""
body = PLAY_URI_BODY_TEMPLATE.format(uri=uri, meta=meta)
response = self.__send_command(TRANSPORT_ENDPOINT, SET_TRANSPORT_ACTION, body)
if (response == ENQUEUE_RESPONSE):
# The track is enqueued, now play it.
return self.play()
else:
return self.__parse_error(response)
def pause(self):
""" Pause the currently playing track.
Returns:
True if the Sonos speaker successfully paused the track.
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.
"""
response = self.__send_command(TRANSPORT_ENDPOINT, PAUSE_ACTION, PAUSE_BODY)
if (response == PAUSE_RESPONSE):
return True
else:
return self.__parse_error(response)
def stop(self):
""" Stop the currently playing track.
Returns:
True if the Sonos speaker successfully stopped the playing track.
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.
"""
response = self.__send_command(TRANSPORT_ENDPOINT, STOP_ACTION, STOP_BODY)
if (response == STOP_RESPONSE):
return True
else:
return self.__parse_error(response)
def seek(self, timestamp):
""" Seeks to a given timestamp in the current track, specified in the
format of HH:MM:SS.
Returns:
True if the Sonos speaker successfully seeked to the timecode.
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.
"""
import re
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"
body = SEEK_TIMESTAMP_BODY_TEMPLATE.format(timestamp=timestamp)
response = self.__send_command(TRANSPORT_ENDPOINT, SEEK_ACTION, body)
if "errorCode" in response:
return self.__parse_error(response)
else:
return True
def next(self):
""" Go to the next track.
Returns:
True if the Sonos speaker successfully skipped to the next track.
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. 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).
"""
response = self.__send_command(TRANSPORT_ENDPOINT, NEXT_ACTION, NEXT_BODY)
if (response == NEXT_RESPONSE):
return True
else:
return self.__parse_error(response)
def previous(self):
""" Go back to the previously played track.
Returns:
True if the Sonos speaker successfully went to the previous track.
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. 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.
"""
response = self.__send_command(TRANSPORT_ENDPOINT, PREV_ACTION, PREV_BODY)
if (response == PREV_RESPONSE):
return True
else:
return self.__parse_error(response)
def mute(self, mute=None):
""" Mute or unmute the Sonos speaker.
Arguments:
mute -- True to mute. False to unmute.
Returns:
True if the Sonos speaker was successfully muted or unmuted.
If the mute argument was not specified: returns the current mute status
0 for unmuted, 1 for muted
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.
"""
if mute is None:
response = self.__send_command(RENDERING_ENDPOINT, GET_MUTE_ACTION, GET_MUTE_BODY)
dom = XML.fromstring(response)
muteState = dom.findtext('.//CurrentMute')
return int(muteState)
else:
mute_value = '1' if mute else '0'
body = MUTE_BODY_TEMPLATE.format(mute=mute_value)
response = self.__send_command(RENDERING_ENDPOINT, MUTE_ACTION, body)
if (response == MUTE_RESPONSE):
return True
else:
return self.parse(response)
def volume(self, volume=None):
""" Get or set the Sonos speaker volume.
Arguments:
volume -- A value between 0 and 100.
Returns:
If the volume argument was specified: returns true if the Sonos speaker
successfully set the volume.
If the volume argument was not specified: returns the current volume of
the Sonos speaker.
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.
"""
if volume is not None:
volume = max(0, min(volume, 100)) # Coerce in range
body = SET_VOLUME_BODY_TEMPLATE.format(volume=volume)
response = self.__send_command(RENDERING_ENDPOINT, SET_VOLUME_ACTION, body)
if (response == SET_VOLUME_RESPONSE):
return True
else:
return self.__parse_error(response)
else:
response = self.__send_command(RENDERING_ENDPOINT, GET_VOLUME_ACTION, GET_VOLUME_BODY)
dom = XML.fromstring(response)
volume = dom.findtext('.//CurrentVolume')
return int(volume)
def bass(self, bass=None):
""" Get or set the Sonos speaker's bass EQ.
Arguments:
bass -- A value between -10 and 10.
Returns:
If the bass argument was specified: returns true if the Sonos speaker
successfully set the bass EQ.
If the bass argument was not specified: returns the current base value.
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.
"""
if bass is not None:
bass = max(-10, min(bass, 10)) # Coerce in range
body = SET_BASS_BODY_TEMPLATE.format(bass=bass)
response = self.__send_command(RENDERING_ENDPOINT, SET_BASS_ACTION, body)
if (response == SET_BASS_RESPONSE):
return True
else:
return self.__parse_error(response)
else:
response = self.__send_command(RENDERING_ENDPOINT, GET_BASS_ACTION, GET_BASS_BODY)
dom = XML.fromstring(response)
bass = dom.findtext('.//CurrentBass')
return int(bass)
def treble(self, treble=None):
""" Get or set the Sonos speaker's treble EQ.
Arguments:
treble -- A value between -10 and 10.
Returns:
If the treble argument was specified: returns true if the Sonos speaker
successfully set the treble EQ.
If the treble argument was not specified: returns the current treble value.
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.
"""
if treble is not None:
treble = max(-10, min(treble, 10)) # Coerce in range
body = SET_TREBLE_BODY_TEMPLATE.format(treble=treble)
response = self.__send_command(RENDERING_ENDPOINT, SET_TREBLE_ACTION, body)
if (response == SET_TREBLE_RESPONSE):
return True
else:
return self.__parse_error(response)
else:
response = self.__send_command(RENDERING_ENDPOINT, GET_TREBLE_ACTION, GET_TREBLE_BODY)
dom = XML.fromstring(response)
treble = dom.findtext('.//CurrentTreble')
return int(treble)
def set_loudness(self, loudness):
""" Set the Sonos speaker's loudness compensation.
Loudness is a complicated topic. You can find a nice summary about this
feature here: http://forums.sonos.com/showthread.php?p=4698#post4698
Arguments:
loudness -- True to turn on loudness compensation. False to disable it.
Returns:
True if the Sonos speaker successfully set the loundess compensation.
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.
"""
loudness_value = '1' if loudness else '0'
body = SET_LOUDNESS_BODY_TEMPLATE.format(loudness=loudness_value)
response = self.__send_command(RENDERING_ENDPOINT, SET_LOUDNESS_ACTION, body)
if (response == SET_LOUDNESS_RESPONSE):
return True
else:
return self.__parse_error(response)
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://travelmarx.blogspot.dk/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.
Code contributed by Thomas Bartvig ([email protected])
Returns:
True if partymode is set
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.
"""
master_speaker_info = self.get_speaker_info()
ips = self.get_speakers_ip()
rc = True
# loop through all IP's in topology and make them join this master
for ip in ips:
if not (ip == self.speaker_ip):
slave = SoCo(ip)
ret = slave.join(master_speaker_info["uid"])
if ret is False:
rc = False
return rc
def join(self, master_uid):
""" Join this speaker to another "master" speaker.
Code contributed by Thomas Bartvig ([email protected])
Returns:
True if this speaker has joined the master speaker
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.
"""
body = JOIN_BODY_TEMPLATE.format(master_uid=master_uid)
response = self.__send_command(TRANSPORT_ENDPOINT, SET_TRANSPORT_ACTION, body)
if (response == JOIN_RESPONSE):
return True
else:
return self.__parse_error(response)
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.
"""
response = self.__send_command(TRANSPORT_ENDPOINT, UNJOIN_ACTION, UNJOIN_BODY)
if (response == UNJOIN_RESPONSE):
return True
else:
return self.__parse_error(response)
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. Note, an error will be returned if you try
to switch to line-in on a device (like the Play:3) that doesn't have
line-in capability.
"""
speaker_info = self.get_speaker_info()
body = SET_LINEIN_BODY_TEMPLATE.format(speaker_uid=speaker_info['uid'])
response = self.__send_command(TRANSPORT_ENDPOINT, SET_TRANSPORT_ACTION, body)
if (response == SET_LINEIN_RESPONSE):
return True
else:
return self.__parse_error(response)
def status_light(self, led_on):
""" Turn on (or off) the white Sonos status light.
Turns on or off the little white light on the Sonos speaker. (It's
between the mute button and the volume up button on the speaker.)
Arguments:
led_on -- True to turn on the light. False to turn off the light.
Returns:
True if the Sonos speaker successfully turned on (or off) the light.
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.
"""
led_state = 'On' if led_on else 'Off'
body = SET_LEDSTATE_BODY_TEMPLATE.format(state=led_state)
response = self.__send_command(DEVICE_ENDPOINT, SET_LEDSTATE_ACTION, body)
if (response == SET_LEDSTATE_RESPONSE):
return True
else:
return self.parse(response)
def get_current_track_info(self):
""" Get information about the currently playing track.
Returns:
A dictionary containing the following information about the currently
playing track: playlist_position, duration, title, artist, album,
position and a link to the album art.
If we're unable to return data for a field, we'll return an empty
string. This can happen for all kinds of reasons so be sure to check
values. For example, a track may not have complete metadata and be
missing an album name. In this case track['album'] will be an empty string.
"""
response = self.__send_command(TRANSPORT_ENDPOINT, GET_CUR_TRACK_ACTION, GET_CUR_TRACK_BODY)
dom = XML.fromstring(response.encode('utf-8'))
track = {'title': '', 'artist': '', 'album': '', 'album_art': '',
'position': ''}
track['playlist_position'] = dom.findtext('.//Track')
track['duration'] = dom.findtext('.//TrackDuration')
track['uri'] = dom.findtext('.//TrackURI')
track['position'] = dom.findtext('.//RelTime')
d = dom.findtext('.//TrackMetaData')
# Duration seems to be '0:00:00' when listening to radio
if d != '' and track['duration'] == '0:00:00':
metadata = XML.fromstring(d.encode('utf-8'))
#Try parse trackinfo
trackinfo = metadata.findtext('.//{urn:schemas-rinconnetworks-com:metadata-1-0/}streamContent')
index = trackinfo.find(' - ')
if index > -1:
track['artist'] = trackinfo[:index]
track['title'] = trackinfo[index+3:]
else:
logger.warning('Could not handle track info: "%s"', trackinfo)
logger.warning(traceback.format_exc())
track['title'] = trackinfo.encode('utf-8')
# If the speaker is playing from the line-in source, querying for track
# metadata will return "NOT_IMPLEMENTED".
elif d != '' and d != 'NOT_IMPLEMENTED':
# Track metadata is returned in DIDL-Lite format
metadata = XML.fromstring(d.encode('utf-8'))
md_title = metadata.findtext('.//{http://purl.org/dc/elements/1.1/}title')
md_artist = metadata.findtext('.//{http://purl.org/dc/elements/1.1/}creator')
md_album = metadata.findtext('.//{urn:schemas-upnp-org:metadata-1-0/upnp/}album')
track['title'] = ""
if (md_title):
track['title'] = md_title.encode('utf-8')
track['artist'] = ""
if (md_artist):
track['artist'] = md_artist.encode('utf-8')
track['album'] = ""
if (md_album):
track['album'] = md_album.encode('utf-8')
album_art = metadata.findtext('.//{urn:schemas-upnp-org:metadata-1-0/upnp/}albumArtURI')
if album_art is not None:
track['album_art'] = 'http://' + self.speaker_ip + ':1400' + metadata.findtext('.//{urn:schemas-upnp-org:metadata-1-0/upnp/}albumArtURI')
return track
def get_speaker_info(self, refresh=False):
""" Get information about the Sonos speaker.
Arguments:
refresh -- Refresh the speaker info cache.
Returns:
Information about the Sonos speaker, such as the UID, MAC Address, and
Zone Name.
"""
if self.speaker_info and refresh is False:
return self.speaker_info
else:
response = requests.get('http://' + self.speaker_ip + ':1400/status/zp')
dom = XML.fromstring(response.content)
self.speaker_info['zone_name'] = dom.findtext('.//ZoneName').encode('utf-8')
self.speaker_info['zone_icon'] = dom.findtext('.//ZoneIcon')
self.speaker_info['uid'] = dom.findtext('.//LocalUID')
self.speaker_info['serial_number'] = dom.findtext('.//SerialNumber')
self.speaker_info['software_version'] = dom.findtext('.//SoftwareVersion')
self.speaker_info['hardware_version'] = dom.findtext('.//HardwareVersion')
self.speaker_info['mac_address'] = dom.findtext('.//MACAddress')
return self.speaker_info
def get_speakers_ip(self, refresh=False):
""" Get the IP addresses of all the Sonos speakers in the network.
Code contributed by Thomas Bartvig ([email protected])
Arguments:
refresh -- Refresh the speakers IP cache.
Returns:
IP addresses of the Sonos speakers.
"""
import re
if self.speakers_ip and not refresh:
return self.speakers_ip
else:
response = requests.get('http://' + self.speaker_ip + ':1400/status/topology')
text = response.text
grp = re.findall(r'(\d+\.\d+\.\d+\.\d+):1400', text)
for i in grp:
response = requests.get('http://' + i + ':1400/status')
if response.status_code == 200:
self.speakers_ip.append(i)
return self.speakers_ip
def get_current_transport_info(self):
""" Get the current playback state
Returns:
A dictionary containing the following information about the speakers playing state
current_transport_state (PLAYING, PAUSED_PLAYBACK, STOPPED),
current_trasnport_status (OK, ?), current_speed(1,?)
This allows us to know if speaker is playing or not. Don't know other states of
CurrentTransportStatus and CurrentSpeed.
"""
response = self.__send_command(TRANSPORT_ENDPOINT, GET_CUR_TRANSPORT_ACTION, GET_CUR_TRANSPORT_BODY)
dom = XML.fromstring(response.encode('utf-8'))
playstate = {
'current_transport_status': '',
'current_transport_state': '',
'current_transport_speed': ''
}
playstate['current_transport_state'] = dom.findtext('.//CurrentTransportState')
playstate['current_transport_status'] = dom.findtext('.//CurrentTransportStatus')
playstate['current_transport_speed'] = dom.findtext('.//CurrentSpeed')
return playstate
def get_queue(self, start = 0, max_items = 100):
""" Get information about the queue.
Returns:
A list containing a dictionary for each track in the queue. The track dictionary
contains the following information about the track: title, artist, album, album_art, uri
If we're unable to return data for a field, we'll return an empty
list. This can happen for all kinds of reasons so be sure to check
values.
This method is heavly based on Sam Soffes (aka soffes) ruby implementation
"""
queue = []
body = GET_QUEUE_BODY_TEMPLATE.format(start, max_items)
response = self.__send_command(CONTENT_DIRECTORY_ENDPOINT, BROWSE_ACTION, body)
try:
dom = XML.fromstring(response.encode('utf-8'))
resultText = dom.findtext('.//Result')
if not resultText: return queue
resultDom = XML.fromstring(resultText.encode('utf-8'))
for element in resultDom.findall('.//{urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/}item'):
try:
item = {
'title': None,
'artist': None,
'album': None,
'album_art': None,
'uri': None
}
item['title'] = element.findtext('{http://purl.org/dc/elements/1.1/}title')
item['artist'] = element.findtext('{http://purl.org/dc/elements/1.1/}creator')
item['album'] = element.findtext('{urn:schemas-upnp-org:metadata-1-0/upnp/}album')
item['album_art'] = element.findtext('{urn:schemas-upnp-org:metadata-1-0/upnp/}albumArtURI')
item['uri'] = element.findtext('{urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/}res')
queue.append(item)
except:
logger.warning('Could not handle item: %s', element)
logger.error(traceback.format_exc())
except:
logger.error('Could not handle result from Sonos')
logger.error(traceback.format_exc())
return queue
def add_to_queue(self, uri):
""" Adds a given track to the queue.
Returns:
If the Sonos speaker successfully added the track, returns the queue
position of the track added.
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.
"""
body = ADD_TO_QUEUE_BODY_TEMPLATE.format(uri=uri)
response = self.__send_command(TRANSPORT_ENDPOINT, ADD_TO_QUEUE_ACTION, body)
if "errorCode" in response:
return self.__parse_error(response)
else:
dom = XML.fromstring(response)
qnumber = dom.findtext('.//FirstTrackNumberEnqueued')
return int(qnumber)
def remove_from_queue(self, index):
""" Removes a track from the queue.
index: the index of the track to remove; first item in the queue is 1
Returns:
True if the Sonos speaker successfully removed the track
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.
"""
#TODO: what do these parameters actually do?
instance = updid = '0'
objid = 'Q:0/'+str(index)
body = REMOVE_FROM_QUEUE_BODY_TEMPLATE.format(instance=instance, objid=objid, updateid=updid)
response = self.__send_command(TRANSPORT_ENDPOINT, REMOVE_FROM_QUEUE_ACTION, body)
if "errorCode" in response:
return self.__parse_error(response)
else:
return True
def clear_queue(self):
""" Removes all tracks from the queue.
Returns:
True if the Sonos speaker cleared the queue.
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.
"""
response = self.__send_command(TRANSPORT_ENDPOINT, CLEAR_QUEUE_ACTION, CLEAR_QUEUE_BODY)
if "errorCode" in response:
return self.__parse_error(response)
else:
return True
def get_favorite_radio_shows(self, start=0, max_items=100):
""" Get favorite radio shows from Sonos' Radio app.
Returns:
A list containing the total number of favorites, the number of favorites
returned, and the actual list of favorite radio shows, represented as a
dictionary with `title` and `uri` keys.
Depending on what you're building, you'll want to check to see if the
total number of favorites is greater than the amount you
requested (`max_items`), if it is, use `start` to page through and
get the entire list of favorites.
"""
return self.__get_radio_favorites(RADIO_SHOWS, start, max_items)
def get_favorite_radio_stations(self, start=0, max_items=100):
""" Get favorite radio stations from Sonos' Radio app.
Returns:
A list containing the total number of favorites, the number of favorites
returned, and the actual list of favorite radio stations, represented
as a dictionary with `title` and `uri` keys.
Depending on what you're building, you'll want to check to see if the
total number of favorites is greater than the amount you
requested (`max_items`), if it is, use `start` to page through and
get the entire list of favorites.
"""
return self.__get_radio_favorites(RADIO_STATIONS, start, max_items)
def __get_radio_favorites(self, favorite_type, start=0, max_items=100):
""" Helper method for `get_favorite_radio_*` methods.
Arguments:
favorite_type -- Specify either `RADIO_STATIONS` or `RADIO_SHOWS`.
start -- Which number to start the retrieval from. Used for paging.
max_items -- The total number of results to return.
"""
if favorite_type != RADIO_SHOWS or RADIO_STATIONS:
favorite_type = RADIO_STATIONS
body = GET_RADIO_FAVORITES_BODY_TEMPLATE.format(favorite_type, start, max_items)
response = self.__send_command(CONTENT_DIRECTORY_ENDPOINT, BROWSE_ACTION, body)
dom = XML.fromstring(response.encode('utf-8'))
result = {}
favorites = []
d = dom.findtext('.//Result')
if d != '':
# Favorites are returned in DIDL-Lite format
metadata = XML.fromstring(d.encode('utf-8'))
for item in metadata.findall('.//{urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/}item'):
favorite = {}
favorite['title'] = item.findtext('.//{http://purl.org/dc/elements/1.1/}title').encode('utf-8')
favorite['uri'] = item.findtext('.//{urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/}res')
favorites.append(favorite)
result['total'] = dom.findtext('.//TotalMatches', 0)
result['returned'] = len(favorites)
result['favorites'] = favorites
return result
def __send_command(self, endpoint, action, body):
""" Send a raw command to the Sonos speaker.
Returns:
The raw response body returned by the Sonos speaker.
"""
headers = {
'Content-Type': 'text/xml',
'SOAPACTION': action
}
soap = SOAP_TEMPLATE.format(body=body)
r = requests.post('http://' + self.speaker_ip + ':1400' + endpoint, data=soap, headers=headers)
return r.content
def __parse_error(self, response):
""" Parse an error returned from the Sonos speaker.
Returns:
The UPnP error code returned by the Sonos speaker.
If we're unable to parse the error response for whatever reason, the
raw response sent back from the Sonos speaker will be returned.
"""
error = XML.fromstring(response)