-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebserver.py
169 lines (116 loc) · 4.06 KB
/
webserver.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
import json
import os
import redis
from flask import Flask, render_template, request
from light_emitting_desk.desk import Desk
from light_emitting_desk.utils import conf
app = Flask(__name__)
app.redis = redis.Redis()
desk_conf = conf["sectors"]
if "TEST_SECTORS" in os.environ:
desk_conf = json.loads(os.environ["TEST_SECTORS"])
app.desk = Desk(desk_conf)
mode_names = list(map(lambda x: x["name"], conf["modes"]))
@app.route("/", methods=["GET"])
def index():
"""Root endpoint."""
if request.accept_mimetypes["text/html"]:
return render_template(
"index.html",
title="LED",
imports=conf["web"]["imports"],
modes=conf["modes"],
)
return {"status": "OK"}
@app.route("/desk/light", methods=["POST"])
def set_colour():
"""Light the desk."""
app.data = validate_request(request)
if "invalid" in app.data:
return {"error": app.data["invalid"]}, 422
return enqueue_and_return(app.data)
@app.route("/desk/off", methods=["POST"])
def switch_off():
"""Instantly turn it all off."""
app.redis.flushall()
colour = [0, 0, 0]
app.data = {"colour": colour, "mode": "sector-diverge"}
return enqueue_and_return(app.data)
@app.route("/desk/colour", methods=["GET"])
def current_desk_colour():
"""Return the desk's colour."""
try:
colour = json.loads(app.redis.get("colours/desk"))
return {"colour": colour, "status": "OK"}
except TypeError:
return {"error": "no data for that"}, 404
def enqueue_and_return(data):
"""Light the lights."""
app.redis.rpush("jobs", json.dumps(data))
app.redis.set("colours/desk", json.dumps(data["colour"]))
return {"colour": data["colour"], "status": "OK"}
# validators
def validate_request(req):
"""Validate the request data."""
mandatory_fields = conf["api"]["mandatory-fields"]
optional_fields = conf["api"]["optional-fields"]
if not req.content_length:
return {"invalid": "no data"}
data = req.get_json()
for field in mandatory_fields:
if field not in data:
data["invalid"] = f"`{field}` must be supplied"
return data
invalid = globals()[f"invalid_{field}"](data[field])
if invalid:
data["invalid"] = invalid
return data
for field, default in optional_fields.items():
try:
invalid = globals()[f"invalid_{field.replace('-', '_')}"](data[field])
if invalid:
data["invalid"] = invalid
return data
except KeyError:
data[field] = default
return data
def invalid_colour(colour):
"""Validate the RGB colour."""
error_message = f"`{colour}` is not a valid RGB colour"
if not isinstance(colour, list):
return error_message
if not all([0 <= component <= 255 for component in colour]):
return error_message
return False
def invalid_mode(mode):
"""Validate the mode."""
valid_modes = list(map(lambda x: x["name"], conf["modes"]))
if mode not in valid_modes:
return f"`{mode}` is not a recognised mode"
return False
def invalid_delay(delay):
"""Validate the interval."""
try:
int(delay)
except ValueError:
return f"`{delay}` is not a valid delay interval"
def invalid_direction(direction):
"""Validate the `direction` parameter."""
valid_directions = ["forwards", "backwards"]
if direction not in valid_directions:
return f"`direction` must be one of [{', '.join(valid_directions)}]"
return False
def invalid_caterpillar_length(length):
"""Validate the `caterpillar-length` parameter."""
try:
length = int(length)
except ValueError:
return "`caterpillar-length` must be something that can be cast to an `int`"
if not 1 <= length <= len(app.desk.indeces):
return (
"`caterpillar-length` must be a number between "
f"1 and {len(app.desk.indeces)}"
)
return False
if __name__ == "__main__": # nocov
app.run(host="0.0.0.0", debug=True)