-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.py
409 lines (384 loc) · 13.3 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
"""
<plugin key="AndroidTV" name="Android TV" author="enesbcs" version="0.0.1">
<params>
<param field="Address" label="IP Address" width="200px" required="true" default="127.0.0.1"/>
<param field="Port" label="Port" width="40px" required="true" default="5555"/>
<param field="Mode1" label="MAC Address (WOL)" width="200px" required="false" default=""/>
<param field="Mode6" label="Debug" width="75px">
<options>
<option label="True" value="Debug"/>
<option label="False" value="Normal" default="True" />
</options>
</param>
</params>
</plugin>
"""
#
# Main Import
import Domoticz
import socket
import subprocess
import struct
import re
import configparser
import os
import sys
class BasePlugin:
# Connection Status
isConnected = -1
volume = -1
initialized = 0
def __init__(self):
return
def onStart(self):
self.initialized = 0
if Parameters["Mode6"] == "Debug":
Domoticz.Debugging(1)
try:
dbfilename = os.path.join(os.path.dirname(__file__), 'database.ini' )
self.cfg = configparser.ConfigParser()
self.cfg.optionxform = str
self.cfg.read(dbfilename)
except Exception as e:
Domoticz.Log(str(e))
self.initialized = 0
return False
if (len(Devices) == 0):
try:
Domoticz.Device(Name="Status", Unit=1, Type=17, Image=2, Switchtype=17, Used=1).Create()
ase = 'Sources'
levelac = ""
levelnames = "Off"
st = "0"
hs = "true"
if self.cfg.has_section(ase):
ops = self.cfg.options(ase)
for o in ops:
levelac += "|"
levelnames += "|"+str(o)
if len(ops)>4:
st = "1"
hs = "false"
Options = { "LevelActions" : levelac ,
"LevelNames" : levelnames,
"LevelOffHidden": hs,
"SelectorStyle" : st
}
Domoticz.Device(Name="Source", Unit=2, TypeName="Selector Switch", Switchtype=18, Image=12, Options=Options, Used=1).Create()
Domoticz.Device(Name="Volume", Unit=3, Type=244, Subtype=73, Switchtype=7, Image=8, Used=1).Create()
Domoticz.Device(Name="App", Unit=4, Type=243, Subtype=19, Used=1).Create()
ase = 'Apps'
levelac = ""
levelnames = "Off"
st = "0"
hs = "true"
if self.cfg.has_section(ase):
ops = self.cfg.options(ase)
for o in ops:
levelac += "|"
levelnames += "|"+str(o)
if len(ops)>4:
st = "1"
hs = "false"
Options = { "LevelActions" : levelac ,
"LevelNames" : levelnames,
"LevelOffHidden": hs,
"SelectorStyle" : st
}
Domoticz.Device(Name="App Selector", Unit=5, TypeName="Selector Switch", Switchtype=18, Image=12, Options=Options, Used=1).Create()
ase = 'Remote'
levelac = ""
levelnames = "Off"
st = "0"
hs = "true"
if self.cfg.has_section(ase):
ops = self.cfg.options(ase)
for o in ops:
levelac += "|"
levelnames += "|"+str(o)
if len(ops)>4:
st = "1"
hs = "false"
Options = { "LevelActions" : levelac ,
"LevelNames" : levelnames,
"LevelOffHidden": hs,
"SelectorStyle" : st
}
Domoticz.Device(Name="Remote commands", Unit=6, TypeName="Selector Switch", Switchtype=18, Image=18, Options=Options, Used=1).Create()
Domoticz.Log("Devices created.")
except Exception as e:
Domoticz.Log(str(e))
self.initialized = 0
return False
Domoticz.Heartbeat(10)
self.config = {
"host" : Parameters["Address"],
"port" : int(Parameters["Port"]),
"mac" : Parameters["Mode1"]
}
Domoticz.Log("Connecting to: "+Parameters["Address"]+":"+Parameters["Port"])
self.isConnected = -1
self.volume = -1
self._isAlive()
if self.isConnected == 1:
try:
subprocess.run(["adb", "connect", self.config["host"]+":"+str(self.config["port"])], timeout=5 )
except:
pass
self.initialized = 1
return True
def onStop(self):
Domoticz.Debug("onStop called")
if self.isConnected == 2:
try:
subprocess.run(["adb", "disconnect", self.config["host"]+":"+str(self.config["port"])], timeout=1 )
except:
pass
def _isAlive(self):
origstat = self.isConnected
socket.setdefaulttimeout(1)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((self.config["host"], self.config["port"]))
if self.isConnected < 1:
self.isConnected = 1 # port opened
except socket.error as e:
self.isConnected = 0
s.close()
if self.isConnected > 0:
try:
log = str(subprocess.check_output("adb -s "+self.config["host"]+":"+str(self.config["port"])+ " get-state", shell=True, timeout=2))
if ("device" in log) and ("error" not in log):
self.isConnected = 2
else:
Domoticz.Debug("ADB error "+log)
except:
pass
if self.isConnected != origstat:
if self.isConnected == 0:
Domoticz.Heartbeat(20)
else:
Domoticz.Heartbeat(10)
if Parameters["Mode6"] == "Debug":
Domoticz.Log("isAlive status :" +str(self.isConnected))
return
def _wakeonlan(self):
mac = str(self.config["mac"]).strip().upper()
if len(mac) > 2:
try:
Domoticz.Debug("WOL "+str(mac))
if ":" in mac:
addr_byte = mac.split(':')
elif "-" in mac:
addr_byte = mac.split('-')
else:
addr_byte = []
if len(addr_byte)>4:
hw_addr = struct.pack('BBBBBB', int(addr_byte[0], 16),
int(addr_byte[1], 16),
int(addr_byte[2], 16),
int(addr_byte[3], 16),
int(addr_byte[4], 16),
int(addr_byte[5], 16))
msg = b'\xff' * 6 + hw_addr * 16
socket_instance = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socket_instance.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
socket_instance.sendto(msg, ('<broadcast>', 9))
socket_instance.close()
except Exception as e:
Domoticz.Debug("WOL error"+str(e))
def onCommand(self, Unit, Command, Level, Color): # react to commands arrived from Domoticz
Domoticz.Log("onCommand called for Unit " + str(Unit) + ": Parameter '" + str(Command) + "', Level: " + str(Level) + ", Connected: " + str(self.isConnected))
Command = Command.strip()
if (Unit == 1): # Status
if (Command == 'On'):
if (self.isConnected == 2):
try: #adb switch on
Domoticz.Debug("ADB on cmd")
subprocess.run(["adb", "-s", self.config["host"]+":"+str(self.config["port"]),"shell","input","keyevent","224"], timeout=1 )
except:
pass
else:
self._wakeonlan() #WOL
else:
if (self.isConnected == 2):
try: #switch off
subprocess.run(["adb", "-s", self.config["host"]+":"+str(self.config["port"]),"shell","input","keyevent","223"], timeout=1 )
except:
pass
else:
Domoticz.Debug("Off cmd when ADB offline")
if (self.isConnected == 2):
if (Unit == 2): # Source
if (Command == 'Set Level'):
ase = 'Sources'
cmdl = ""
if self.cfg.has_section(ase):
ops = self.cfg.options(ase)
cmdc = 0
for o in ops:
cmdl = self.cfg.get(ase,o,raw=True)
cmdc += 10
if cmdc >= Level:
break
try:
cmd = ["adb", "-s", self.config["host"]+":"+str(self.config["port"])]
cmd2 = cmdl.split()
cmd += cmd2
subprocess.run(cmd, timeout=2 )
except:
pass
if (Unit == 3): # Volume
if (Command == 'Set Level'):
try:
subprocess.run(["adb", "-s", self.config["host"]+":"+str(self.config["port"]),"shell","media","volume","--show","--set", str(Level)], timeout=2 )
if int(Level) == 0:
ml = 0
else:
ml = 1
Devices[3].Update(nValue=ml,sValue=str(Level))
except:
pass
elif Command == "Off": #mute
if self.volume > 0:
try:
subprocess.run(["adb", "-s", self.config["host"]+":"+str(self.config["port"]),"shell","input","keyevent","164"], timeout=2 )
except:
pass
elif Command == "On": #unmute
if self.volume == 0:
try:
subprocess.run(["adb", "-s", self.config["host"]+":"+str(self.config["port"]),"shell","input","keyevent","164"], timeout=2 )
except:
pass
if (Unit == 5): # Apps
if (Command == 'Set Level'):
ase = 'Apps'
cmdl = ""
if self.cfg.has_section(ase):
ops = self.cfg.options(ase)
cmdc = 0
for o in ops:
cmdl = self.cfg.get(ase,o,raw=True)
cmdc += 10
if cmdc >= Level:
break
try:
cmd = ["adb", "-s", self.config["host"]+":"+str(self.config["port"])]
cmd2 = cmdl.split()
cmd += cmd2
subprocess.run(cmd, timeout=2 )
except:
pass
if (Unit == 6): # Remote
if (Command == 'Set Level'):
ase = 'Remote'
cmdl = ""
if self.cfg.has_section(ase):
cmdc = 0
ops = self.cfg.options(ase)
for o in ops:
cmdl = self.cfg.get(ase,o,raw=True)
cmdc += 10
if cmdc >= Level:
break
try:
subprocess.run(["adb", "-s", self.config["host"]+":"+str(self.config["port"]),"shell","input","keyevent",cmdl], timeout=2 )
except:
pass
return True
def onHeartbeat(self):
Domoticz.Debug("Heartbeating...")
if self.initialized==0:
self.isConnected = 0
return False
self._isAlive()
currentStatus = 0
if self.isConnected == 1:
try:
subprocess.run(["adb", "connect", self.config["host"]+":"+str(self.config["port"])], timeout=1 )
except:
pass
elif self.isConnected == 2:
try:
log = str(subprocess.check_output("adb -s "+self.config["host"]+":"+str(self.config["port"])+ " shell dumpsys power |grep 'mWakefulness'", shell=True, timeout=2))
if "Awake" in log:
currentStatus = 1
elif "error:" in log:
self.isConnected = 1
except:
self.isConnected = 1
if self.isConnected==2:
try:
log = str(subprocess.check_output("adb -s "+self.config["host"]+":"+str(self.config["port"])+ " shell media volume --get", shell=True, timeout=2))
except:
log = "error:"
if ("error:" in log):
self.isConnected = 1
elif "volume" in log:
sl = log.find('volume is')
if sl>-1:
ts = log[(sl+10):]
ta = ts.split(" ")
try:
self.volume = int(float(ta[0].strip()))
if self.volume == 0:
ml = 0
else:
ml = 1
try:
av = int(Devices[3].sValue)
except:
av = -1
if av != int(self.volume):
Devices[3].Update(nValue=ml,sValue=str(self.volume))
except:
pass
if self.isConnected==2:
try:
log = str(subprocess.check_output("adb -s "+self.config["host"]+":"+str(self.config["port"])+ " shell dumpsys window windows |grep -E 'mFocusedApp'", shell=True, timeout=2))
except Exception as e:
log = "error: "+str(e)
if ("error:" in log):
self.isConnected = 1
elif "Focus" in log:
try:
current_focus = re.search(r'(\b\S+\/\S+\b)', log, re.IGNORECASE).group(0)
except:
current_focus = ""
if str(Devices[4].sValue).strip() != str(current_focus).strip():
Devices[4].Update(nValue=0,sValue=str(current_focus))
if currentStatus == 0:
if Devices[1].nValue != currentStatus:
Devices[1].Update(nValue=0,sValue="Off")
Devices[4].Update(nValue=0,sValue="")
else:
if Devices[1].nValue != currentStatus:
Devices[1].Update(nValue=1,sValue="On")
return True
global _plugin
_plugin = BasePlugin()
def onStart():
global _plugin
_plugin.onStart()
def onStop():
global _plugin
_plugin.onStop()
def onConnect(Connection, Status, Description):
global _plugin
return
def onDeviceModified(Unit):
global _plugin
return
def onDisconnect(Connection):
global _plugin
return
def onMessage(Connection, Data):
global _plugin
return
def onCommand(Unit, Command, Level, Color):
global _plugin
_plugin.onCommand(Unit, Command, Level, Color)
def onHeartbeat():
global _plugin
_plugin.onHeartbeat()