This repository has been archived by the owner on Apr 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
remotestick-server.py
executable file
·462 lines (404 loc) · 15.7 KB
/
remotestick-server.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
#!/usr/bin/env python
#
# Copyright 2010 Patrik Akerfeldt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
#
from bottle import route, run, response, request, static_file
from ctypes import util
from ctypes import *
from getopt import getopt, GetoptError
from sys import argv, exit, platform
from base64 import b64encode
import time
VERSION = "0.4.1"
API_VERSION = 1
#Device methods
TELLSTICK_TURNON = 1
TELLSTICK_TURNOFF = 2
TELLSTICK_BELL = 4
TELLSTICK_TOGGLE = 8
TELLSTICK_DIM = 16
TELLSTICK_LEARN = 32
ALL_METHODS = TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_BELL | TELLSTICK_TOGGLE | TELLSTICK_DIM | TELLSTICK_LEARN
reqauth = True
username = None
password = None
libtelldus = None
static_folder = "./static/"
disable_static=False
def loadlibrary(libraryname=None):
if libraryname == None:
if platform == "darwin" or platform == "win32":
libraryname = "TelldusCore"
elif platform == "linux2":
libraryname = "telldus-core"
else:
libraryname = "TelldusCore"
ret = util.find_library(libraryname)
else:
ret = libraryname
if ret == None:
return (None, libraryname)
global libtelldus
if platform == "win32":
libtelldus = windll.LoadLibrary(ret)
else:
libtelldus = cdll.LoadLibrary(ret)
libtelldus.tdGetName.restype = c_char_p
libtelldus.tdLastSentValue.restype = c_char_p
libtelldus.tdGetProtocol.restype = c_char_p
libtelldus.tdGetModel.restype = c_char_p
libtelldus.tdGetErrorString.restype = c_char_p
libtelldus.tdLastSentValue.restype = c_char_p
return ret, libraryname
def errmsg(x):
return {
100: "Authentication failed",
101: "Unsupported format",
201: "Name not supplied",
202: "Model not supplied",
203: "Protocol not supplied",
210: "Malformed parameters",
211: "No device removed",
220: "Method not supported",
300: "Telldus-core error"
}[x]
def err(format, responsecode, request, code, code_msg=None):
response.status = responsecode
if responsecode == 401:
response.headers.append("WWW-Authenticate", "Basic realm=\"RemoteStick\"")
if code_msg == None:
code_msg = errmsg(code)
if format == "xml":
return err_xml(request, code_msg)
else:
return err_xml(request, code_msg)
def err_xml(request, msg):
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<hash>\n\t<request>" + request + "</request>\n\t<error>" + msg + "</error>\n</hash>"
def authenticate(auth):
global username, password
if reqauth and auth == None:
return False
elif reqauth:
sentUsername, sentPassword = auth
return (username == sentUsername and password == sentPassword)
else:
return True
def read_device(identity):
name = libtelldus.tdGetName(identity)
lastcmd = libtelldus.tdLastSentCommand(identity, 1)
protocol = libtelldus.tdGetProtocol(identity)
model = libtelldus.tdGetModel(identity)
methods = libtelldus.tdMethods(identity, ALL_METHODS)
lastValue = libtelldus.tdLastSentValue(identity)
element = "<device id=\"" + str(identity) + "\">\n\t\t<name>" + name + "</name>\n\t\t<protocol>" + protocol + "</protocol>\n\t\t<model>" + model + "</model>\n"
if lastcmd == 1:
element += "\t\t<lastcmd>ON</lastcmd>\n"
else:
element += "\t\t<lastcmd>OFF</lastcmd>\n"
if lastValue != None and lastValue != "":
try:
lastValueConverted = int(lastValue)
element += "\t\t<lastvalue>" + str(lastValueConverted) + "</lastvalue>\n"
except Exception, e:
pass
if methods & TELLSTICK_BELL:
element += "\t\t<supportedMethod id=\"" + str(TELLSTICK_BELL) + "\">" + "TELLSTICK_BELL</supportedMethod>\n"
if methods & TELLSTICK_TOGGLE:
element += "\t\t<supportedMethod id=\"" + str(TELLSTICK_TOGGLE) + "\">" + "TELLSTICK_TOGGLE</supportedMethod>\n"
if methods & TELLSTICK_TURNOFF:
element += "\t\t<supportedMethod id=\"" + str(TELLSTICK_TURNOFF) + "\">" + "TELLSTICK_TURNOFF</supportedMethod>\n"
if methods & TELLSTICK_TURNON:
element += "\t\t<supportedMethod id=\"" + str(TELLSTICK_TURNON) + "\">" + "TELLSTICK_TURNON</supportedMethod>\n"
if methods & TELLSTICK_DIM:
element += "\t\t<supportedMethod id=\"" + str(TELLSTICK_DIM) + "\">" + "TELLSTICK_DIM</supportedMethod>\n"
if methods & TELLSTICK_LEARN:
element += "\t\t<supportedMethod id=\"" + str(TELLSTICK_LEARN) + "\">" + "TELLSTICK_LEARN</supportedMethod>\n"
element += "</device>\n"
return element
def pre_check(format, accepted_formats):
if format not in accepted_formats:
return False, 400, 101
if not authenticate(request.auth):
return False, 401, 100
return True, None, None
def set_headers(format):
if format == "xml":
response.set_content_type('text/xml; charset=utf8')
response.headers.append("X-API-VERSION", str(API_VERSION))
response.headers.append("X-VERSION", VERSION)
@route('/devices.:format', method='GET')
def devices(format):
ok, response_code, error_code = pre_check(format, ["xml"])
if not ok:
return err(format, response_code, 'GET /devices.' + format, error_code)
set_headers(format)
result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<devices>\n"
numDevices = libtelldus.tdGetNumberOfDevices()
for i in range(numDevices):
result += read_device(libtelldus.tdGetDeviceId(i))
result += "</devices>"
return result
@route('/devices.:format', method='POST')
def new_device(format):
request_str = 'POST /devices.' + format
ok, response_code, error_code = pre_check(format, ["xml"])
if not ok:
return err(format, response_code, request_str, error_code)
set_headers(format)
name = request.POST.get('name', '').strip()
if not name:
return err(format, 400, request_str, 201)
model = request.POST.get('model', '')
if not model:
return err(format, 400, request_str, 202)
protocol = request.POST.get('protocol', '')
if not protocol:
return err(format, 400, request_str, 203)
rawParams = request.POST.get('parameters', '')
parameters = []
if rawParams != None:
for param in rawParams.split():
keyval = param.split('=')
if len(keyval) != 2:
return err(format, 400, request_str, 210)
else:
parameters.append(keyval)
identity = libtelldus.tdAddDevice()
libtelldus.tdSetName(identity, name.strip())
libtelldus.tdSetProtocol(identity, protocol.strip())
libtelldus.tdSetModel(identity, model.strip())
for param in parameters:
libtelldus.tdSetDeviceParameter(identity, param[0], param[1])
retval = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
retval += read_device(identity)
return retval
@route('/devices/:id.:format', method='GET')
def get_device(id, format):
request_str = 'GET /devices/' + id + "." + format
ok, response_code, error_code = pre_check(format, ["xml"])
if not ok:
return err(format, response_code, request_str, error_code)
set_headers(format)
retval = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
try:
retval += read_device(int(id))
return retval
except ValueError:
return err(format, 400, request_str, 210)
@route('/devices/:id.:format', method='DELETE')
def delete_device(id, format):
request_str = 'DELETE /devices/' + id + "." + format
ok, response_code, error_code = pre_check(format, ["xml"])
if not ok:
return err(format, response_code, request_str, error_code)
set_headers(format)
try:
retval = libtelldus.tdRemoveDevice(int(id))
except ValueError:
return err(format, 400, request_str, 210)
if retval == 1:
return ""
else:
return err(format, 400, request_str, 211)
@route('/devices/:id.:format', method='PUT')
def change_device(id, format):
request_str = 'PUT /devices/' + id + "." + format
ok, response_code, error_code = pre_check(format, ["xml"])
if not ok:
return err(format, response_code, request_str, error_code)
set_headers(format)
name = request.POST.get('name', '').strip()
protocol = request.POST.get('protocol', '').strip()
model = request.POST.get('model', '').strip()
if name:
libtelldus.tdSetName(int(id), name)
if model:
libtelldus.tdSetModel(int(id), model)
if protocol:
libtelldus.tdSetProtocol(int(id), protocol)
retval = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
try:
retval += read_device(int(id))
return retval
except ValueError:
return err(format, 400, request_str, 210)
return ""
@route('/devices/:id/on.:format', method='GET')
def turnon_device(id, format):
request_str = 'GET /devices/' + id + "/on." + format
ok, response_code, error_code = pre_check(format, ["xml"])
if not ok:
return err(format, response_code, request_str, error_code)
set_headers(format)
try:
identity = int(id)
except ValueError:
return err(format, 400, request_str, 210)
if libtelldus.tdMethods(identity, TELLSTICK_TURNON) & TELLSTICK_TURNON:
retval = libtelldus.tdTurnOn(identity)
if retval == 0:
return ""
else:
return err(format, 502, request_str, 300, libtelldus.tdGetErrorString(retval))
else:
return err(format, 400, request_str, 220)
@route('/devices/:id/off.:format', method='GET')
def turnoff_device(id, format):
request_str = 'GET /devices/' + id + "/off." + format
ok, response_code, error_code = pre_check(format, ["xml"])
if not ok:
return err(format, response_code, request_str, error_code)
set_headers(format)
try:
identity = int(id)
except ValueError:
return err(format, 400, request_str, 210)
if libtelldus.tdMethods(identity, TELLSTICK_TURNOFF) & TELLSTICK_TURNOFF:
retval = libtelldus.tdTurnOff(identity)
if retval == 0:
return ""
else:
return err(format, 502, request_str, 300, libtelldus.tdGetErrorString(retval))
else:
return err(format, 400, request_str, 220)
@route('/devices/:id/dim/:level.:format', method='GET')
def dim_device(id, level, format):
request_str = 'GET /devices/' + id + "/dim/" + level + "." + format
ok, response_code, error_code = pre_check(format, ["xml"])
if not ok:
return err(format, response_code, request_str, error_code)
set_headers(format)
try:
identity = int(id)
dimlevel = int(level)
# dimlevel = int(round(int(level)*2.55))
except ValueError:
return err(format, 400, request_str, 210)
if libtelldus.tdMethods(identity, TELLSTICK_DIM) & TELLSTICK_DIM:
retval = libtelldus.tdDim(identity, dimlevel)
if retval == 0:
return ""
else:
return err(format, 502, request_str, 300, libtelldus.tdGetErrorString(retval))
else:
return err(format, 400, request_str, 220)
@route('/devices/:id/learn.:format', method='GET')
def learn_device(id, format):
request_str = 'GET /devices/' + id + "/learn." + format
ok, response_code, error_code = pre_check(format, ["xml"])
if not ok:
return err(format, response_code, request_str, error_code)
set_headers(format)
try:
identity = int(id)
except ValueError:
return err(format, 400, request_str, 210)
if libtelldus.tdMethods(identity, TELLSTICK_LEARN) & TELLSTICK_LEARN:
retval = libtelldus.tdLearn(identity)
if retval == 0:
return ""
else:
return err(format, 502, request_str, 300, libtelldus.tdGetErrorString(retval))
else:
return err(format, 400, request_str, 220)
@route('/s', method='GET')
@route('/s/', method='GET')
def static_default():
global disable_static
global static_folder
if not disable_static:
return static_file('index.html', root=static_folder)
@route('/s/:file#.*[^/]#', method='GET')
def static(file):
global disable_static
global static_folder
if not disable_static:
return static_file(file, root=static_folder)
def usage():
print "Usage: remotestick-server [OPTION] ..."
print "Expose tellstick interfaces through RESTful services."
print ""
print "Without any arguments remotestick-server will start a http server on 127.0.0.1:8422 where no authentication is required."
print "Setting the name of the telldus-core library should not be needed. remotestick-server is able to figure out the correct library name automatically. If, for some reason, this is unsuccessful, use --library."
print ""
print "Given that static files are not disabled, they are always accessed through the URI path /s/ not matter where the static files folder is defined."
print ""
print "-h, --host\t\tHost/IP which the server will bind to, default to loopback"
print "-p, --port\t\tPort which the server will listen on, default to 8422"
print "-u, --username\t\tUsername used for client authentication"
print "-s, --password\t\tPassword used for client authentication"
print "-l, --library\t\tName of telldus-core library"
print "-f, --static\t\tPath to static files folder, defaults to ./static"
print "-d, --disable-static\tDisable static files"
print "-V, --version\t\tPrint the version number and exit"
def version():
print "remotestick-server v" + VERSION
def main():
try:
opts, args = getopt(argv[1:], "?h:p:u:s:l:f:dV", ["?", "host=", "port=", "username=", "password=", "library=", "static=", "disable-static", "version"])
except GetoptError, err:
print str(err)
usage()
exit(2)
host = None
port = None
library = None
global username
global password
global reqauth
global static
global disable_static
for o, a in opts:
if o in ("-h", "--host"):
host = a
elif o in ("-p", "--port"):
port = a
elif o in ("-u", "--username"):
username = a
elif o in ("-s", "--password"):
password = a
elif o in ("-l", "--library"):
library = a
elif o in ("-f", "--static"):
static_folder = a
elif o in ("-d", "--disable-static"):
disable_static=True
elif o in ("-V", "--version"):
version()
exit()
elif o == '-?':
usage()
exit()
else:
assert False, "unhandled option " + o
lib, libname = loadlibrary(library)
if lib == None:
print "Error: Cannot find library " + libname
exit(3)
if username == None or password == None:
print "Warning: No authentication required. Please consider setting --username and --password."
reqauth = False
if (host == None and port == None):
run(host="0.0.0.0", port="8422")
elif host != None and port == None:
run(host=host, port="8422")
elif host == None and port != None:
run(host="0.0.0.0", port=port)
else:
run(host=host, port=port)
if __name__ == "__main__":
main()