forked from jorilytter/remotestick-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remotestick-server.py
executable file
·466 lines (394 loc) · 14.6 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
463
464
465
466
#!/usr/bin/env python
#
# Copyright 2015 Jori Lytter
# 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
import sensorconf
VERSION = "0.6.0"
API_VERSION = 3
#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
TELLSTICK_TEMPERATURE = 1
TELLSTICK_HUMIDITY = 2
reqauth = True
username = None
password = None
libtelldus = None
static_folder = "./static/"
def loadlibrary(libraryname=None):
if libraryname == None:
libraryname = "telldus-core"
ret = util.find_library(libraryname)
else:
ret = libraryname
if ret == None:
return (None, libraryname)
global libtelldus
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(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)
return "{\"request\": \"" + request + "\", \"error\": \"" + code_msg + "\"}"
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 = ("{"
"\"id\": \"" + str(identity) + "\","
"\"name\": \"" + name + "\","
"\"protocol\": \"" + protocol + "\","
"\"model\": \"" + model + "\",")
if lastcmd == 1:
element += "\"lastcmd\": \"ON\""
else:
element += "\"lastcmd\": \"OFF\""
if lastValue != None and lastValue != "":
try:
lastValueConverted = int(lastValue)
element += ",\"lastvalue\": \"" + str(lastValueConverted) + "\""
except Exception, e:
pass
element += ",\"supportedMethods\": ["
if methods & TELLSTICK_BELL:
element += "{\"id\": \"" + str(TELLSTICK_BELL) + "\", \"name\": \"TELLSTICK_BELL\"},"
if methods & TELLSTICK_TOGGLE:
element += "{\"id\": \"" + str(TELLSTICK_TOGGLE) + "\", \"name\": \"TELLSTICK_TOGGLE\"},"
if methods & TELLSTICK_TURNOFF:
element += "{\"id\": \"" + str(TELLSTICK_TURNOFF) + "\", \"name\": \"TELLSTICK_TURNOFF\"},"
if methods & TELLSTICK_TURNON:
element += "{\"id\": \"" + str(TELLSTICK_TURNON) + "\", \"name\": \"TELLSTICK_TURNON\"},"
if methods & TELLSTICK_DIM:
element += "{\"id\": \"" + str(TELLSTICK_DIM) + "\", \"name\": \"TELLSTICK_DIM\"},"
if methods & TELLSTICK_LEARN:
element += "{\"id\": \"" + str(TELLSTICK_LEARN) + "\", \"name\": \"TELLSTICK_LEARN\"},"
element = element[:-1]
element += "]},"
return element
def pre_check():
if not authenticate(request.auth):
return False, 401, 100
return True, None, None
def set_headers():
response.set_content_type("application/json; charset=utf8")
response.headers.append("X-API-VERSION", str(API_VERSION))
response.headers.append("X-VERSION", VERSION)
@route("/devices", method="GET")
def devices():
set_headers()
result = "{\"devices\": ["
numDevices = libtelldus.tdGetNumberOfDevices()
for i in range(numDevices):
result += read_device(libtelldus.tdGetDeviceId(i))
result = result[:-1]
result += "]}"
return result
# Sensor reading example taken from https://github.com/whale521/telldus_test/blob/95f93cd6d316a910c5d4d2d518f772e43b7caa20/examples/python/sensors/sensorspoll.py
@route("/sensors", method ="GET")
def sensors():
set_headers()
result = "{"
protocollength = 20
modellength = 20
valuelength = 20
protocol = create_string_buffer(protocollength)
model = create_string_buffer(modellength)
idvalue = c_int()
dataTypes = c_int()
while(libtelldus.tdSensor(protocol, protocollength, model, modellength, byref(idvalue), byref(dataTypes)) == 0):
if (idvalue.value == sensorconf.outdoor or idvalue.value == sensorconf.indoor):
print "Sensor: ", protocol.value, model.value, "id:", idvalue.value
value = create_string_buffer(valuelength)
timestampvalue = c_int()
if((dataTypes.value & TELLSTICK_TEMPERATURE) != 0):
success = libtelldus.tdSensorValue(protocol.value, model.value, idvalue.value, TELLSTICK_TEMPERATURE, value, valuelength, byref(timestampvalue))
print "Temperature: ", value.value, "C,"
if (idvalue.value == sensorconf.outdoor):
result += "\"outdoorTemperature\":"
result += value.value
if (idvalue.value == sensorconf.indoor):
result += "\"indoorTemperature\":"
result += value.value
result += ","
if((dataTypes.value & TELLSTICK_HUMIDITY) != 0 and idvalue.value == sensorconf.indoor):
success = libtelldus.tdSensorValue(protocol.value, model.value, idvalue.value, TELLSTICK_HUMIDITY, value, valuelength, byref(timestampvalue))
print "Humidity: ", value.value, "%,"
result += "\"indoorHumidity\":"
result += value.value
result += ","
result = result[:-1]
result += "}"
return result
@route("/devices", method="POST")
def new_device():
request_str = "POST /devices"
set_headers()
name = request.POST.get("name", "").strip()
if not name:
return err(400, request_str, 201)
model = request.POST.get("model", "")
if not model:
return err(400, request_str, 202)
protocol = request.POST.get("protocol", "")
if not protocol:
return err(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(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 = read_device(identity)
return retval
@route("/devices/:id", method="GET")
def get_device(id):
request_str = "GET /devices/" + id
set_headers()
try:
retval = read_device(int(id))
return retval
except ValueError:
return err(400, request_str, 210)
@route("/devices/:id", method="DELETE")
def delete_device(id):
request_str = "DELETE /devices/" + id
set_headers()
try:
retval = libtelldus.tdRemoveDevice(int(id))
except ValueError:
return err(400, request_str, 210)
if retval == 1:
return "{\"status\": \"OK\"}"
else:
return err(400, request_str, 211)
@route("/devices/:id", method="PUT")
def change_device(id):
request_str = "PUT /devices/" + id
set_headers()
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)
try:
retval = read_device(int(id))
return retval
except ValueError:
return err(400, request_str, 210)
return "{\"status\": \"OK\"}"
@route("/devices/:id/on", method="GET")
def turnon_device(id):
request_str = "GET /devices/" + id + "/on"
set_headers()
try:
identity = int(id)
except ValueError:
return err(400, request_str, 210)
if libtelldus.tdMethods(identity, TELLSTICK_TURNON) & TELLSTICK_TURNON:
retval = libtelldus.tdTurnOn(identity)
if retval == 0:
return "{\"status\": \"OK\"}"
else:
return err(502, request_str, 300, libtelldus.tdGetErrorString(retval))
else:
return err(400, request_str, 220)
@route("/devices/:id/off", method="GET")
def turnoff_device(id):
request_str = "GET /devices/" + id + "/off"
set_headers()
try:
identity = int(id)
except ValueError:
return err(400, request_str, 210)
if libtelldus.tdMethods(identity, TELLSTICK_TURNOFF) & TELLSTICK_TURNOFF:
retval = libtelldus.tdTurnOff(identity)
if retval == 0:
return "{\"status\": \"OK\"}"
else:
return err(502, request_str, 300, libtelldus.tdGetErrorString(retval))
else:
return err(400, request_str, 220)
@route("/devices/:id/dim/:level", method="GET")
def dim_device(id, level):
request_str = "GET /devices/" + id + "/dim/" + level
set_headers()
try:
identity = int(id)
dimlevel = int(level)
# dimlevel = int(round(int(level)*2.55))
except ValueError:
return err(400, request_str, 210)
if libtelldus.tdMethods(identity, TELLSTICK_DIM) & TELLSTICK_DIM:
retval = libtelldus.tdDim(identity, dimlevel)
if retval == 0:
return "{\"status\": \"OK\"}"
else:
return err(502, request_str, 300, libtelldus.tdGetErrorString(retval))
else:
return err(400, request_str, 220)
@route("/devices/:id/learn", method="GET")
def learn_device(id):
request_str = "GET /devices/" + id + "/learn"
set_headers()
try:
identity = int(id)
except ValueError:
return err(400, request_str, 210)
if libtelldus.tdMethods(identity, TELLSTICK_LEARN) & TELLSTICK_LEARN:
retval = libtelldus.tdLearn(identity)
if retval == 0:
return "{\"status\": \"OK\"}"
else:
return err(502, request_str, 300, libtelldus.tdGetErrorString(retval))
else:
return err(400, request_str, 220)
@route("/", method="GET")
@route("", method="GET")
def static_default():
global static_folder
return static_file("index.html", root=static_folder)
@route("/:file#.*[^/]#", method="GET")
def static(file):
global static_folder
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
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 ("-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):
host = "0.0.0.0"
if (port == None):
port = "8422"
run(host=host, port=port)
if __name__ == "__main__":
main()