-
-
Notifications
You must be signed in to change notification settings - Fork 98
/
remote.py
345 lines (271 loc) · 13.2 KB
/
remote.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
from ws4py.client.threadedclient import WebSocketClient
from types import FunctionType
from urllib.parse import parse_qs, urlparse
from wakeonlan import send_magic_packet
import socket
import requests
import base64
import json
import os
import logging
from .payload import hello_data
class LGTVRemote(WebSocketClient):
@classmethod
def getCommands(cls):
excludes = [
'opened',
'closed',
'received_message',
'exec_command',
'getCommands'
]
out = []
m = [x for x, y in cls.__dict__.items() if type(y) == FunctionType]
for method in m:
if method.startswith("_" + cls.__name__):
continue
if method in excludes:
continue
if method.startswith("__"):
continue
out.append(method)
out.sort()
return out
def __init__(self, name, ip=None, mac=None, key=None, hostname=None, ssl=False):
self.__command_count = 0
self.__waiting_callback = None
self.__commands = []
self.__handshake_done = False
self.__hostname = hostname
self.__clientKey = key
self.__macAddress = mac
self.__ip = ip
self.__name = name
if self.__hostname is not None:
# Over ride IP address when we know the hostname
self.__ip = socket.gethostbyname(self.__hostname)
if ssl==False:
super(LGTVRemote, self).__init__('ws://' + self.__ip + ':3000/', exclude_headers=["Origin"])
else:
super(LGTVRemote, self).__init__('wss://' + self.__ip + ':3001/', exclude_headers=["Origin"])
def execute(self, command, args):
self.__commands.append({command: args})
if self.__handshake_done is True:
self.__execute()
def serialise(self):
return {
self.__name: {
"key": self.__clientKey,
"mac": self.__macAddress,
"ip": self.__ip,
"hostname": self.__hostname
}
}
#
# Pragma Mark WebSocketClient subclass
#
def opened(self):
if self.__clientKey is None:
raise Exception("Client is not authenticated")
logging.debug("Initiating handshake")
hello_data['payload']['client-key'] = self.__clientKey
self.__waiting_callback = self.__handshake
self.send(json.dumps(hello_data))
def closed(self, code, reason: str = ''):
if type(reason) == bytes:
reason = reason.decode('utf-8')
print (json.dumps({
"closing": {
"code": code,
"reason": str(reason)
}
}))
def received_message(self, response):
logging.debug("Received response")
logging.debug(response)
if self.__waiting_callback:
self.__waiting_callback(json.loads(str(response)))
#
# Pragma Mark Internal command handling
#
def __handshake(self, response):
if 'client-key' in response['payload'].keys():
logging.debug("Handshake complete")
self.__handshake_done = True
self.__execute()
def __execute(self):
if self.__handshake_done is False:
print ("Error: Handshake failed")
while len(self.__commands) > 0:
command = self.__commands.pop(0)
method = list(command.keys())[0]
args = command[method]
self.__class__.__dict__[method](self, **args)
# self.__waitClose()
def __waitClose(self):
self._th.join(timeout=1)
self.close()
def __defaultHandler(self, response):
logging.debug(response)
# {"type":"response","id":"0","payload":{"returnValue":true}}
if response['type'] == "error":
print (json.dumps(response))
self.close()
if "returnValue" in response["payload"] and response["payload"]["returnValue"] is True:
print (json.dumps(response))
self.close()
else:
print (json.dumps(response))
def __send_command(self, msgtype, uri, payload=None, callback=None, prefix=None):
if not callback:
callback = self.__defaultHandler
self.__waiting_callback = callback
if prefix is None:
messageid = str(self.__command_count)
else:
messageid = prefix + '_' + str(self.__command_count)
message_data = {
'id': messageid,
'type': msgtype,
'uri': uri
}
if type(payload) == dict:
payload = json.dumps(payload)
if type(payload) == str and len(payload) > 2:
message_data['payload'] = payload
self.__command_count += 1
logging.debug(message_data)
self.send(json.dumps(message_data))
def __get_youtube_id_from_url(self, url_string):
if url_string.startswith(("youtu", "www")):
url_string = "http://" + url_string
url = urlparse(url_string)
if url.hostname and url.path:
if "youtube" in url.hostname:
if url.path == "/watch":
return parse_qs(url.query)["v"][0]
elif url.path.startswith(("/embed/", "/v/")):
return url.path.split("/")[2]
elif "youtu.be" in url.hostname:
return url.path[1:]
# No ID found
return None
#
# Pragma Mark Supported commands
#
def on(self):
if not (self.__macAddress) and not (self.__ip):
print ("Client must have been powered on and paired before power on works")
send_magic_packet(self.__macAddress)
def off(self):
self.__send_command("request", "ssap://system/turnOff")
def openBrowserAt(self, url, callback=None):
self.__send_command("request", "ssap://system.launcher/open", {"target": url}, callback)
def notification(self, message, callback=None):
self.__send_command("request", "ssap://system.notifications/createToast", {"message": message}, callback)
def createAlert(self, message, button, callback=None):
self.__send_command("request", "ssap://system.notifications/createAlert", {"message": message, "buttons": [{"label": button}]}, callback)
def closeAlert(self, alertId, callback=None):
self.__send_command("request", "ssap://system.notifications/closeAlert", {'alertId': alertId}, callback)
# not working, why?
#def notificationClose(self, toastId, callback=None):
#self.__send_command("request", "ssap://system.notifications/closeToast", {'toastId': toastId}, callback)
def notificationWithIcon(self, message, url, callback=None):
if os.path.exists(url):
with open(url) as f:
content = f.read()
else:
content = requests.get(url).content
data = base64.b64encode(content)
data = {"iconData": data, "iconExtension": "png", "message": message}
self.__send_command("request", "ssap://system.notifications/createToast", data, callback)
def mute(self, muted, callback=None):
self.__send_command("request", "ssap://audio/setMute", {"mute": muted}, callback)
def audioStatus(self, callback=None):
self.__send_command("request", "ssap://audio/getStatus", None, callback, "status")
def audioVolume(self, callback=None):
self.__send_command("request", "ssap://audio/getVolume", None, callback, "status")
def setVolume(self, level, callback=None):
self.__send_command("request", "ssap://audio/setVolume", {"volume": level}, callback)
def volumeUp(self, callback=None):
self.__send_command("request", "ssap://audio/volumeUp", None, callback, "volumeup")
def volumeDown(self, callback=None):
self.__send_command("request", "ssap://audio/volumeDown", None, callback, "volumedown")
def inputMediaPlay(self, callback=None):
self.__send_command("request", "ssap://media.controls/play", None, callback)
def inputMediaStop(self, callback=None):
self.__send_command("request", "ssap://media.controls/stop", None, callback)
def inputMediaPause(self, callback=None):
self.__send_command("request", "ssap://media.controls/pause", None, callback)
def inputMediaRewind(self, callback=None):
self.__send_command("request", "ssap://media.controls/rewind", None, callback)
def inputMediaFastForward(self, callback=None):
self.__send_command("request", "ssap://media.controls/fastForward", None, callback)
def inputChannelUp(self, callback=None):
self.__send_command("request", "ssap://tv/channelUp", None, callback)
def inputChannelDown(self, callback=None):
self.__send_command("request", "ssap://tv/channelDown", None, callback)
def setTVChannel(self, channel, callback=None):
self.__send_command("request", "ssap://tv/openChannel", {"channelId": channel}, callback)
def getTVChannel(self, callback=None):
self.__send_command("request", "ssap://tv/getCurrentChannel", None, callback, "channels")
def listChannels(self, callback=None):
self.__send_command("request", "ssap://tv/getChannelList", None, callback, "channels")
def getCursorSocket(self, callback=None):
self.__send_command("request", "ssap://com.webos.service.networkinput/getPointerInputSocket", None, callback)
def sendEnterKey(self, callback=None):
self.__send_command("request", "ssap://com.webos.service.ime/sendEnterKey", None, callback)
def input3DOn(self, callback=None):
self.__send_command("request", "ssap://com.webos.service.tv.display/set3DOn", None, callback)
def input3DOff(self, callback=None):
self.__send_command("request", "ssap://com.webos.service.tv.display/set3DOff", None, callback)
def listInputs(self, callback=None):
self.__send_command("request", "ssap://tv/getExternalInputList", None, callback, "input")
def setInput(self, input_id, callback=None):
self.__send_command("request", "ssap://tv/switchInput", {"inputId": input_id}, callback)
def swInfo(self, callback=None):
self.__send_command("request", "ssap://com.webos.service.update/getCurrentSWInformation", None, callback, "sw_info")
def listServices(self, callback=None):
self.__send_command("request", "ssap://api/getServiceList", None, callback, "services")
def listLaunchPoints(self, callback=None):
self.__send_command("request", "ssap://com.webos.applicationManager/listLaunchPoints", None, callback, "launcher")
def openAppWithPayload(self, payload, callback=None):
self.__send_command("request", "ssap://com.webos.applicationManager/launch", payload, callback)
def startApp(self, appid, callback=None):
self.__send_command("request", "ssap://system.launcher/launch", {'id': appid}, callback)
def closeApp(self, appid, callback=None):
self.__send_command("request", "ssap://system.launcher/close", {'id': appid}, callback)
def openYoutubeId(self, videoid, callback=None):
self.openYoutubeURL("http://www.youtube.com/tv?v=" + videoid, callback)
def openYoutubeURL(self, url, callback=None):
payload = {"id": "youtube.leanback.v4", "params": {"contentTarget": url}}
self.__send_command("request", "ssap://system.launcher/launch", payload, callback)
def openYoutubeLegacyId(self, videoid, callback=None):
payload = {"id": "youtube.leanback.v4", "contentId": videoid}
self.__send_command("request", "ssap://system.launcher/launch", payload, callback)
def openYoutubeLegacyURL(self, url, callback=None):
videoid = self.__get_youtube_id_from_url(url)
if videoid:
self.openYoutubeLegacyId(videoid, callback)
else:
logging.debug("Invalid Youtube video URL: " + url)
print("Invalid Youtube video URL")
self.close()
def getForegroundAppInfo(self, callback=None):
self.__send_command("request", "ssap://com.webos.applicationManager/getForegroundAppInfo", None, callback)
def getPowerState(self, callback=None):
self.__send_command("request", "ssap://com.webos.service.tvpower/power/getPowerState", None, callback)
def getSoundOutput(self, callback=None):
self.__send_command("request", "ssap://com.webos.service.apiadapter/audio/getSoundOutput", None, callback)
def getSystemInfo(self, callback=None):
self.__send_command("request", "ssap://system/getSystemInfo", None, callback)
def listApps(self, callback=None):
self.__send_command("request", "ssap://com.webos.applicationManager/listApps", None, callback)
def setSoundOutput(self, output, callback=None):
self.__send_command("request", "ssap://audio/changeSoundOutput", {"output": output}, callback)
def screenOff(self):
self.__send_command("request", "ssap://com.webos.service.tvpower/power/turnOffScreen", {"standbyMode": "active"})
def screenOn(self):
self.__send_command("request", "ssap://com.webos.service.tvpower/power/turnOnScreen", {"standbyMode": "active"})
def getPictureSettings(self, keys=["contrast", "backlight", "brightness", "color"]):
self.__send_command("request", "ssap://settings/getSystemSettings", {"category": "picture", "keys": keys})