as flask without docker

This commit is contained in:
2026-09-06 15:53:58 +02:00
parent b7f98c2ccf
commit 1e18920ec6
8 changed files with 164 additions and 165 deletions
+65 -83
View File
@@ -1,17 +1,35 @@
from __future__ import annotations
import html
import logging
import os
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlencode, urlparse
from io import BytesIO
from flask import Flask, Response, abort, render_template_string, request, send_file, url_for
from .collector import Collector, HueClient, Settings
from .rrd_store import RRDStore
LOG = logging.getLogger("hue-collector")
PERIODS = ("6h", "24h", "7d", "30d")
PAGE = '''<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="refresh" content="60">
<title>Hue history</title><style>
:root{color-scheme:dark;font-family:system-ui,sans-serif}body{margin:auto;max-width:1200px;padding:1rem;background:#0b1220;color:#e5e7eb}
header{display:flex;gap:1rem;align-items:center;justify-content:space-between;flex-wrap:wrap}nav a{padding:.45rem .7rem;color:#93c5fd;text-decoration:none}
nav a.active{background:#1d4ed8;color:white;border-radius:.35rem}.status,p{color:#9ca3af}section{background:#111827;border:1px solid #374151;border-radius:.6rem;padding:.75rem;margin:1rem 0}
h1,h2{margin:.25rem 0 .5rem}h2{font-size:1.1rem}p{margin:.25rem 0}.error{color:#fca5a5}img{display:block;width:100%;height:auto}
</style></head><body><header><div><h1>Philips Hue</h1><div class="status">{{ status }}{% if error %} — <span class="error">{{ error }}</span>{% endif %}</div></div>
<nav>{% for value in periods %}<a class="{{ 'active' if value == period else '' }}" href="{{ url_for('dashboard', range=value) }}">{{ value }}</a>{% endfor %}</nav></header>
<h1>Rooms and zones</h1>{% for item in groups %}<section><h2>{{ item.type|title }}: {{ item.name }}</h2>
<img loading="lazy" src="{{ url_for('graph', kind='group', item_id=item.id, range=period) }}" alt="Light history"></section>
{% else %}<p>No groups collected yet.</p>{% endfor %}
<h1>Sensors</h1>{% for item in sensors %}<section><h2>{{ item.name }}</h2>
<p>{{ item.room or item.zones or 'No room' }} · {% if item.value is none %}unavailable{% else %}{{ '%.1f'|format(item.value) }} {{ item.unit }}{% endif %}</p>
<img loading="lazy" src="{{ url_for('graph', kind='sensor', item_id=item.id, range=period) }}" alt="Sensor history"></section>
{% else %}<p>No sensors collected yet.</p>{% endfor %}</body></html>'''
class State:
@@ -37,93 +55,57 @@ def collection_loop(collector: Collector, store: RRDStore, state: State, interva
time.sleep(max(1, interval - (time.monotonic() - started)))
def page(state: State, period: str) -> bytes:
with state.lock:
snapshot = state.snapshot
last_success = state.last_success
error = state.error
status = f"Last update: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(last_success))}" if last_success else "Waiting for first collection"
if error:
status += f" — Error: {html.escape(error)}"
controls = " ".join(
f'<a class="{("active" if value == period else "")}" href="/?range={value}">{value}</a>'
for value in ("6h", "24h", "7d", "30d")
)
group_cards = []
for item in sorted(snapshot["groups"], key=lambda value: (value["type"], value["name"].lower())):
query = urlencode({"kind": "group", "id": item["id"], "range": period})
group_cards.append(
f'<section><h2>{html.escape(item["type"].title())}: {html.escape(item["name"])}</h2>'
f'<img loading="lazy" src="/graph?{query}" alt="Light history"></section>'
)
sensor_cards = []
for item in sorted(snapshot["sensors"], key=lambda value: (value["type"], value["name"].lower())):
query = urlencode({"kind": "sensor", "id": item["id"], "range": period})
value = "unavailable" if item["value"] is None else f'{item["value"]:.1f} {item["unit"]}'
location = item["room"] or item["zones"] or "No room"
sensor_cards.append(
f'<section><h2>{html.escape(item["name"])}</h2><p>{html.escape(location)} · {html.escape(value)}</p>'
f'<img loading="lazy" src="/graph?{query}" alt="Sensor history"></section>'
)
document = f'''<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="refresh" content="60">
<title>Hue history</title><style>
:root{{color-scheme:dark;font-family:system-ui,sans-serif}}body{{margin:auto;max-width:1200px;padding:1rem;background:#0b1220;color:#e5e7eb}}
header{{display:flex;gap:1rem;align-items:center;justify-content:space-between;flex-wrap:wrap}}nav a{{padding:.45rem .7rem;color:#93c5fd;text-decoration:none}}
nav a.active{{background:#1d4ed8;color:white;border-radius:.35rem}}.status,p{{color:#9ca3af}}section{{background:#111827;border:1px solid #374151;border-radius:.6rem;padding:.75rem;margin:1rem 0}}
h1,h2{{margin:.25rem 0 .5rem}}h2{{font-size:1.1rem}}p{{margin:.25rem 0}}img{{display:block;width:100%;height:auto}}
</style></head><body><header><div><h1>Philips Hue</h1><div class="status">{status}</div></div><nav>{controls}</nav></header>
<h1>Rooms and zones</h1>{''.join(group_cards) or '<p>No groups collected yet.</p>'}
<h1>Sensors</h1>{''.join(sensor_cards) or '<p>No sensors collected yet.</p>'}</body></html>'''
return document.encode()
def create_app(settings: Settings | None = None, *, start_collector: bool = True) -> Flask:
settings = settings or Settings.from_env()
app = Flask(__name__)
state = State()
store = RRDStore(settings.data_dir, settings.interval)
app.extensions["hue_state"] = state
app.extensions["hue_rrd_store"] = store
if start_collector:
collector = Collector(HueClient(settings))
threading.Thread(target=collection_loop, args=(collector, store, state, settings.interval), daemon=True).start()
def handler_for(state: State, store: RRDStore):
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
parsed = urlparse(self.path)
query = parse_qs(parsed.query)
if parsed.path == "/":
body, status, content_type = page(state, query.get("range", ["24h"])[0]), 200, "text/html; charset=utf-8"
elif parsed.path == "/healthz":
with state.lock:
healthy = state.last_success is not None
body, status, content_type = (b"ok\n", 200, "text/plain") if healthy else (b"not ready\n", 503, "text/plain")
elif parsed.path == "/graph":
try:
kind, item_id = query["kind"][0], query["id"][0]
if kind not in {"group", "sensor"}:
raise ValueError("unknown graph kind")
with state.lock:
collection = state.snapshot["groups" if kind == "group" else "sensors"]
item = next(value for value in collection if value["id"] == item_id)
body = store.graph(kind, item, query.get("range", ["24h"])[0])
status, content_type = 200, "image/png"
except (KeyError, ValueError, StopIteration, FileNotFoundError) as exc:
body, status, content_type = f"graph not found: {exc}\n".encode(), 404, "text/plain"
except Exception as exc:
LOG.exception("Graph rendering failed")
body, status, content_type = f"graph error: {exc}\n".encode(), 500, "text/plain"
else:
body, status, content_type = b"not found\n", 404, "text/plain"
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
@app.get("/")
def dashboard():
period = request.args.get("range", "24h")
if period not in PERIODS:
period = "24h"
with state.lock:
groups = sorted(state.snapshot["groups"], key=lambda item: (item["type"], item["name"].lower()))
sensors = sorted(state.snapshot["sensors"], key=lambda item: (item["type"], item["name"].lower()))
last_success, error = state.last_success, state.error
status = time.strftime("Last update: %Y-%m-%d %H:%M:%S", time.localtime(last_success)) if last_success else "Waiting for first collection"
return render_template_string(PAGE, groups=groups, sensors=sensors, status=status, error=error, periods=PERIODS, period=period)
def log_message(self, fmt, *args):
LOG.debug(fmt, *args)
@app.get("/graph/<kind>/<item_id>.png")
def graph(kind: str, item_id: str):
if kind not in {"group", "sensor"}:
abort(404)
with state.lock:
collection = state.snapshot["groups" if kind == "group" else "sensors"]
item = next((value for value in collection if value["id"] == item_id), None)
if item is None:
abort(404)
try:
image = store.graph(kind, item, request.args.get("range", "24h"))
except (ValueError, FileNotFoundError):
abort(404)
return send_file(BytesIO(image), mimetype="image/png", max_age=30)
return Handler
@app.get("/healthz")
def health():
with state.lock:
healthy = state.last_success is not None
return Response("ok\n" if healthy else "not ready\n", status=200 if healthy else 503, mimetype="text/plain")
return app
def main() -> None:
logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO"), format="%(asctime)s %(levelname)s %(message)s")
settings = Settings.from_env()
state = State()
store = RRDStore(settings.data_dir, settings.interval)
collector = Collector(HueClient(settings))
threading.Thread(target=collection_loop, args=(collector, store, state, settings.interval), daemon=True).start()
app = create_app(settings)
LOG.info("Serving Hue dashboard on http://%s:%s", settings.listen_host, settings.listen_port)
ThreadingHTTPServer((settings.listen_host, settings.listen_port), handler_for(state, store)).serve_forever()
app.run(host=settings.listen_host, port=settings.listen_port, debug=False, use_reloader=False)