-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path__init__.py
3623 lines (3294 loc) · 164 KB
/
__init__.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 -*-
#
# This file is part of EventGhost.
# Copyright (C) 2014-2020 Chase Whitten <[email protected]>
#
# No Code here on out within this file may be used accept with EventGhost.
# Permission by myself (Chase Whitten) must be granted by me to use this code
# or part of this code in any other program.
#
######################################## Register ############################################
eg.RegisterPlugin(
name = "Sonos",
author = "Chase Whitten (Techoguy)",
version = "0.9.5 beta", #changes to the albumarturl, added trigger for this
kind = "program",
canMultiLoad = False,
description = "This plugin allows you to control your SONOS zone players. This works with grouped zones or stereo pairs. This plugin will search your network for Zone Players during startup, and if any SONOS ZP is added or removed from the network the plugin will automatically update itself. Each ZP is unique based on the MAC address. This means even if the name of a ZP is changed it won't affect your actions. If you have to replace a ZP, then all actions that use that ZP will have to be updated. Many more comands will be added soon.",
createMacrosOnAdd = True
#createMacrosOnAdd = False
)
###################################### Import ###############################################
import eg
from xml.dom.minidom import parse, parseString
import httplib, urllib
import wx.lib
#from socket import *
import time
import asyncore, socket
from xml.dom.minidom import parse, parseString
import os
import linecache # for PrintException()
import sys # for PrintException()
if os.name != "nt":
import fcntl
import struct
#for debugging and knowing which functions called another
import inspect
###################################### Globals ###############################################
globalZPList = {} #dict to store ZP objects.
globalServiceList = {} #dict to store service/subscription objects
globalDebug = 0
globalRestartScheduler = None
albumartloc = "C:\\SONOS_Covers\\" #make sure to include dual \\ and include it at the end.
############# Manually add IP address below ##############
# this plugin is designed to support PCs with only one active network card
# So to guarantee the right IP address is selected when you have multiple network cards
# enter it below.
# Note that this PC should have a static address if an address is entered below.
# To allow dynamic ip address in which the plugin gets the IP address automatically,
# leave it blank ("")
localip = ""
##########################################################
'''Known models:
S1 = Sonos PLAY:1
S3 = Sonos PLAY:3
S5 = Sonos PLAY:5
S9 = Sonos PLAYBAR
Sub = Sonos SUB
ZP120 = Sonos CONNECT:AMP
ZP90 = Sonos CONNECT
'''
#list of ZPs that support Line In
LINEINMODELS = [
'ZP90', 'ZP120', 'S5'
]
#list of ZPs that support TV inputs
TVINMODELS = [
'S9'
]
#weather conditions
CONDITIONCODES = {
'0':'tornado',
'1':'tropical storm',
'2':'hurricane',
'3':'severe thunderstorms',
'4':'thunderstorms',
'5':'mixed rain and snow',
'6':'mixed rain and sleet',
'7':'mixed snow and sleet',
'8':'freezing drizzle',
'9':'drizzle',
'10':'freezing rain',
'11':'showers',
'12':'showers',
'13':'snow flurries',
'14':'light snow showers',
'15':'blowing snow',
'16':'snow',
'17':'hail',
'18':'sleet',
'19':'dust',
'20':'foggy',
'21':'haze',
'22':'smoky',
'23':'blustery',
'24':'windy',
'25':'cold',
'26':'cloudy',
'27':'mostly cloudy at night',
'28':'mostly cloudy during the day',
'29':'partly cloudy at night',
'30':'partly cloudy during the day',
'31':'clear at night',
'32':'sunny',
'33':'fair at night',
'34':'fair day',
'35':'mixed rain and hail',
'36':'hot',
'37':'isolated thunderstorms',
'38':'scattered thunderstorms',
'39':'scattered thunderstorms',
'40':'scattered showers',
'41':'heavy snow',
'42':'scattered snow showers',
'43':'heavy snow',
'44':'partly cloudy',
'45':'thundershowers',
'46':'snow showers',
'47':'isolated thundershowers',
'3200':'not available'
}
###################################### Functions #############################################
### example of calling the speech plugin: eg.plugins.Speech.TextToSpeech(u'Microsoft Hazel Desktop - English (Great Britain)', 1, u'Today is a beutiful day. the temperature is 87 degrees outside at {TIME} ', 0, 100)
def PrintException():
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
#filename = f.f_code.co_filename
#linecache.checkcache(filename)
#line = linecache.getline(filename, lineno, f.f_globals)
#print 'EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj)
print 'EXCEPTION AT LINE: %s = %s' % (lineno, exc_obj)
trigger = 'EXCEPTION AT LINE: '+str(lineno)+" = "+str(exc_obj)
eg.TriggerEvent("ERROR", prefix='SONOS', payload=trigger)
def get_interface_ip(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
ifname[:15]))[20:24])
def get_lan_ip():
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith("127.") and os.name != "nt":
interfaces = [
"eth0",
"eth1",
"eth2",
"wlan0",
"wlan1",
"wifi0",
"ath0",
"ath1",
"ppp0",
]
for ifname in interfaces:
try:
ip = get_interface_ip(ifname)
break
except IOError:
pass
return ip
def HtmlSplit(data=""):
header = {}
header['body'] = ""
headerstring = data.split("\r\n\r\n")[0]
try:
header['body'] = data.split("\r\n\r\n")[1]
except:
pass
headerlist = headerstring.split("\r\n")
try:
header['status-type'] = headerlist[0].split(" ",2)[0]
header['status-code'] = headerlist[0].split(" ",2)[1]
header['status'] = headerlist[0].split(" ",2)[2]
headerlist = headerlist[1:]
except:
header['status-type'] = "Unknown"
header['status-code'] = "NA"
header['status'] = "Response Error, Status Code not found (HtmlSplit)"
trigger = "Response Error, Status Code not found (HtmlSplit)"
eg.TriggerEvent("ERROR", prefix='SONOS', payload=trigger)
for s in headerlist:
variable = s.split(":",1)[0] #.lower() #some text is upper case and other is not, so this will force it to be lower in case it changes or is different for different devices.
try:
value = s.split(":",1)[1].strip() #remove white space, there is usually a space after :
except:
value = ""
header[variable] = value
return header
class AsyncRequesting(asyncore.dispatcher):
def __init__(self, HOSTzp, PORTzp, data, callback):
self.HOSTzp = HOSTzp
self.PORTzp = PORTzp
self.data = data
self.contentLength = 0
self.connectionClose = ''
self.callback = callback
self.portused = 0
self.buffer = ""
self.start_connection()
def RestartSonosAsyncore(self):
if globalDebug >= 2:
print "====== Restarting Asyncore Now ====================="
eg.RestartAsyncore()
def start_connection(self):
global globalRestartScheduler
self.connectionMade = "NO"
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
# it appears that if you call eg.RestartAsyncore() to close together, it causes all
# kinds of problems with the asyncore and sockets. To fix this, eg.RestartAsyncore() is
# only called once 0.1 seconds has passed without any other new sockets created.
try:
self.renewCallBack = eg.scheduler.CancelTask(globalRestartScheduler)
except:
pass
globalRestartScheduler = eg.scheduler.AddTask(.4, self.RestartSonosAsyncore)
#eg.RestartAsyncore()
try:
self.connect((self.HOSTzp, self.PORTzp))
self.portused = self.getsockname()[1]
except socket.error, e:
print "Connection to %s on port %s failed: %s" % (self.HOSTzp, self.PORTzp, e)
trigger = "Connection to "+str(self.HOSTzp)+" on port "+str(self.PORTzp)+" failed: "+str(e)
eg.TriggerEvent("ERROR", prefix='SONOS', payload=trigger)
self.buffer = self.data
def handle_connect(self):
if globalDebug >= 2:
print "%s handle_connect" % self.portused
self.connectionMade = "CONNECTED"
pass
def handle_close(self):
if globalDebug >= 2:
print str(self.portused) + " -- CLOSED handle_close, State: %s" % self.connectionMade
if self.connectionMade == "CONNECTED": #connection made but then closed, so retry.
self.close() #close current socket,
#if globalDebug >= 1:
print "%s socket closed before reading, RETRYING connection" % self.portused
self.start_connection() #retry sending.
elif self.connectionMade == "READ":
if globalDebug >= 1:
print "%s -- handle_close state:, %s" % (self.portused,self.connectionMade)
self.close()
else: #everything else and "NO"
if globalDebug >= 1:
print "No response from %s:%s" % (self.HOSTzp, self.PORTzp)
self.close()
data = "No Response from %s:%s" % (self.HOSTzp, self.PORTzp)
response = {'body':"",'ERROR':data}
self.callback(response)
def chunk_decode(self, data):
tempString = "".join(data.split('\r\n')[1::2])
tempString = tempString.replace("\n","")
try:
tempString = tempString.replace("\t"," ")
except:
pass
return tempString
def handle_read(self):
if globalDebug >= 2:
print "%s handle_read" % self.portused
self.connectionMade = "READ"
data = self.recv(1024)
if globalDebug >= 2:
print "%s-handle_read" % (self.portused)
if globalDebug >= 2:
print "%s-Data:\r\n%s------End Of Data------" % (self.portused, data)
try:
self.response #if it doesn't exist, it's the first read
#continues if this is the second read
if globalDebug >= 2:
print "--2+ chunked byte received"
if data != '':
self.response['body'] = self.response['body'] + data
#if self.contentLength <= len(self.response['body']):
# if self.connectionClose == 'close':
# if globalDebug >= 1:
# print "%s length met 2+ socket closing" % self.portused
# self.close()
# self.callback(self.response)
if self.transferEncoding == "":
if self.contentLength <= len(self.response['body']):
if self.connectionClose == 'close':
if globalDebug >= 2:
print "%s length met 2+ socket closing" % self.portused
self.close()
self.callback(self.response)
else:#handle chunk encoding
if self.response['body'][-4:]=="\r\n\r\n":
if self.connectionClose == 'close':
if globalDebug >= 2:
print "%s chunk 2+ socket closing" % self.portused
self.close()
self.response['body'] = self.chunk_decode(self.response['body'])
self.callback(self.response)
else: # data empty before content length reached
print "%s Response ERROR: Connection closed before reaching content length or end" % self.portused
print "%s Current-Length:%s SB: %s \n%s" % (self.portused,len(self.response['body']), self.contentLength, self.response)
self.callback(self.response)
except AttributeError: #if first read
self.response = HtmlSplit(data)
if data != '':
'''need to look for Transfer-Encoding: chunked first, and
create a new function that will read all data and decode it'''
try:
self.transferEncoding = self.response['Transfer-Encoding'] #=============================
except:
try:
self.transferEncoding = self.response['TRANSFER-ENCODING'] #=============================
except:
self.transferEncoding = ""
try:
self.contentLength = int(self.response['Content-Length']) #=============================
except:
try:
self.contentLength = int(self.response['CONTENT-LENGTH'])
except:
self.contentLength = 0
try:
self.connectionClose = self.response['Connection']
except:
try:
self.connectionClose = self.response['CONNECTION']
except:
self.connectionClose = ''
if self.transferEncoding == "":
if self.contentLength <= len(self.response['body']):
if self.connectionClose == 'close':
if globalDebug >= 2:
print "%s length met 1 socket closing" % self.portused
self.close()
self.callback(self.response)
else:#handle chunk encoding
if self.response['body'][-4:]=="\r\n\r\n":
if self.connectionClose == 'close':
if globalDebug >= 2:
print "%s chunk 1 socket closing" % self.portused
self.close()
self.response['body'] = self.chunk_decode(self.response['body'])
self.callback(self.response)
else:
if globalDebug >= 1:
print "%s ---- Response empty ----- " % self.portused
self.callback(self.response)
'''might need to have "except" here to handle all other exceptions for the sockets errors. '''
def writable(self):
try:
if globalDebug >= 99:
print "%s writable len:%s" % (self.portused,len(self.buffer))
#this is actually called sometimes before the next lines of self.connect((self.HOSTzp, self.PORTzp))
# which means portused and buffer might not be assigned yet.
return (len(self.buffer) > 0)
except:
print "%s writable no buffer" % self.portused
return False
def handle_write(self):
if globalDebug >= 2:
print "%s handle_write" % self.portused
try:
sent = self.send(self.buffer)
except:
sent = self.send(self.buffer.encode("utf-8"))
'''might need another try/except here to handle the send if not available right now'''
self.buffer = self.buffer[sent:]
def handle_expt(self):
errorText = "handle_expt : %s:%s" % (self.HOSTzp, self.PORTzp)
eg.TriggerEvent("ERROR", prefix='SONOS', payload=errorText)
try:
self.close()
except:
pass
trigger = "ERROR, handle_expt: "+str(self.HOSTzp)+":"+str(self.PORTzp)
eg.TriggerEvent("ERROR", prefix='SONOS', payload=trigger)
raise Exception("ERROR, handle_expt: %s:%s" % (self.HOSTzp, self.PORTzp))
def handle_error(self):
errorText = "handle_error : %s:%s" % (self.HOSTzp, self.PORTzp)
eg.TriggerEvent("ERROR", prefix='SONOS', payload=errorText)
try:
self.close()
except:
pass
PrintException()
trigger = "ERROR, handle_error: "+str(self.HOSTzp)+":"+str(self.PORTzp)
eg.TriggerEvent("ERROR", prefix='SONOS', payload=trigger)
raise Exception("ERROR, handle_error: %s:%s" % (self.HOSTzp, self.PORTzp))
def handle_connect_expt(self,expt):
errorText = "connection error: %s \r\n..... %s:%s" % (expt,self.HOSTzp, self.PORTzp)
eg.TriggerEvent("ERROR", prefix='SONOS', payload=errorText)
try:
self.close()
except:
pass
trigger = "ERROR, handle_connect_expt: "+str(self.HOSTzp)+":"+str(self.PORTzp)
eg.TriggerEvent("ERROR", prefix='SONOS', payload=trigger)
raise Exception("ERROR, handle_connect_expt: %s:%s" % (self.HOSTzp, self.PORTzp))
class Service():
def __init__(self, zp, url, EventCallBack, eventport):
self.zp = zp
self.url = url
self.EventCallBack = EventCallBack
self.eventport = eventport
self.subsTimeout = 3600
self.Subscribe()
def ServiceErrorHandler(self, data):
if "ERROR" in data.keys():
if data['ERROR'].find("No Response") >= 0:
self.UnsubResponse(data)
del globalZPList[self.zp.uuid] #delete zp from list
#trigger eg event....
if globalDebug >= 1:
print "\n\ndeleted ZP from List: %s" % self.zp.uuid
trigger = "%s.%s" % ("DELETED", self.zp.uuid)
eg.TriggerEvent(trigger, prefix='SONOS', payload=self.zp.ip)
trigger = "%s-%s" % (self.zp.ip, self.zp.uuid)
eg.TriggerEvent("ZonePlayerDeleted", prefix='SONOS', payload=trigger)
if globalDebug >= 1:
print "\n\n"
if self.url.find("ZoneGroupTopology")>0: #if true, subscribe to a different ZP.
try:
uuid = globalZPList.keys()[0] #select random ZP to get grouptopology from
tempservice = Service(globalZPList[uuid], "/ZoneGroupTopology/Event", ZoneGroupTopologyEvent)
except:#if there are no more ZPs, through error
trigger = "ERROR: Can't connect to SONOS Zone Players"
eg.TriggerEvent("ERROR", prefix='SONOS', payload=trigger)
raise Exception(trigger)
else: #unhandled error
trigger = data['ERROR']
eg.TriggerEvent("ERROR", prefix='SONOS', payload=trigger)
raise Exception(data['ERROR'])
return data
def RenewResponse(self, data):
#might not need.
#store timeout
#schedule, renew function call
#remember to store this so it can be cancelled later.
if globalDebug >= 1:
print "renew Response received..."
pass
def Renew(self):
if globalDebug >= 1:
print "sending renew request...."
port = 1400
data = "SUBSCRIBE " + self.url + " HTTP/1.1\r\nSID: " + self.SID + "\r\nTIMEOUT: Second-"+str(self.subsTimeout)+"\r\nHOST: "+self.zp.ip+":"+str(port)+"\r\nContent-Length: 0\r\n\r\n"
#self.renrequest = AsyncRequesting(self.zp.ip, port, data, self.RenewResponse)
self.subrequest = AsyncRequesting(self.zp.ip, port, data, self.SubResponse)
#restart loop to include the new socket object
# this is needed because this is created after the first call to RestartAsyncore
#eg.RestartAsyncore() #removed
if globalDebug >= 1:
print "%s requesting renew: %s - %s" % (self.subrequest.portused, globalZPList[self.zp.uuid].name, self.url.split("/")[-2])
#eg.RestartAsyncore()
def UnsubResponse(self, data):
# Unsubscribe response
# check to make sure 200 OK is recieved
# trigger eg event....
#HTTP/1.1 200 OK
#Server: Linux UPnP/1.0 Sonos/24.0-71060 (ZP120)
#Connection: close
global globalServiceList
global globalZPList
if globalDebug >= 2:
print "%s Unsubscribed response %s - %s" % (self.unsubrequest.portused, globalZPList[self.zp.uuid].name, self.url.split("/")[-2])
del globalServiceList[self.SID]
globalZPList[self.zp.uuid].services[self.url.split("/")[-2]] = ""
if globalDebug >= 2:
print "UnsubResponse Data: %s" % data
try:
self.unsubrequest.close()
except Exception, e:
print " Service Unsubscribe Response Error: %s" % e
trigger = "Service Unsubscribe Response Error: "+str(e)
eg.TriggerEvent("ERROR", prefix='SONOS', payload=trigger)
PrintException()
def Unsubscribe(self):
#cancel the scheduled task for the renew
#send cancel request
if globalDebug >= 2:
print "sending unsubscribe request to %s" % (self.zp.ip)
try:
eg.scheduler.CancelTask(self.renewCallBack) # cancel renew callback
except Exception, e:
if globalDebug >= 2:
print "can't Cancel Task renewCallBack in Unsubscribed %s" % str(e)
pass
try:
self.renrequest.close()
except Exception, e:
pass
try:
self.subrequest.close()
except Exception, e:
pass
try:
self.unsubrequest.close()
except Exception, e:
pass
port = 1400
data = "UNSUBSCRIBE " + self.url + " HTTP/1.1\r\nUSER-AGENT: Linux UPnP/1.0 Sonos/24.0-69180m (WDCR:Microsoft Windows NT 6.2.9200.0)\r\nHOST: "+self.zp.ip+":"+str(port)+"\r\nSID: " + self.SID + "\r\n\r\n"
if globalDebug >= 2:
print "sending unsubscribe request: %s - %s" % (globalZPList[self.zp.uuid].name, self.url.split("/")[-2])
self.unsubrequest = AsyncRequesting(self.zp.ip, port, data, self.UnsubResponse)
def SubResponse(self, data):
global globalServiceList
global globalZPList
#print "subscribe response: %s - %s" % (globalZPList[self.zp.uuid].name, self.url.split("/")[-2])
try:
response = self.ServiceErrorHandler(data)
try:
eg.scheduler.CancelTask(self.renewCallBack)#restart if needed.
except:
pass
self.subsTimeout = int(response['TIMEOUT'].split("-")[1]) #ex: TIMEOUT: Seconds-3200
if globalDebug >= 2:
print response['SID']
self.SID = response['SID']
globalServiceList[self.SID] = self # store service object in global dict
# store SID info in ZP object
globalZPList[self.zp.uuid].services[self.url.split("/")[-2]] = self.SID
if globalZPList[self.zp.uuid].name == "":
globalZPList[self.zp.uuid].name = self.zp.ip
if globalDebug >= 2:
print "Subscribed to %s on %s" % (self.url.split("/")[-2],globalZPList[self.zp.uuid].name)
if globalDebug >= 2:
print "%s subscribed response %s - %s" % (self.subrequest.portused, globalZPList[self.zp.uuid].name, self.url.split("/")[-2])
self.renewCallBack = eg.scheduler.AddTask(self.subsTimeout/2, self.Renew)
except Exception, e:
print " Service Subscribe Response Error: %s" % e
trigger = "Service Subscribe Response Error: "+str(e)
eg.TriggerEvent("ERROR", prefix='SONOS', payload=trigger)
PrintException()
def Subscribe(self):
global globalZPList
port = 1400
data = "SUBSCRIBE " + self.url + " HTTP/1.1\r\nNT: upnp:event\r\nTIMEOUT: Second-"+str(self.subsTimeout)+"\r\nHOST: "+self.zp.ip+":"+str(port)+"\r\nCALLBACK: <http://" + localip + ":" + str(self.eventport) + "/events>\r\nContent-Length: 0\r\n\r\n"
self.subrequest = AsyncRequesting(self.zp.ip, port, data, self.SubResponse)
if globalZPList[self.zp.uuid].name == "":
globalZPList[self.zp.uuid].name = self.zp.ip
if globalDebug >= 2:
print "%s sending subscribe request: %s - %s" % (self.subrequest.portused, globalZPList[self.zp.uuid].name, self.url.split("/")[-2])
def Event(self, data):
#define how the event response is handled, unique for each service
self.EventCallBack(self.zp.uuid, data)
def RenderingControlEvent(uuid, data):
global globalZPList
try:
#print "AVTransportEvent received from %s" % globalZPList[uuid].name
xml = parseString(data)
xmlLastChange = xml.getElementsByTagName('LastChange')[0].firstChild.nodeValue
xml = parseString(xmlLastChange.encode('utf-8'))
if globalDebug >= 2:
print xml.toxml()
try:
globalZPList[uuid].volume
except:
globalZPList[uuid].volume = "-"
#try:
if True:
#loop through all volume nodes to find Master node
for volume in xml.getElementsByTagName('Volume'):
if volume.attributes['channel'].value=="Master": #if master channel, save current volume
vol = volume.attributes['val'].value
if globalZPList[uuid].volume != vol: #if volume has changed, trigger event and save.
trigger = "%s.%s" % (uuid, "Volume")
vol = "vol-%s %s" % (vol, globalZPList[uuid].name)
eg.TriggerEvent(trigger, prefix='SONOS', payload=vol)
globalZPList[uuid].volume = volume.attributes['val'].value
#except:
# pass
try:
globalZPList[uuid].mute
except:
globalZPList[uuid].mute = "-"
try:
#loop through all mute nodes to find Master node
for mute in xml.getElementsByTagName('Mute'):
if mute.attributes['channel'].value=="Master": #if master channel, save current mute
vol = mute.attributes['val'].value
if globalZPList[uuid].mute != vol: #if mute has changed, trigger event and save.
trigger = "%s.%s" % (uuid, "Mute")
vol = "mute-%s %s" % (vol, globalZPList[uuid].name)
eg.TriggerEvent(trigger, prefix='SONOS', payload=vol)
globalZPList[uuid].mute = mute.attributes['val'].value
except:
pass
try:
globalZPList[uuid].outputFixed = xml.getElementsByTagName('OutputFixed').attributes['val'].value
except:
pass
try:
globalZPList[uuid].headphoneConnected = xml.getElementsByTagName('HeadphoneConnected').attributes['val'].value
except:
pass
except Exception, e:
print "RenderingControlEvent XML error: %s" % e
trigger = "RenderingControlEvent XML error: "+str(e)
eg.TriggerEvent("ERROR", prefix='SONOS', payload=trigger)
def UpdateTransportStates(uuid, transportstate):
#updated all Zone Players within a group.
for key in globalZPList:
if not globalZPList[key].invisible:
if globalZPList[key].coordinator == uuid:
globalZPList[key].TransportState(transportstate)
'''
Need to clean this up and have it match the getmediainfo and getpositioninfo
need to create event for when stream source changes
need to create event when track/metadata is updated
'''
def UpdateTrackTitle(uuid, title, artist="", source="", albumarturl=""): #added 2/3/2016
#updated all Zone Players within a group.
for key in globalZPList:
if not globalZPList[key].invisible:
if globalZPList[key].coordinator == uuid:
if globalZPList[key].title != title:
trigger = "%s.Title" % (key)
payload = "%s:%s" % (globalZPList[key].name,title)
eg.TriggerEvent(trigger, prefix='SONOS', payload=payload)
globalZPList[key].title = title
trigger = "%s.Artist" % (key)
payload = "%s:%s" % (globalZPList[key].name,artist)
eg.TriggerEvent(trigger, prefix='SONOS', payload=payload)
globalZPList[key].artist = artist
trigger = "%s.Source" % (key)
payload = "%s:%s" % (globalZPList[key].name,source)
eg.TriggerEvent(trigger, prefix='SONOS', payload=payload)
globalZPList[key].source = source
if globalZPList[key].albumarturl != albumarturl:
trigger = "%s.AlbumArtWorkURL" % (key)
payload = "%s:%s" % (globalZPList[key].name,albumarturl)
eg.TriggerEvent(trigger, prefix='SONOS', payload=payload)
globalZPList[key].albumarturl = albumarturl
'''
Need to get the medi source like spotify, pandora, etc.
Maybe I can add a call to this as well when a ZP starts to play to update this?
'''
def AVTransportEvent(uuid, data):
global globalZPList
title = "unknown title"
artist = "unknown artist"
source = "unknown source"
albumarturl = ""
try:
#print "AVTransportEvent received from %s" % globalZPList[uuid].name
xml = parseString(data)
xmlLastChange = xml.getElementsByTagName('LastChange')[0].firstChild.nodeValue
xml = parseString(xmlLastChange.encode('utf-8'))
if globalDebug >= 2:
print xml.toxml()
try:
transportstate = xml.getElementsByTagName("TransportState")[0].attributes['val'].value
#check to see if avTransportURI exists, if it doesn't update transportstate (only occurs when first starting)
if globalDebug >= 1:
print "%s Received ZP Transport State: %s" % (globalZPList[uuid].name,transportstate)
except:
pass
try:
globalZPList[uuid].avTransportURI
except:
globalZPList[uuid].avTransportURI = ""
try: #sleeptimer triggers this event with no transportstate info
UpdateTransportStates(uuid, transportstate)
except:
pass
try:
newAVTransportURI = xml.getElementsByTagName("AVTransportURI")[0].attributes['val'].value
globalZPList[uuid].avTransportURI = newAVTransportURI
except Exception, e:
#if AVTransportURI is present, this means the stream is updating so transportstate 'STOPPED' should be ignored.
try:
UpdateTransportStates(uuid, transportstate)
except:
pass
try:
globalZPList[uuid].currentPlayMode = xml.getElementsByTagName("CurrentPlayMode")[0].attributes['val'].value
if globalDebug >= 1:
print "%s currentPlayMode: %s" % (globalZPList[uuid].name, globalZPList[uuid].currentPlayMode)
except:
pass
try:
globalZPList[uuid].playbackStorageMedium = xml.getElementsByTagName("PlaybackStorageMedium")[0].attributes['val'].value
if globalDebug >= 1:
print "%s playbackStorageMedium: %s" % (globalZPList[uuid].name, globalZPList[uuid].playbackStorageMedium)
except:
pass
#AVTransportURIMetaData (streaming station info)
try:
avtransportURIMetaData = xml.getElementsByTagName("AVTransportURIMetaData")[0].attributes['val'].value
if avtransportURIMetaData == "":
if globalDebug >= 1:
print "%s avtransportURIMetaData: <empty>" % globalZPList[uuid].name
else:
tempxml = parseString(avtransportURIMetaData)
#print "------- %s AVTransport URI Meta Data -------------" % (globalZPList[uuid].name) #2/3/2016
#print tempxml.toxml() #2/3/2016
source = tempxml.getElementsByTagName("dc:title")[0].firstChild.nodeValue
if globalDebug >= 1:
print "%s Stream Title: %s" % (globalZPList[uuid].name, source)
except Exception, e:
if globalDebug >= 2:
print "failed %s" % str(e)
#CurrentTrackMetaData information (sub xml)
try:
currenttrackmetadata = xml.getElementsByTagName("CurrentTrackMetaData")[0].attributes['val'].value
tempxml = parseString(currenttrackmetadata.encode('utf-8'))
tempxml = parseString(currenttrackmetadata.encode('utf-8'))
#print "------- %s Current track meta Data -------------" % (globalZPList[uuid].name) #2/3/2016
#print tempxml.toxml()
#get and save album cover jpg
albumartlink = tempxml.getElementsByTagName("upnp:albumArtURI")[0].firstChild.nodeValue
albumarturl = "http://" + globalZPList[uuid].ip + ":1400" + albumartlink #2/3/2016
if globalDebug >= 2:
print "album cover URL: %s" % albumarturl
pass
#picfileloc = albumartloc + uuid + ".jpg" #2/3/2016 uncomment to save cover art to the albumartloc
#urllib.urlretrieve(albumarturl, picfileloc) #2/3/2016 uncomment to save cover art to the albumartloc
#to get high resolution pics:
#http://www.albumartexchange.com/covers.php?sort=7&q=Scary+Monsters+and+Nice&fltr=2&bgc=&page=&sng=1
#this returns: html, which has a <a href="/gallery/images/public/..." taht has the picture.
#if it can't find anything it response with "There are no images to display."
except Exception, e:
if globalDebug >= 2:
print "failed %s" % str(e)
pass
try:
title = tempxml.getElementsByTagName("dc:title")[0].firstChild.nodeValue
if globalDebug >= 1:
print "Track: " + title
except:
pass
try:
artist = tempxml.getElementsByTagName("dc:creator")[0].firstChild.nodeValue
if globalDebug >= 1:
print "Artist: " + artist
except:
pass
try:
album = tempxml.getElementsByTagName("upnp:album")[0].firstChild.nodeValue
if globalDebug >= 1:
print "Album: " + album
#high resolution artwork search based on alum name:
album = album.replace(" ","+")
#print "http://www.albumartexchange.com/covers.php?sort=7&q=" + album + "&fltr=2&bgc=&page=&sng=1"
except:
pass
#trigger EG events
UpdateTrackTitle(uuid, title, artist, source, albumarturl) #add 2/3/2016
except Exception, e:
print "AVTransportEvent XML error: %s" % e
trigger = "AVTransportEvent XML error: "+str(e)
eg.TriggerEvent("ERROR", prefix='SONOS', payload=trigger)
'''
need to add an event when group topology changes
how to handle name/ip changes vs actual grouping changes?
need to look at zonegrouptopology for ZPs that are added and removed.
currently the plugin knows when they are removed when the event renewal times out due
to no response from the removed ZP. Adding a new ZP should work below but it seems when
a ZP is disconnected this isn't happening. As example, ZP was removed, commands
said that the device had been rmoved as expected but when it was re-added the device
was not re-added.
Also, if a device can be seen to be removed from grouptopology then it'll work faster.
The problem here to look out ofr is that during group changes sometimes the
grouptopology doesn't have all the ZPs listed.
'''
def ZoneGroupTopologyEvent(uuid, data):
global globalZPList
try:
#print data
xml = parseString(data)
#find ZoneGroupState, ignore any other event
#if "ZoneGroupState" in xml.childNodes
try:
xmlstring = xml.getElementsByTagName('ZoneGroupState')[0].firstChild.nodeValue
except:
if globalDebug >= 1:
print "ZoneGroupTopologyEvent: Property is not ZoneGroupState, ignoring..."
return
#print xmlstring
xml = parseString(xmlstring.encode('utf-8'))
grouplist = xml.getElementsByTagName('ZoneGroup')
#print grouplist
#loop through group info and update zpList
zpInfo = {} #temp.
subscribeList = []
unsubscribeList = []
for zg in grouplist:
#print zg.attributes['Coordinator'].value
coordinator = zg.attributes['Coordinator'].value
#to find ZPs that are in the Satellites configurations with PlayBar:
try:
zplist = zg.getElementsByTagName('Satellite')
for zp in zplist:
attrlist = dict(zp.attributes.items())
uuid = attrlist['UUID']
#add ZP to dict if new
ip = attrlist['Location'].split("/")[2].split(":")[0]
xmllocation = attrlist['Location']
if uuid not in globalZPList:
globalZPList[uuid] = ZonePlayer(uuid, ip, xmllocation)
#globalZPList[uuid].uuid = uuid
globalZPList[uuid].ip = ip
globalZPList[uuid].name = attrlist['ZoneName']
globalZPList[uuid].isZoneBridge = '0'
globalZPList[uuid].coordinator = coordinator
globalZPList[uuid].invisible = 1
if globalDebug >= 1:
print '{0: <27}'.format(uuid) + '{0: <17}'.format(ip) + attrlist['ZoneName']
except:
pass
zplist = zg.getElementsByTagName('ZoneGroupMember')
for zp in zplist:
attrlist = dict(zp.attributes.items())
uuid = attrlist['UUID']
#add ZP to dict if new
ip = attrlist['Location'].split("/")[2].split(":")[0]
xmllocation = attrlist['Location']
if uuid not in globalZPList:
globalZPList[uuid] = ZonePlayer(uuid, ip, xmllocation)
#globalZPList[uuid].uuid = uuid
globalZPList[uuid].ip = ip
globalZPList[uuid].name = attrlist['ZoneName']
try:
globalZPList[uuid].isZoneBridge = attrlist['IsZoneBridge']
except:
globalZPList[uuid].isZoneBridge = '0'
#check to see if the coordinator is changing,
#if coordinator changing, update transportstate for ZP to state.
if globalZPList[uuid].coordinator != coordinator:
if globalDebug >= 1:
print "%s coordinator changed to %s" % (globalZPList[uuid].name,globalZPList[coordinator].name)
if coordinator == uuid:
globalZPList[uuid].TransportState("PAUSED_PLAYBACK")
elif globalZPList[coordinator].transportState == "Playing":
globalZPList[uuid].TransportState("PLAYING")
else:
globalZPList[uuid].TransportState("PAUSED_PLAYBACK")
globalZPList[uuid].coordinator = coordinator
#subscribe to AVTransport (all that are coordinators)
if coordinator == uuid: #if true, ZP is coordinator
stringflagco = " :coordinator -%s-" % globalZPList[uuid].services["AVTransport"]
if globalZPList[uuid].services["AVTransport"] == "": # no SID
if globalDebug >= 2:
print " Subscribing to %s" % globalZPList[uuid].name
subscribeList.append(uuid)
else:
pass
if globalDebug >= 2:
print " AVTransport already subscribed to %s" % globalZPList[uuid].name
else:
stringflagco = " -%s-" % globalZPList[uuid].services["AVTransport"]
if not globalZPList[uuid].services["AVTransport"] == "": #SID present
unsubscribeList.append(uuid)
if globalDebug >= 2:
print " Unsubscribing to %s" % globalZPList[uuid].name
#globalServiceList[globalZPList[uuid].services["AVTransport"]].Unsubscribe()
else:
if globalDebug >= 2:
print " AVTransport already unsubscribed to %s" % globalZPList[uuid].name
if "Invisible" in attrlist:
globalZPList[uuid].invisible = 1
if globalDebug >= 1:
print '{0: <27}'.format(uuid) + '{0: <17}'.format(ip) + attrlist['ZoneName'] + " (Invisible)" + stringflagco
else:
globalZPList[uuid].invisible = 0
if globalDebug >= 1:
print '{0: <27}'.format(uuid) + '{0: <17}'.format(ip) + attrlist['ZoneName'] + stringflagco
for zp in subscribeList:
if not globalZPList[zp].isZoneBridge == '1':
if globalDebug >= 1:
print "Subscribing to AVTransportEvent on %s" % globalZPList[zp].name
#globalZPList[zp].services["AVTransport"] = "testing"
tempservice = Service(globalZPList[zp], "/MediaRenderer/AVTransport/Event", AVTransportEvent, serverPort)
for zp in unsubscribeList:
if globalDebug >= 1:
print "Unsubscribing to AVTransportEvent on%s" % globalZPList[zp].name
#globalZPList[zp].services["AVTransport"] = ""
globalServiceList[globalZPList[zp].services["AVTransport"]].Unsubscribe()
#subscribe to RenderingControl (Volume) only if it's not invisible
for zp, zpobject in globalZPList.iteritems():
if zpobject.invisible:
#if subscribed, unsubscribe
if not zpobject.services["RenderingControl"] == "":
globalServiceList[zpobject.services["RenderingControl"]].Unsubscribe()
else:#if unsubscriebed, subscribe
if zpobject.services["RenderingControl"] == "":
tempservice = Service(globalZPList[zp], "/MediaRenderer/RenderingControl/Event", RenderingControlEvent, serverPort)
except Exception, e:
print "ZoneGroupTopologyEvent XML error: %s" % e
trigger = "ZoneGroupTopologyEvent XML error: "+str(e)+"\n\n"+data
eg.TriggerEvent("ERROR", prefix='SONOS', payload=trigger)
if globalDebug >= 1:
print "----- ZoneGroupTopology Data Response -------\n%s\n\n" % data
class EventChannel(asyncore.dispatcher):
contentlength = 0
eventdata = ""
def handle_write(self):
if globalDebug >= 2:
print "--- Event Handle_Write ---"
#pass
def handle_close(self):
if globalDebug >= 2:
print "--- Event Handle_Close ---"
#pass
def handle_read(self):
if globalDebug >= 2:
print "--- Event Handle_Read ---"
data = self.recv(8192)
try:
if self.contentlength == 0:
self.eventdata = HtmlSplit(data)
self.contentlength = int(self.eventdata['CONTENT-LENGTH']) #CONTENT-LENGTH
if self.eventdata['NT'] != 'upnp:event': #NT #check to make sure it's an event
trigger = "ERROR, expected to receive event"
eg.TriggerEvent("ERROR", prefix='SONOS', payload=trigger)
raise Exception("ERROR, expected to receive event")
else:
self.eventdata['body'] = self.eventdata['body'] + data
if self.contentlength <= len(self.eventdata['body']):
self.send('HTTP/1.1 200 OK\r\nContent-Length: 0')
if globalDebug >= 1:
print "--- Event Handle_Read self.close ---"
self.close()
if globalDebug >= 2:
print self.eventdata['body']
SID = self.eventdata['SID'] #SID
if SID in globalServiceList:
servicename = globalServiceList[SID].url.split("/")[-2]
zpevent = globalZPList[globalServiceList[SID].zp.uuid].name
if globalDebug >= 1:
print "--- EVENT Received --- %s from %s" % (servicename, zpevent)
globalServiceList[SID].Event(self.eventdata['body'])
self.contentlength = 0
self.eventdata = ""
except Exception, e:
if globalDebug >= 2:
print "--- Event Handle_Read except self.close ---"
self.close()
errorText = "event receive error: %s - %s" % (Exception, e)
eg.TriggerEvent("ERROR", prefix='SONOS', payload=errorText)
print errorText
#self.send('HTTP/1.1 500 Internal Server ERROR\r\nContent-Length: 0')
def handle_expt(self):
errorText = "EventChannel handle_expt : %s:%s" % (self.HOSTzp, self.PORTzp)