-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlights_api.py
More file actions
executable file
·199 lines (171 loc) · 5.26 KB
/
lights_api.py
File metadata and controls
executable file
·199 lines (171 loc) · 5.26 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
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
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from pywizlight import wizlight
import subprocess
LIGHTS = "/home/pi/bin/lights"
app = FastAPI(title="Lights API")
class Cmd(BaseModel):
cmd: str
def run_lights(args):
p = subprocess.run([LIGHTS, *args], capture_output=True, text=True)
out = (p.stdout or "") + (p.stderr or "")
return p.returncode, out
@app.get("/health")
def health():
return {"ok": True}
@app.get("/status")
def status():
rc, out = run_lights(["status"])
return {"rc": rc, "out": out}
ALL_IPS = [
"192.168.86.123", # kitchen 1
"192.168.86.124", # kitchen 2
"192.168.86.133", # entryway 1
"192.168.86.134", # entryway 2
]
ROOM_BY_IP = {
"192.168.86.123": "kitchen",
"192.168.86.124": "kitchen",
"192.168.86.133": "entryway",
"192.168.86.134": "entryway",
}
@app.get("/status/json")
async def status_json():
bulbs = [wizlight(ip) for ip in ALL_IPS]
results = []
try:
for bulb in bulbs:
try:
state = await bulb.updateState()
on = state.get_state()
bri = state.get_brightness()
ct = state.get_colortemp()
rgb = state.get_rgb()
if rgb and all(v is None for v in rgb):
rgb = None
results.append({
"ip": bulb.ip,
"room": ROOM_BY_IP.get(bulb.ip),
"on": bool(on),
"brightness": bri,
"colortemp": ct,
"rgb": rgb,
})
except Exception:
results.append({
"ip": bulb.ip,
"room": ROOM_BY_IP.get(bulb.ip),
"on": None,
"error": "unreachable",
})
finally:
for bulb in bulbs:
await bulb.async_close()
return {"bulbs": results}
@app.post("/cmd")
def cmd(payload: Cmd):
args = payload.cmd.strip().split()
if not args:
raise HTTPException(400, "empty cmd")
rc, out = run_lights(args)
return {"rc": rc, "out": out}
@app.post("/preset/{name}")
def preset(name: str):
rc, out = run_lights([name])
return {"rc": rc, "out": out}
@app.post("/off")
def off():
rc, out = run_lights(["off"])
return {"rc": rc, "out": out}
VALID_ROOMS = {"kitchen", "entryway", "all"}
@app.post("/room/{room}/toggle")
def room_toggle(room: str):
if room not in VALID_ROOMS:
raise HTTPException(404, f"Unknown room: {room}")
rc, out = run_lights([room, "toggle"])
return {"rc": rc, "out": out}
@app.post("/room/{room}/on")
def room_on(room: str):
if room not in VALID_ROOMS:
raise HTTPException(404, f"Unknown room: {room}")
rc, out = run_lights([room, "on"])
return {"rc": rc, "out": out}
@app.post("/room/{room}/off")
def room_off(room: str):
if room not in VALID_ROOMS:
raise HTTPException(404, f"Unknown room: {room}")
rc, out = run_lights([room, "off"])
return {"rc": rc, "out": out}
@app.post("/room/{room}/preset/{name}")
def room_preset(room: str, name: str):
if room not in VALID_ROOMS:
raise HTTPException(404, f"Unknown room: {room}")
rc, out = run_lights([room, name])
return {"rc": rc, "out": out}
@app.post("/fade/{name}/{seconds}")
def fade(name: str, seconds: float):
rc, out = run_lights(["fade", name, str(seconds)])
return {"rc": rc, "out": out}
@app.post("/alert/{seconds}")
def alert(seconds: float = 15):
rc, out = run_lights(["alert", str(seconds)])
return {"rc": rc, "out": out}
@app.post("/alert/police/{seconds}")
def alert_police(seconds: float = 15):
rc, out = run_lights(["alert-police", str(seconds)])
return {"rc": rc, "out": out}
@app.post("/alert/pulse/{seconds}")
def alert_pulse(seconds: float = 15):
rc, out = run_lights(["alert-pulse", str(seconds)])
return {"rc": rc, "out": out}
from fastapi.responses import HTMLResponse
UI_HTML = """
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Lights</title>
<style>
body { font-family: sans-serif; background:#111; color:#eee; padding:20px }
button { margin:4px; padding:10px 14px; font-size:16px }
input { width:120px }
pre { background:#000; padding:10px }
</style>
</head>
<body>
<h2>Lights</h2>
<div>
<button onclick="cmd('warm')">Warm</button>
<button onclick="cmd('cool')">Cool</button>
<button onclick="cmd('night')">Night</button>
<button onclick="cmd('movie')">Movie</button>
<button onclick="cmd('off')">Off</button>
</div>
<h3>Fade</h3>
<input id="fadeSecs" type="number" value="10" min="1"> seconds
<button onclick="fade('night')">Fade to Night</button>
<h3>Status</h3>
<button onclick="status()">Refresh</button>
<pre id="out"></pre>
<script>
function cmd(name) {
fetch('/preset/' + name, {method:'POST'}).then(status)
}
function fade(name) {
const s = document.getElementById('fadeSecs').value
fetch(`/fade/${name}/${s}`, {method:'POST'}).then(status)
}
function status() {
fetch('/status/json').then(r=>r.json()).then(j=>{
document.getElementById('out').textContent =
JSON.stringify(j, null, 2)
})
}
status()
</script>
</body>
</html>
"""
@app.get("/ui", response_class=HTMLResponse)
def ui():
return UI_HTML