-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.py
749 lines (605 loc) · 30.9 KB
/
plugin.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
#
# Title : Jacks Internet Radio
# Author: Jack Veraart
# Date : 2021-04-15
#
# Changelog :
#
# version 3.0.0 : Changed for new Domoticz API
# version 2.0.0 : Added Room
# version 1.0.0 : Initial version
#
"""
<plugin key="JacksInternetRadio" name="Jacks Internet Radio" author="Jack Veraart" version="3.0.0">
<description>
<font size="4" color="white">Internet Radio</font><font color="white">...Notes...</font>
<ul style="list-style-type:square">
<li><font color="yellow">Requirements:</font></li>
<li><font color="yellow"> - Install audio player mplayer : sudo apt install mplayer -y </font></li>
<li><font color="yellow">Preconfigured radio is available in plugin folder in internetradio.conf</font></li>
<li><font color="yellow">Add Admin account details below so I can import icons and create a room.</font></li>
<li><font color="yellow">To develop your own plugin...check this web site... <a href="https://www.domoticz.com/wiki/Developing_a_Python_plugin" ><font color="cyan">Developing_a_Python_plugin</font></a></font></li>
</ul>
</description>
<params>
<param field="Username" label="Username." width="120px" default="Username"/>
<param field="Password" label="Password." width="120px" default="Password" password="true"/>
<param field="Mode6" label="Debug." width="75px">
<options>
<option label="True" value="Debug"/>
<option label="False" value="Normal" default="true"/>
</options>
</param>
</params>
</plugin>
"""
import Domoticz
# Prepare some global variables
StartupOK=0
LocalHostInfo=''
HeartbeatInterval= 5 # 5 seconds
HomeFolder='' # plugin finds right value
DeviceLibrary={}
class BasePlugin:
enabled = False
def __init__(self):
#self.var = 123
return
# --------------------------------------------------------------------------------------------------------------------------------------------------------
def onStart(self):
import os
global StartupOK
global HomeFolder
global LocalHostInfo
self.pollinterval = HeartbeatInterval #Time in seconds between two polls
if Parameters["Mode6"] == 'Debug':
self.debug = True
Domoticz.Debugging(1)
DumpConfigToLog()
else:
Domoticz.Debugging(0)
Domoticz.Log("onStart called")
try:
#
# Set some globals variables to right values
#
HomeFolder =str(Parameters["HomeFolder"])
Username =str(Parameters["Username"])
Password =str(Parameters["Password"])
LocalHostInfo = "https://"+Username+":"+Password+"@"+GetDomoticzIP()+":"+GetDomoticzHTTPSPort()
StartupOK = ImportImages()
# Create devices as configured in internetradio.conf
if StartupOK == 1:
StartupOK = CreateDevices()
if StartupOK == 1:
Domoticz.Log('onStartup OK')
Domoticz.Heartbeat(HeartbeatInterval)
else:
Domoticz.Log('ERROR starting up')
except:
StartupOK = 0
Domoticz.Log('ERROR starting up')
# --------------------------------------------------------------------------------------------------------------------------------------------------------
def onStop(self):
Domoticz.Log("onStop called")
player('stop')
def onConnect(self, Connection, Status, Description):
Domoticz.Log("onConnect called")
def onMessage(self, Connection, Data):
Domoticz.Log("onMessage called")
# --------------------------------------------------------------------------------------------------------------------------------------------------------
def onCommand(self, Unit, Command, Level, Hue):
DeviceName=Devices[Unit].Name[8:-9] # remove <center> and </center>
DeviceType=DeviceLibrary[DeviceName]['Type']
# Domoticz.Log("onCommand called >"+str(Unit)+'< >'+DeviceName+'< >'+Command+'< >'+str(Level)+'< >'+DeviceType)
if DeviceType == 'Dimmer': # It is the volume slider
if Command == 'Off':
Level = 0
if Command == 'On':
Level = 25
if Level == '100':
Level = 25
if Devices[Unit].sValue != str(Level):
SoundDevice=player('getdevice')
# Domoticz.Log('SoundDevice: '+SoundDevice)
player('volume',SoundDevice,str(Level))
Devices[Unit].Update( nValue=2, sValue=str(Level))
elif DeviceType == 'StationList': # It is a station list
StationIndex=int(Level/10)-1
StationName=DeviceLibrary[DeviceName]['StationNames'][StationIndex]
if StationName.replace(' ','') != '':
player('stop')
StationURL=DeviceLibrary[DeviceName]['StationURLs'][StationIndex]
SoundDevice=player('getdevice')
Domoticz.Log('Tune into Station: >'+StationName+'< URL >'+StationURL)
player('play' ,SoundDevice,StationURL)
for Device in DeviceLibrary:
if DeviceLibrary[Device]['Type'] == 'Text':
if Devices[DeviceLibrary[Device]['Unit']].sValue != StationName:
message='<h4>'
message=message+'\n'
message=message+'\n'
message=message+ '<center><font color=blue>' + SoundDevice+'</font><font color=white>............</font></center>'
message=message+'\n'
message=message+ '<center><font color=blue>' + DeviceName+'</font><font color=white>............</font></center>'
message=message+'</h4>'
message=message+'\n'
message=message+'<h4>'
message=message+ '<marquee scrollamount="3"><a href="'+StationURL+'"><font color=blue>Station : </font><font color=green>' + StationName+'</font><font color=red> Click me 🔊 </font></a></marquee>'
message=message+'</h4>'
message=message+'\n'
message=message+'<h4>'
message=message+'</h4>'
Devices[DeviceLibrary[Device]['Unit']].Update( nValue=0, sValue=message)
# --------------------------------------------------------------------------------------------------------------------------------------------------------
def onNotification(self, Name, Subject, Text, Status, Priority, Sound, ImageFile):
Domoticz.Log("Notification: " + Name + "," + Subject + "," + Text + "," + Status + "," + str(Priority) + "," + Sound + "," + ImageFile)
def onDisconnect(self, Connection):
Domoticz.Log("onDisconnect called")
# --------------------------------------------------------------------------------------------------------------------------------------------------------
def onHeartbeat(self):
Domoticz.Debug("onHeartbeat called")
#
# This is to copy the volume slider from the host to the plugin so you can control the volume from host and plugin.
#
if StartupOK == 1:
for Device in DeviceLibrary:
if DeviceLibrary[Device]['Type'] == 'Dimmer': # we have one dimmer and this is for the volume
Level=player('getvolume')
Domoticz.Debug('SoundDevice Level: '+str(Level))
onCommand(DeviceLibrary[Device]['Unit'], 'Set Level', Level, 0)
# --------------------------------------------------------------------------------------------------------------------------------------------------------
global _plugin
_plugin = BasePlugin()
def onStart():
global _plugin
_plugin.onStart()
def onStop():
global _plugin
_plugin.onStop()
def onConnect(Connection, Status, Description):
global _plugin
_plugin.onConnect(Connection, Status, Description)
def onMessage(Connection, Data):
global _plugin
_plugin.onMessage(Connection, Data)
def onCommand(Unit, Command, Level, Hue):
global _plugin
_plugin.onCommand(Unit, Command, Level, Hue)
def onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile):
global _plugin
_plugin.onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile)
def onDisconnect(Connection):
global _plugin
_plugin.onDisconnect(Connection)
def onHeartbeat():
global _plugin
_plugin.onHeartbeat()
# Generic helper functions
def DumpConfigToLog():
for x in Parameters:
if Parameters[x] != "":
Domoticz.Debug( "'" + x + "':'" + str(Parameters[x]) + "'")
Domoticz.Debug("Device count: " + str(len(Devices)))
for x in Devices:
Domoticz.Debug("Device: " + str(x) + " - " + str(Devices[x]))
Domoticz.Debug("Device ID: '" + str(Devices[x].ID) + "'")
Domoticz.Debug("Device Name: '" + Devices[x].Name + "'")
Domoticz.Debug("Device nValue: " + str(Devices[x].nValue))
Domoticz.Debug("Device sValue: '" + Devices[x].sValue + "'")
Domoticz.Debug("Device LastLevel: " + str(Devices[x].LastLevel))
return
# --------------------------------------------------------------------------------------------------------------------------------------------------------
# ---------------------------------------------------- Image Management Routines -----------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------------------------------------------------------------
# ---------------------------------------------------- Image Management Routines -----------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------------------------------------------------------------
def GetDomoticzHTTPSPort():
try:
import subprocess
except:
Domoticz.Log("python3 is missing module subprocess")
try:
import time
except:
Domoticz.Log("python3 is missing module time")
try:
Domoticz.Debug('GetDomoticzHTTPSPort check startup file')
pathpart=Parameters['HomeFolder'].split('/')[3]
searchfile = open("/etc/init.d/"+pathpart+".sh", "r")
for line in searchfile:
if ("-sslwww" in line) and (line[0:11]=='DAEMON_ARGS'):
HTTPSPort=str(line.split(' ')[2].split('"')[0])
HTTPSPort = HTTPSPort.replace('\\n','') # remove EOL
searchfile.close()
Domoticz.Debug('GetDomoticzHTTPSPort looked in: '+"/etc/init.d/"+pathpart+".sh"+' and found port: '+HTTPSPort)
except:
Domoticz.Debug('GetDomoticzHTTPSPort check running process')
command='ps -ef | grep domoticz | grep sslwww | grep -v grep | tr -s " "'
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
timeouts=0
result = ''
while timeouts < 10:
p_status = process.wait()
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
HTTPSPort=str(output)
HTTPSPort = HTTPSPort[HTTPSPort.find('-sslwww'):]
HTTPSPort = HTTPSPort[HTTPSPort.find(' ')+1:]
HTTPSPort = HTTPSPort[:HTTPSPort.find(' ')]
HTTPSPort = HTTPSPort.replace('\\n','') # remove EOL
else:
time.sleep(0.2)
timeouts=timeouts+1
Domoticz.Log('GetDomoticzHTTPSPort looked at running process and found port: '+HTTPSPort)
return HTTPSPort
# --------------------------------------------------------------------------------------------------------------------------------------------------------
def GetImageDictionary():
import json
import requests
try:
mydict={}
url=LocalHostInfo+'/json.htm?type=command¶m=custom_light_icons'
response=requests.get(url, verify=False)
data = json.loads(response.text)
for Item in data['result']:
mydict[str(Item['imageSrc'])]=int(Item['idx'])
except:
mydict={}
return mydict
# --------------------------------------------------------------------------------------------------------------------------------------------------------
def ImportImages():
#
# Import ImagesToImport if not already loaded
#
try :
import glob
except:
Domoticz.Log("python3 is missing module glob")
global ImageDictionary
MyStatus=1
ImageDictionary=GetImageDictionary()
if ImageDictionary == {}:
Domoticz.Log("Please modify your setup to have Admin access. (See Hardware setup page of this plugin.)")
MyStatus = 0
else:
for zipfile in glob.glob(HomeFolder+"CustomIcons/*.zip"):
importfile=zipfile.replace(HomeFolder,'')
try:
Domoticz.Image(importfile).Create()
Domoticz.Debug("ImportImages Imported/Updated icons from " + importfile)
except:
MyStatus = 0
Domoticz.Log("ImportImages ERROR can not import icons from " + importfile)
if (MyStatus == 1) :
ImageDictionary=GetImageDictionary()
Domoticz.Debug('ImportImages Oke')
return MyStatus
# --------------------------------------------------------------------------------------------------------------------------------------------------------
def GetDomoticzIP():
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
# --------------------------------------------------------------------------------------------------------------------------------------------------------
# ---------------------------------------------------- Device Creation Routines ------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------------------------------------------------------------
def CreateDevice(deviceunit,devicename,devicetype,devicelogo="",devicedescription="",sAxis="",InitialValue=0.0):
if deviceunit not in Devices:
if ImageDictionary == {}:
firstimage=0
firstimagename='NoImage'
Domoticz.Log("ERROR I can not access the image library. Please modify the hardware setup to have the right Username and Password.")
else:
firstimage=int(str(ImageDictionary.values()).split()[0].split('[')[1][:-1])
firstimagename=str(ImageDictionary.keys()).split()[0].split('[')[1][1:-2]
Domoticz.Debug("First image id: " + str(firstimage) + " name: " + firstimagename)
if firstimage != 0: # we have a dictionary with images and hopefully also the image for devicelogo
try:
deviceoptions={}
deviceoptions['Custom']="1;"+sAxis
Domoticz.Device(Name=devicename, Unit=deviceunit, TypeName=devicetype, Used=1, Image=ImageDictionary[devicelogo], Description=devicedescription).Create()
Devices[deviceunit].Update(nValue=Devices[deviceunit].nValue, sValue=str(InitialValue))
Domoticz.Debug("Created device : " + devicename + " with '"+ devicelogo + "' icon and options "+str(deviceoptions)+' Value '+str(InitialValue))
except:
# when devicelogo does not exist, use the first image found, (TypeName values Text and maybe some others will use standard images for that TypeName.)
try:
Domoticz.Device(Name=devicename, Unit=deviceunit, TypeName=devicetype, Used=1, Image=firstimage, Description=devicedescription).Create()
Devices[deviceunit].Update(nValue=Devices[deviceunit].nValue, sValue=str(InitialValue))
Domoticz.Debug("Created device : " + devicename+ " with '"+ firstimagename + "' icon and Value "+str(InitialValue))
except:
Domoticz.Log("ERROR Could not create device : " + devicename)
#
# Devices are created with as prefix the name of the Hardware device as you named it during adding your hardware
# The next replaces that prefix, also after every restart so names are fixed
#
try:
# Note that deviceoptions needs to be a python dictionary so first create a dictionary and fill it with 1 entry
deviceoptions={}
deviceoptions['Custom']="1;"+sAxis
NewName = '<center>'+devicename+'</center>'
Devices[deviceunit].Update(nValue=Devices[deviceunit].nValue, sValue=Devices[deviceunit].sValue, Name=NewName, Options=deviceoptions, Description=devicedescription)
except:
dummy=1
# -----------------------------# --------------------------------------------------------------------------------------------------------------------------------------------------------
def CreateSelectorSwitch(deviceunit,devicename,devicebuttons,devicelogo="",devicedescription="",SelectorStyle=0):
#
# Create a selector switch devicebuttons format : button1|.....|buttonx
#
if deviceunit not in Devices:
firstLevelName=devicebuttons.split('|')[0]
Domoticz.Debug('First Level: '+firstLevelName)
if (SelectorStyle == 0):
Options = {'LevelActions': '|'*(devicebuttons.count('|')+1),
'LevelNames': firstLevelName+'|'+devicebuttons,
'LevelOffHidden': 'true',
'SelectorStyle': '0'}
else:
Options = {'LevelActions': '|'*(devicebuttons.count('|')+1),
'LevelNames': firstLevelName+'|'+devicebuttons,
'LevelOffHidden': 'true',
'SelectorStyle': '1'}
try:
Domoticz.Device(Name=devicename, Unit=deviceunit, TypeName="Selector Switch", Switchtype=18, Image=ImageDictionary[devicelogo], Options=Options, Used=1,Description=devicedescription).Create()
Domoticz.Debug("Created device : " + devicename + " with '"+ devicelogo + "' icon and options "+str(Options))
except:
Domoticz.Log("ERROR Could not create selector switch : " + devicename)
#
# Devices are created with as prefix the name of the Hardware device as you named it during adding your hardware
# The next replaces that prefix, also after every restart so names are fixed
#
try:
# NewName = LocationCode+devicename
NewName = '<center>'+devicename+'</center>'
index=int(Devices[deviceunit].nValue/10)-1
firstLevelName=devicebuttons.split('|')[index]
# Domoticz.Log('...'+devicebuttons+'...'+str(index)+'...'+firstLevelName)
if (SelectorStyle == 0):
Options = {'LevelActions': '|'*(devicebuttons.count('|')+1),
'LevelNames': firstLevelName+'|'+devicebuttons,
'LevelOffHidden': 'true',
'SelectorStyle': '0'}
else:
Options = {'LevelActions': '|'*(devicebuttons.count('|')+1),
'LevelNames': firstLevelName+'|'+devicebuttons,
'LevelOffHidden': 'true',
'SelectorStyle': '1'}
Domoticz.Debug('Update settings for: '+NewName)
if NewName != Devices[deviceunit].Name or Options != Devices[deviceunit].Options :
Devices[deviceunit].Update(nValue=Devices[deviceunit].nValue, sValue=Devices[deviceunit].sValue, Name=NewName,Options=Options,Description=devicedescription)
# the next forces the right logo to be set after startup
UpdateSelectorSwitch(deviceunit,Devices[deviceunit].nValue)
except:
dummy=1
#---------------------------------------------------------------------------------------------------------------------------
def CreateDevices():
global DeviceLibrary
DeviceLibrary={}
Name=''
Type=''
Units=''
Command=''
MyStatus=1
ConfigFile='internetradio.conf'
try:
TheConfigFile=open(HomeFolder+ConfigFile, "r")
TheConfigFile.close
for Line in TheConfigFile:
linea=Line
if Line[0] not in ['#', ' ', '\t', '\n' ] and Line.replace(' ','').replace('\t','') != '\n': # skip comments and empty lines
Line=Line.replace('\n','') # remove EOL
if Line.split('=')[0] == 'Description':
DeviceEntry={}
Description = Line.split('=')[1]
DeviceEntry['Description'] = Description
DeviceEntry['Unit'] = -1
StationCounter=0
StationLabels=''
StationNames=[]
StationURLs=[]
elif Line.split('=')[0] == 'Name':
Name = Line.split('=',1)[1]
DeviceEntry['Name'] = Name
elif Line.split('=')[0] == 'Type':
TypeName = Line.split('=')[1]
DeviceEntry['Type'] = TypeName
elif Line.split('=')[0] == 'Units':
Units = Line.split('=')[1]
DeviceEntry['Units'] = Units
elif Line.split('=')[0] == 'Station':
StationLabel = Line.split('=',1)[1]
StationLabel = StationLabel.split(';')[0]
StationName=StationLabel
StationURL = Line.split('=',1)[1]
StationURL = StationURL.split(';')[1]
StationLabels=StationLabels+'|'+StationLabel
StationNames.append(StationName)
StationURLs.append(StationURL)
StationCounter = StationCounter + 1
Domoticz.Debug('Stations: '+str(StationCounter)+' '+StationLabels)
Domoticz.Debug('URLs: '+str(StationCounter)+' '+str(StationURLs))
elif Line.split('=')[0] == 'Image':
Image = Line.split('=')[1]
DeviceEntry['Image'] = Image
DeviceEntry['StationLabels'] = StationLabels[1:]
DeviceEntry['StationNames'] = StationNames
DeviceEntry['StationURLs'] = StationURLs
DeviceEntry['StationCounter'] = StationCounter
DeviceLibrary[Name] = DeviceEntry
Domoticz.Debug(str(DeviceEntry))
else:
Domoticz.Debug('Error Line: '+Line)
MyStatus=-1
Domoticz.Debug(str(DeviceLibrary))
except:
MyStatus=-1
Domoticz.Log('Error opening config file: '+HomeFolder+ConfigFile)
if MyStatus == 1:
#
# Delete all my devices
#
DeleteOne=1
while DeleteOne == 1: # My implementation of repeat until, make sure to get into the loop and immediately make sure to get out of it
DeleteOne = 0
for Unit in Devices: # inner loop to find what to delete
DeleteOne = 1 # stay in the loop because we may have to do our thing again
UnitToDelete = Unit
Item=Devices[Unit].Name
if DeleteOne == 1: # out of the inner loop it is safe to delete
Domoticz.Debug('.....')
Domoticz.Debug('.....Delete my own device: **'+Item+'** Unit: **'+str(UnitToDelete)+'**')
Devices[UnitToDelete].Delete()
Domoticz.Debug('.....Deleted my own device: **'+Item+'** Unit: **'+str(UnitToDelete)+'**')
#
# Create all my devices from internetradio.conf
#
for Device in DeviceLibrary:
if DeviceLibrary[Device]['Unit'] == -1:
Unit = 1
while Unit in Devices:
Unit = Unit + 1
DeviceLibrary[Device]['Unit'] = Unit
if DeviceLibrary[Device]['Type'] == 'StationList' :
Domoticz.Debug('Create '+str(Device))
CreateSelectorSwitch(Unit,DeviceLibrary[Device]['Name'],DeviceLibrary[Device]['StationLabels'],DeviceLibrary[Device]['Image'],DeviceLibrary[Device]['Description'],1)
if DeviceLibrary[Device]['Type'] == 'Dimmer' :
Domoticz.Debug('Create '+str(Device))
CreateDevice(Unit,DeviceLibrary[Device]['Name'],'Dimmer',DeviceLibrary[Device]['Image'],DeviceLibrary[Device]['Description'],DeviceLibrary[Device]['Units'],0)
if DeviceLibrary[Device]['Type'] == 'Text' :
Domoticz.Debug('Create '+str(Device))
CreateDevice(Unit,DeviceLibrary[Device]['Name'],'Text','',DeviceLibrary[Device]['Description'],'',0)
#
# Create Internet Radio Room internetradio.conf
#
for Device in DeviceLibrary:
if DeviceLibrary[Device]['Type'] == 'Room' :
Domoticz.Debug('Create Room: '+DeviceLibrary[Device]['Name'])
RoomIDX = CreateRoom(DeviceLibrary[Device]['Name'], False)
#
# Add all items to Internet Radio Room
#
for Device in DeviceLibrary:
if DeviceLibrary[Device]['Type'] != 'Room' :
Domoticz.Debug('Add Room Item: '+DeviceLibrary[Device]['Name']+' idx: '+str(Devices[DeviceLibrary[Device]['Unit']].ID))
AddToRoom(RoomIDX,Devices[DeviceLibrary[Device]['Unit']].ID)
#
# Make sure there is no mplayer process active
#
player('stop')
return MyStatus
# --------------------------------------------------------------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------------------------------------------------------------
def CreateRoom(RoomName, Recreate):
try:
import json
except:
Domoticz.Log("python3 is missing module json")
try:
import requests
except:
Domoticz.Log("python3 is missing module requests")
idx=0
try:
Domoticz.Debug('Check if Room Exists')
url=LocalHostInfo+'/json.htm?type=command¶m=getplans&order=name&used=true'
Domoticz.Debug('Check Room '+url)
response=requests.get(url, verify=False)
# response=requests.get(url)
data = json.loads(response.text)
if 'result' in data.keys():
for Item in data['result']:
if str(Item['Name']) == RoomName:
idx=int(Item['idx'])
Domoticz.Debug('Found Room '+RoomName+' with idx '+str(idx))
if (idx != 0) and Recreate :
url=LocalHostInfo+'/json.htm?idx='+str(idx)+'¶m=deleteplan&type=command'
Domoticz.Log('Delete Room '+url)
response=requests.get(url, verify=False)
# response=requests.get(url)
idx = 0
if idx == 0 :
url=LocalHostInfo+'/json.htm?name='+RoomName+'¶m=addplan&type=command'
Domoticz.Log('Create Room '+url)
response=requests.get(url, verify=False)
# response=requests.get(url)
data = json.loads(response.text)
Domoticz.Log('CreateRoom Created Room'+str(data))
idx=int(data['idx'])
except:
Domoticz.Log('ERROR CreateRoom Failed')
idx=0
Domoticz.Debug('CreateRoom status should not be 0 : '+str(idx))
return idx
# --------------------------------------------------------------------------------------------------------------------------------------------------------
def AddToRoom(RoomIDX,ItemIDX):
try:
import json
except:
Domoticz.Log("python3 is missing module json")
try:
import requests
except:
Domoticz.Log("python3 is missing module requests")
status=1
try:
url=LocalHostInfo+'/json.htm?activeidx='+str(ItemIDX)+'&activetype=0&idx='+str(RoomIDX)+'¶m=addplanactivedevice&type=command'
response=requests.get(url, verify=False)
# response=requests.get(url)
data = json.loads(response.text)
except:
Domoticz.Log('ERROR AddRoom Failed')
status=0
Domoticz.Debug('AddToRoom status should not be 0 : '+str(status))
return status
# --------------------------------------------------------------------------------------------------------------------------------------------------------
# ---------------------------------------------------- Hardware Routines --------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------------------------------------------------------------------
def player(action, device='', what=''):
import subprocess
import time
returncode='None'
if action == 'getdevice':
command='su -c - pi "amixer | head -n 1 | cut -b 22-100"'
elif action == 'play':
command='su -c - pi "nohup mplayer -msglevel all=-1 '+ what + ' > /dev/null 2>&1 &"'
elif action == 'volume':
command='su -c - pi "amixer set '+device+' '+str(what)+'%"'
elif action == 'getvolume':
command='su -c - pi amixer | grep "%" | head -1 | cut -d "[" -f 2 | cut -d "%" -f 1'
elif action == 'stop':
command ='killall mplayer'
# Domoticz.Log("player command : "+command)
try:
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
if action in ['getdevice', 'getvolume']:
timeouts=0
while timeouts < 10:
p_status = process.wait()
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
if action == 'getdevice':
device=str(output.strip())[2:-3]
returncode=device
if action == 'getvolume':
volume=str(output.strip())[2:-1]
returncode=volume
timeouts=10
else:
time.sleep(0.2)
timeouts=timeouts+1
except:
returncode='None'
return returncode
# --------------------------------------------------------------------------------------------------------------------------------------------------------