-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathechoServer.py
More file actions
88 lines (73 loc) · 3.13 KB
/
echoServer.py
File metadata and controls
88 lines (73 loc) · 3.13 KB
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
import web
import redis
import json
db = redis.StrictRedis(host='localhost', port=4747, db=0)
urls = (
'/api', 'new_user',
'/api/(.+)', 'api_access'
)
class EchoServer(web.application):
def run(self, port=8080, *middleware):
func = self.wsgifunc(*middleware)
return web.httpserver.runsimple(func, ('0.0.0.0', port))
# For complete functionality, need to implement new user
class new_user:
def POST(self):
data = web.data()
response = "{'test': 'hello'}"
return response
class api_access:
def POST(self, name):
return format(name)
def GET(self, name):
if "lights/" in name:
id = name.rsplit("/", 1)[-1]
device = db.get("hue_" + str(id))
state = db.get(device).lower()
response = "{\"state\": {\"on\": " + state + ", \"bri\": 0, \"alert\": \"none\",\"effect\": \"none\"," + \
"\"reachable\": true }, \"type\": \"Dimmable light\",\"name\": \"" + device + "\"" + \
",\"modelid\": \"LWB004\",\"swversion\": \"66012040\"}"
else:
web_sensor_lookup = {}
sensor_id = 1
sensors = db.lrange("sensors", 0, -1)
for sensor in sensors:
sensor = json.loads(sensor)
if sensor["type"] in ["zwave", "wifi"] and sensor["function"] in ["switch", "dimmer", "curtain", "screen"]:
web_sensor_lookup[str(sensor_id)] = sensor["name"]
db.set("hue_" + str(sensor_id), sensor["name"])
sensor_id += 1
response = "{"
for id, sensor in web_sensor_lookup.iteritems():
response += "\"" + id + "\":{\"state\": {\"on\": false,\"bri\": 0,\"alert\":\"none\",\"effect\":" + \
"\"none\",\"reachable\": true},\"type\": \"Dimmable light\",\"name\":\"" + sensor + \
"\",\"modelid\": \"LWB004\", \"swversion\": \"66012040\" },"
response = response[:-1]
response += "}"
return response
def PUT(self, name):
name = name[:-6]
id = name.rsplit("/", 1)[-1]
data = web.data()
bright_adjust = False
response = "["
try:
bright = json.loads(data)["bri"]
response += "{\"success\":{\"/lights/" + str(id) + "/state/bri\":" + str(bright) + "}},"
bright_adjust = True
except:
pass
try:
state = json.loads(data)["on"]
response += "{\"success\":{\"/lights/" + str(id) + "/state/on\":" + str(state).lower() + "}}"
except:
pass
response += "]"
if bright_adjust:
state = int((bright/254.0)*100.0)
db.lpush("sensor_changes", "{\"name\": \"" + db.get("hue_" + str(id)) + "\", \"state\": \"" + str(state) + "\"}")
response = "[{\"success\":{\"/lights/" + str(id) + "/state/on\":" + str(state).lower() + "}}]"
return response
if __name__ == "__main__":
app = EchoServer(urls, globals())
app.run()