-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_ui.py
More file actions
322 lines (270 loc) · 11 KB
/
web_ui.py
File metadata and controls
322 lines (270 loc) · 11 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
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
#!/usr/bin/env python3
from __future__ import annotations
import os
import shlex
import subprocess
import sys
import threading
import time
from dataclasses import dataclass
from typing import Optional
from flask import Flask, redirect, render_template_string, request, url_for
APP = Flask(__name__)
FIREPLACE_PY = os.path.join(os.path.dirname(__file__), "fireplace.py")
FIREPLACE_CLI_PYTHON = os.getenv("FIREPLACE_CLI_PYTHON", "python3")
@dataclass
class RunResult:
when: float
action: str
command: str
exit_code: Optional[int]
output: str
_lock = threading.Lock()
_last_result: Optional[RunResult] = None
_hold_proc: Optional[subprocess.Popen[str]] = None
_hold_cmd: Optional[str] = None
HTML = """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Fireplace Relay UI</title>
<style>
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif; margin: 24px; max-width: 900px; }
.row { display: flex; gap: 16px; flex-wrap: wrap; }
.card { border: 1px solid #ddd; border-radius: 10px; padding: 16px; }
label { display: block; font-size: 14px; margin-top: 10px; }
input[type=text], input[type=number] { padding: 8px; width: 220px; }
button { padding: 10px 14px; margin-right: 10px; margin-top: 10px; }
.mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; }
pre { background: #f6f8fa; padding: 12px; overflow: auto; border-radius: 8px; }
.small { font-size: 13px; color: #444; }
</style>
</head>
<body>
<h1>Fireplace Relay UI (local)</h1>
<p class="small">Controls <span class="mono">low_flame</span> via <span class="mono">fireplace.py</span>. Bind is local-only by default.</p>
<div class="row">
<div class="card" style="flex: 1 1 360px;">
<h2>Settings</h2>
<form method="post" action="{{ url_for('run_action') }}">
<label>Boot guard seconds (applies to ignite/on/off)</label>
<input type="number" step="0.1" name="boot_guard_seconds" value="{{ boot_guard_seconds }}" />
<label>Pulse ms (ignite)</label>
<input type="number" step="1" name="pulse_ms" value="{{ pulse_ms }}" />
<label>Hold seconds (optional, for Start Hold)</label>
<input type="number" step="0.1" name="hold_seconds" value="{{ hold_seconds }}" placeholder="blank = hold until Stop" />
<label style="margin-top: 12px;">
<input type="checkbox" name="dry_run" {% if dry_run %}checked{% endif %} /> Dry-run (no GPIO)
</label>
<label>
<input type="checkbox" name="active_low" {% if active_low %}checked{% endif %} /> Active-low (invert)
</label>
<div>
<button type="submit" name="action" value="ignite_pulse">Ignite Pulse (low_flame)</button>
<button type="submit" name="action" value="start_hold">Start Hold (low_flame)</button>
<button type="submit" name="action" value="stop">Stop (open)</button>
</div>
</form>
<h3>Status</h3>
<div class="small">
Hold process: {% if hold_running %}<b>RUNNING</b>{% else %}not running{% endif %}
</div>
{% if hold_cmd %}
<div class="small">Command: <span class="mono">{{ hold_cmd }}</span></div>
{% endif %}
</div>
<div class="card" style="flex: 1 1 460px;">
<h2>Last Result</h2>
{% if last %}
<div class="small">Action: <span class="mono">{{ last.action }}</span></div>
<div class="small">Exit: <span class="mono">{{ last.exit_code }}</span></div>
<div class="small">Command: <span class="mono">{{ last.command }}</span></div>
<pre class="mono">{{ last.output }}</pre>
{% else %}
<div class="small">No commands run yet.</div>
{% endif %}
</div>
</div>
</body>
</html>
"""
def _build_base_args() -> list[str]:
# IMPORTANT: default to system python for GPIO access.
# The dev web server may run in a venv without GPIO pin-factory backends.
return [FIREPLACE_CLI_PYTHON, FIREPLACE_PY]
def _add_common_after_subcommand(
argv: list[str], *, boot_guard_seconds: str, dry_run: bool, active_low: bool
) -> list[str]:
# fireplace.py defines these as subcommand options (via argparse parents),
# so they must appear AFTER the subcommand name.
if boot_guard_seconds.strip() != "":
argv += ["--boot-guard-seconds", boot_guard_seconds]
if dry_run:
argv.append("--dry-run")
if active_low:
argv.append("--active-low")
return argv
def _cli_env() -> dict[str, str]:
env = dict(os.environ)
# Keep CLI colors off for captured output (web view).
env["FIREPLACE_COLOR"] = "never"
env["NO_COLOR"] = "1"
return env
def _run_sync(action: str, argv: list[str]) -> RunResult:
started = time.time()
cmd_str = " ".join(shlex.quote(a) for a in argv)
try:
cp = subprocess.run(argv, capture_output=True, text=True, timeout=60, env=_cli_env())
out = (cp.stdout or "") + (cp.stderr or "")
return RunResult(when=started, action=action, command=cmd_str, exit_code=cp.returncode, output=out.strip())
except Exception as e:
return RunResult(when=started, action=action, command=cmd_str, exit_code=None, output=f"ERROR: {e}")
def _stop_hold_locked() -> RunResult:
global _hold_proc, _hold_cmd
started = time.time()
if _hold_proc is None or _hold_proc.poll() is not None:
_hold_proc = None
_hold_cmd = None
return RunResult(when=started, action="stop", command="(no hold process)", exit_code=0, output="Hold process was not running.")
proc = _hold_proc
cmd = _hold_cmd or "(unknown)"
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)
_hold_proc = None
_hold_cmd = None
return RunResult(
when=started,
action="stop",
command=cmd,
exit_code=0,
output="Stopped hold process (sent terminate/kill as needed).",
)
@APP.get("/")
def index():
with _lock:
hold_running = _hold_proc is not None and _hold_proc.poll() is None
hold_cmd = _hold_cmd
last = _last_result
# Defaults chosen for safety and convenience.
return render_template_string(
HTML,
boot_guard_seconds=request.args.get("boot_guard_seconds", "12"),
pulse_ms=request.args.get("pulse_ms", "250"),
hold_seconds=request.args.get("hold_seconds", ""),
dry_run=(request.args.get("dry_run", "") == "on"),
active_low=(request.args.get("active_low", "") == "on"),
hold_running=hold_running,
hold_cmd=hold_cmd,
last=last,
)
@APP.post("/run")
def run_action():
global _last_result, _hold_proc, _hold_cmd
action = (request.form.get("action") or "").strip()
boot_guard_seconds = request.form.get("boot_guard_seconds", "12")
pulse_ms = request.form.get("pulse_ms", "250")
hold_seconds = request.form.get("hold_seconds", "").strip()
dry_run = request.form.get("dry_run") == "on"
active_low = request.form.get("active_low") == "on"
if action == "ignite_pulse":
argv = _build_base_args() + ["ignite"]
argv = _add_common_after_subcommand(
argv, boot_guard_seconds=boot_guard_seconds, dry_run=dry_run, active_low=active_low
)
argv += ["--main-relay", "low_flame", "--pulse-ms", pulse_ms]
result = _run_sync("ignite_pulse", argv)
with _lock:
_last_result = result
elif action == "start_hold":
with _lock:
# If already running, do nothing.
if _hold_proc is not None and _hold_proc.poll() is None:
_last_result = RunResult(
when=time.time(),
action="start_hold",
command=_hold_cmd or "(unknown)",
exit_code=0,
output="Hold process already running.",
)
else:
argv = _build_base_args() + ["on"]
argv = _add_common_after_subcommand(
argv, boot_guard_seconds=boot_guard_seconds, dry_run=dry_run, active_low=active_low
)
argv += ["--main-relay", "low_flame"]
if hold_seconds != "":
argv += ["--hold-seconds", hold_seconds]
cmd_str = " ".join(shlex.quote(a) for a in argv)
try:
_hold_proc = subprocess.Popen(
argv,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
env=_cli_env(),
)
_hold_cmd = cmd_str
_last_result = RunResult(
when=time.time(),
action="start_hold",
command=cmd_str,
exit_code=None,
output="Started hold process. Use Stop to open the relay.",
)
except Exception as e:
_hold_proc = None
_hold_cmd = None
_last_result = RunResult(
when=time.time(),
action="start_hold",
command=cmd_str,
exit_code=None,
output=f"ERROR starting hold: {e}",
)
elif action == "stop":
with _lock:
result = _stop_hold_locked()
_last_result = result
# Also ensure we actively open the relay via CLI (belt + suspenders).
argv = _build_base_args() + ["off"]
argv = _add_common_after_subcommand(
argv, boot_guard_seconds=boot_guard_seconds, dry_run=dry_run, active_low=active_low
)
argv += ["--main-relay", "low_flame"]
sync = _run_sync("off", argv)
with _lock:
_last_result = RunResult(
when=time.time(),
action="stop",
command=f"{result.command}\n{sync.command}",
exit_code=sync.exit_code,
output=(result.output + "\n" + (sync.output or "")).strip(),
)
else:
with _lock:
_last_result = RunResult(when=time.time(), action="unknown", command="", exit_code=1, output="Unknown action")
# Preserve current form settings in query string for convenience.
return redirect(
url_for(
"index",
boot_guard_seconds=boot_guard_seconds,
pulse_ms=pulse_ms,
hold_seconds=hold_seconds,
dry_run=("on" if dry_run else ""),
active_low=("on" if active_low else ""),
)
)
def main() -> int:
host = os.getenv("FIREPLACE_WEB_HOST", "127.0.0.1")
port = int(os.getenv("FIREPLACE_WEB_PORT", "8080"))
debug = os.getenv("FIREPLACE_WEB_DEBUG", "").strip().lower() in {"1", "true", "yes", "y"}
APP.run(host=host, port=port, debug=debug)
return 0
if __name__ == "__main__":
raise SystemExit(main())