-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
234 lines (199 loc) · 6.51 KB
/
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
import os
import time
import logging
import webcolors
import secrets
import uvicorn
from typing import Annotated
from fastapi import FastAPI, Request, Depends, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.responses import (
RedirectResponse,
)
from blinkstick_python.blinkstick import blinkstick
import colorlog
class ColoredFormatter(colorlog.ColoredFormatter):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.converter = time.gmtime
logging.config.fileConfig('logging.conf', disable_existing_loggers=False)
logger = logging.getLogger(__name__)
bs = blinkstick.find_first()
app = FastAPI(
title="BlickStick-Square API Server",
summary="RESTful API server to control the BlinkStick Square",
redoc_url=None
)
default_username = os.getenv("BS_SQ_API_USERNAME")
if default_username is None:
default_username = 'admin'
logger.warning(f"Username empty, set to '{default_username}'")
default_username_bytes = default_username.encode("UTF-8")
default_password = os.getenv("BS_SQ_API_PASSWORD")
if default_password is None:
default_password = secrets.token_hex(16)
logger.warning(f"Password empty, set random for '{default_username}'")
default_password_bytes = default_password.encode("UTF-8")
security = HTTPBasic()
def check_login(
credentials: Annotated[HTTPBasicCredentials, Depends(security)]
):
current_username_bytes = credentials.username.encode("utf8")
is_correct_username = secrets.compare_digest(
current_username_bytes, default_username_bytes
)
current_password_bytes = credentials.password.encode("utf8")
is_correct_password = secrets.compare_digest(
current_password_bytes, default_password_bytes
)
if is_correct_username and is_correct_password:
logging.info(f"user '{credentials.username}' authenticated")
return credentials.username
else:
logging.error(f"user '{credentials.username}' authentication failed")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:8000",
"*"
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
def color_to_hex(color):
return webcolors.name_to_hex(color)
def color_from_hex(hex):
return webcolors.hex_to_name(hex)
@app.get("/", include_in_schema=False)
def root():
response = RedirectResponse(url='/docs#')
return response
@app.get("/color")
def color(
username: Annotated[HTTPBasicCredentials, Depends(check_login)] = None
):
if username is None:
return {"error": "not authenticated"}
if bs is None:
return {"error": "no device found"}
try:
hex = bs.get_color(color_format="hex")
name = color_from_hex(hex)
logger.info(f'name: {name}, hex: {hex}')
return {"result": {"name": name, "hex": hex}}
except Exception as e:
logger.error(str(e))
return {"result": False}
@app.get("/on")
def on(
color: Annotated[str, "HTML Color"] = "green",
username: Annotated[HTTPBasicCredentials, Depends(check_login)] = None
):
if username is None:
return {"error": "not authenticated"}
if bs is None:
return {"error": "no device found"}
try:
hex = color_to_hex(color)
bs.set_color(hex=hex)
logger.info(f'name: {color}, hex: {hex}')
return {"result": True}
except Exception as e:
logger.error(str(e))
return {"result": False}
@app.get("/off")
def off(
username: Annotated[HTTPBasicCredentials, Depends(check_login)] = None
):
if username is None:
return {"error": "not authenticated"}
if bs is None:
return {"error": "no device found"}
try:
bs.turn_off()
logger.info('turned off')
return {"result": True}
except Exception as e:
logger.error(str(e))
return {"result": False}
@app.get("/pulse")
def pulse(
color: str = "blue",
duration: int = 1000,
steps: int = 50,
username: Annotated[HTTPBasicCredentials, Depends(check_login)] = None
):
if username is None:
return {"error": "not authenticated"}
if bs is None:
return {"error": "no device found"}
try:
hex = color_to_hex(color)
bs.pulse(hex=hex, duration=duration, steps=steps)
logger.info(f"pulsed in {color} for {duration}ms in {steps} steps")
return {"result": True}
except Exception as e:
logger.error(str(e))
return {"result": False}
@app.get("/blink")
def blink(
color: str = "green",
delay: int = 500,
repeats: int = 3,
username: Annotated[HTTPBasicCredentials, Depends(check_login)] = None
):
if username is None:
return {"error": "not authenticated"}
if bs is None:
return {"error": "no device found"}
try:
hex = color_to_hex(color)
bs.blink(hex=hex, delay=delay, repeats=repeats)
logger.info(f"blinked in {color} for {delay}ms {repeats} times")
return {"result": True}
except Exception as e:
logger.error(str(e))
return {"result": False}
@app.get("/morph")
def morph(
color: str = "yellow",
duration: int = 6000,
steps: int = 100,
username: Annotated[HTTPBasicCredentials, Depends(check_login)] = None
):
if username is None:
return {"error": "not authenticated"}
if bs is None:
return {"error": "no device found"}
try:
hex = color_to_hex(color)
bs.morph(hex=hex, duration=duration, steps=steps)
logger.info(f"morphed to {color} in {duration}ms in {steps} steps")
return {"result": True}
except Exception as e:
logger.error(str(e))
return {"result": False}
if __name__ == "__main__":
logger.info(f"Started by python ({__name__})")
host = "0.0.0.0"
port = "8000"
logger.info(f"Running uvicorn on {host}:{port}")
uvicorn.run(app,
host=host,
port=port,
log_config="logging.conf",
use_colors=False)