app.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  1. """Nutikodu andmete veebiliides (FastAPI).
  2. Loeb ClickHouse'i `uus67` skeemist (zigbee andurid) ja serveerib:
  3. GET / -> veebirakendus (static/index.html)
  4. GET /api/meta -> seadmed, tz, andmete ulatus
  5. GET /api/temperatuur -> aegrida (temp + niiskus), agg=hour|day
  6. GET /api/ukseandur -> ukseolekute sündmused (tulevikuks)
  7. GET /api/vead -> häirete sündmused (tulevikuks)
  8. GET /api/latest -> viimased väärtused + lahtised häired
  9. GET /health
  10. ClickHouse'i päringud kasutavad `zigbee` kasutajat (SELECT uus67.*) ja
  11. `param_*` parameetreid (SQL-süst välistatud). Tulemused loetakse
  12. `FORMAT JSONEachRow` kujul (üks JSON-objekt rea kohta).
  13. Valikuline kaitse: WEB_ACCESS_TOKEN keskkonnamuutuja (tühi = kaitseta).
  14. """
  15. from __future__ import annotations
  16. import asyncio
  17. import hmac
  18. import html
  19. import secrets
  20. import json
  21. import os
  22. import re
  23. import threading
  24. import time
  25. from collections import defaultdict
  26. from datetime import datetime, timedelta
  27. from pathlib import Path
  28. from zoneinfo import ZoneInfo
  29. import color
  30. import paho.mqtt.client as mqtt
  31. import requests
  32. from fastapi import Body, Depends, FastAPI, Form, HTTPException, Query, Request
  33. from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse
  34. from fastapi.staticfiles import StaticFiles
  35. from starlette.middleware.sessions import SessionMiddleware
  36. ROOT = Path(__file__).parent
  37. STATIC_DIR = ROOT / "static"
  38. TZ = ZoneInfo("Europe/Tallinn")
  39. CH_URL = os.environ.get("CH_URL", "http://clickhouse:8123").rstrip("/")
  40. CH_USER = os.environ.get("CH_USER", "zigbee")
  41. CH_PASS = os.environ.get("CH_PASS", "")
  42. CH_DB = os.environ.get("CH_DB", "uus67")
  43. # Värvisensori juhtimine (MQTT, edge broker). OFF peatab ESP32 publitseerimise
  44. # -> ClickHouse'i ei kirjutata.
  45. VARV_MQTT_HOST = os.environ.get("VARV_MQTT_HOST", "")
  46. VARV_MQTT_PORT = int(os.environ.get("VARV_MQTT_PORT", "8883"))
  47. VARV_MQTT_TLS = os.environ.get("VARV_MQTT_TLS", "true").strip().lower() in ("1", "true", "yes", "on")
  48. VARV_MQTT_USER = os.environ.get("VARV_MQTT_USER", "")
  49. VARV_MQTT_PASS = os.environ.get("VARV_MQTT_PASS", "")
  50. VARV_CMD_TOPIC = os.environ.get("VARV_CMD_TOPIC", "varvus/switch/sensor/command")
  51. VARV_STATE_TOPIC = os.environ.get("VARV_STATE_TOPIC", "varvus/switch/sensor/state")
  52. VARV_BANDS = ("f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8")
  53. VARV_CALIB_FIELDS = VARV_BANDS + ("clear", "nir")
  54. VARV_CALIB_TABLE = os.environ.get("VARV_CALIB_TABLE", "varvus_calib")
  55. WEB_ACCESS_TOKEN = os.environ.get("WEB_ACCESS_TOKEN", "")
  56. WEB_PASSWORD = os.environ.get("WEB_PASSWORD", "")
  57. WEB_SECRET_KEY = os.environ.get("WEB_SECRET_KEY", "") or secrets.token_hex(32)
  58. HA_URL = os.environ.get("HA_URL", "http://100.87.1.24:8123").rstrip("/")
  59. HA_TOKEN = os.environ.get("HA_TOKEN", "")
  60. AWAY_ENTITY = os.environ.get("AWAY_ENTITY", "input_boolean.kodust_eemal")
  61. SESSION_MAX_AGE = int(os.environ.get("SESSION_MAX_AGE", "604800"))
  62. LOGIN_MAX_ATTEMPTS = int(os.environ.get("LOGIN_MAX_ATTEMPTS", "5"))
  63. LOGIN_WINDOW_SECONDS = int(os.environ.get("LOGIN_WINDOW_SECONDS", "300"))
  64. DEFAULT_RANGE_DAYS = 7
  65. MAX_RANGE_DAYS = 3660
  66. # --- Transport (bussid + praamid) ---
  67. BUS_GRAPHQL = os.environ.get(
  68. "BUS_GRAPHQL", "https://api.peatus.ee/routing/v1/routers/estonia/index/graphql"
  69. ).rstrip("/")
  70. BUS_STOPS = [s.strip() for s in os.environ.get(
  71. "BUS_STOPS", "estonia:24703,estonia:27213").split(",") if s.strip()]
  72. PRAAM_API = os.environ.get(
  73. "PRAAM_API", "https://www.praamid.ee/online/events").rstrip("/")
  74. RII_HOIATUS_URL = os.environ.get(
  75. "RII_HOIATUS_URL", "https://www.ilmateenistus.ee/ilm/prognoosid/hoiatused/"
  76. )
  77. TRANSPORT_TTL = int(os.environ.get("TRANSPORT_TTL", "60"))
  78. UA = "Mozilla/5.0 (compatible; Nutikodu-web/1.0)"
  79. PRAAM_DIRECTIONS = {"HR": "Heltermaa → Rohuküla", "RH": "Rohuküla → Heltermaa"}
  80. SHIP_NAMES = {"TI": "Tiiu", "LE": "Leiger", "RE": "Regu"}
  81. PRAAM_STATUS = {"CONFIRMED": "plaanipärane", "CANCELLED": "tühistatud", "SUSPENDED": "seisatud"}
  82. SEA_AREAS = ["Väinameri", "Hiiu maakond", "Lääne maakond"]
  83. WIND_TYPES = ["tugev tuul", "väga tugev tuul", "torm", "merehoiatus", "tugev tuul ja lained"]
  84. _cache: dict[str, tuple[float, object]] = {}
  85. _cache_lock = threading.Lock()
  86. def cached(key: str, ttl: int, producer):
  87. """Lihtne mälusisene TTL-vahemälu väliste API-de jaoks."""
  88. now = time.monotonic()
  89. with _cache_lock:
  90. hit = _cache.get(key)
  91. if hit and now - hit[0] < ttl:
  92. return hit[1]
  93. value = producer()
  94. with _cache_lock:
  95. _cache[key] = (time.monotonic(), value)
  96. return value
  97. app = FastAPI(title="Nutikodu", version="0.2.0")
  98. app.add_middleware(
  99. SessionMiddleware,
  100. secret_key=WEB_SECRET_KEY,
  101. https_only=False,
  102. same_site="lax",
  103. max_age=SESSION_MAX_AGE,
  104. )
  105. @app.middleware("http")
  106. async def add_no_cache(request: Request, call_next):
  107. """Staatika ja API ilma vahemäluta — muidu jääb brauserisse vana JS/HTML."""
  108. response = await call_next(request)
  109. path = request.url.path
  110. if (
  111. path == "/"
  112. or path.startswith("/api/")
  113. or path.endswith((".js", ".css", ".html", ".webmanifest", ".svg"))
  114. ):
  115. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  116. response.headers["Pragma"] = "no-cache"
  117. return response
  118. def ch_query(query: str, params: dict[str, str] | None = None) -> list[dict]:
  119. """Käivita ClickHouse'i päring ja tagasta read JSON-objektidena."""
  120. q = {"database": CH_DB, "query": f"{query} FORMAT JSONEachRow"}
  121. for key, value in (params or {}).items():
  122. q[f"param_{key}"] = value
  123. try:
  124. resp = requests.post(
  125. f"{CH_URL}/",
  126. params=q,
  127. auth=(CH_USER, CH_PASS),
  128. timeout=20,
  129. )
  130. except requests.RequestException as exc:
  131. raise HTTPException(status_code=502, detail=f"ClickHouse'i ühendus: {exc}") from exc
  132. if resp.status_code != 200:
  133. raise HTTPException(status_code=502, detail=f"ClickHouse: {resp.text.strip()[:400]}")
  134. text = resp.text.strip()
  135. if not text:
  136. return []
  137. try:
  138. return [json.loads(line) for line in text.splitlines() if line.strip()]
  139. except json.JSONDecodeError as exc:
  140. raise HTTPException(status_code=502, detail=f"ClickHouse'i vastus: {text[:200]}") from exc
  141. _login_failures: dict[str, list[float]] = defaultdict(list)
  142. _login_lock = threading.Lock()
  143. def client_ip(request: Request) -> str:
  144. forwarded = request.headers.get("x-forwarded-for")
  145. if forwarded:
  146. return forwarded.split(",")[0].strip()
  147. return request.client.host if request.client else "?"
  148. def retry_after_seconds(ip: str) -> int:
  149. now = time.monotonic()
  150. with _login_lock:
  151. history = [t for t in _login_failures.get(ip, []) if now - t < LOGIN_WINDOW_SECONDS]
  152. _login_failures[ip] = history
  153. if len(history) >= LOGIN_MAX_ATTEMPTS:
  154. return int(LOGIN_WINDOW_SECONDS - (now - history[0])) + 1
  155. return 0
  156. def register_login_failure(ip: str) -> None:
  157. with _login_lock:
  158. _login_failures[ip].append(time.monotonic())
  159. def reset_login_failures(ip: str) -> None:
  160. with _login_lock:
  161. _login_failures.pop(ip, None)
  162. def is_authed(request: Request) -> bool:
  163. """Kas päring on autenditud: Bearer token VÕI sessiooniküpsis."""
  164. auth = request.headers.get("authorization", "")
  165. if auth.lower().startswith("bearer "):
  166. token = auth[7:].strip()
  167. if WEB_ACCESS_TOKEN and secrets.compare_digest(token, WEB_ACCESS_TOKEN):
  168. return True
  169. try:
  170. if request.session.get("auth") is True:
  171. return True
  172. except Exception:
  173. pass
  174. return False
  175. def require_auth(request: Request) -> None:
  176. if not is_authed(request):
  177. raise HTTPException(
  178. status_code=401,
  179. detail="Autentimine nõutud (Bearer token või sisselogimine)",
  180. headers={"WWW-Authenticate": "Bearer"},
  181. )
  182. def parse_dt(value: str | None, default: datetime) -> str:
  183. """Võta vastu 'YYYY-MM-DD[ HH:MM[:SS]]' või ISO 'T'-eraldajaga."""
  184. if not value:
  185. return default.strftime("%Y-%m-%d %H:%M:%S")
  186. cleaned = value.strip().replace("T", " ")
  187. for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
  188. try:
  189. return datetime.strptime(cleaned, fmt).strftime("%Y-%m-%d %H:%M:%S")
  190. except ValueError:
  191. continue
  192. raise HTTPException(status_code=422, detail=f"Vigane kuupäev: {value}")
  193. def resolve_range(from_: str | None, to: str | None) -> tuple[str, str]:
  194. now = datetime.now(TZ)
  195. to_s = parse_dt(to, now)
  196. to_dt = datetime.strptime(to_s, "%Y-%m-%d %H:%M:%S")
  197. from_s = parse_dt(from_, to_dt - timedelta(days=DEFAULT_RANGE_DAYS))
  198. from_dt = datetime.strptime(from_s, "%Y-%m-%d %H:%M:%S")
  199. if from_dt > to_dt:
  200. raise HTTPException(status_code=422, detail="'from' peab olema enne 'to'")
  201. if (to_dt - from_dt).days > MAX_RANGE_DAYS:
  202. raise HTTPException(status_code=422, detail="Vahemik on liiga pikk")
  203. return from_s, to_s
  204. @app.get("/api/meta")
  205. async def meta() -> dict:
  206. devices = [row["device"] for row in ch_query(
  207. f"SELECT DISTINCT device FROM {CH_DB}.temperatuur ORDER BY device"
  208. )]
  209. bounds = ch_query(
  210. f"SELECT toString(min(hour)) AS min_hour, toString(max(hour)) AS max_hour, count() AS rows "
  211. f"FROM {CH_DB}.temperatuur"
  212. )
  213. first = bounds[0] if bounds else {"min_hour": None, "max_hour": None, "rows": 0}
  214. return {
  215. "tz": "Europe/Tallinn",
  216. "db": CH_DB,
  217. "devices": devices,
  218. "min": first["min_hour"],
  219. "max": first["max_hour"],
  220. "rows": first["rows"],
  221. "default_range_days": DEFAULT_RANGE_DAYS,
  222. }
  223. @app.get("/api/temperatuur")
  224. async def temperatuur(
  225. from_: str | None = Query(None, alias="from"),
  226. to: str | None = Query(None),
  227. device: str | None = Query(None),
  228. agg: str = Query("hour", pattern="^(hour|day)$"),
  229. ) -> dict:
  230. from_s, to_s = resolve_range(from_, to)
  231. params = {"from": from_s, "to": to_s}
  232. where = (
  233. f"hour BETWEEN toDateTime({{from:String}}, 'Europe/Tallinn') "
  234. f"AND toDateTime({{to:String}}, 'Europe/Tallinn')"
  235. )
  236. if device:
  237. where += " AND device = {device:String}"
  238. params["device"] = device
  239. if agg == "day":
  240. select = (
  241. "toUInt64(toUnixTimestamp(toStartOfDay(hour))) * 1000 AS t, device, "
  242. "round(avg(temperature), 2) AS temperature, round(avg(humidity), 2) AS humidity, "
  243. "max(taidetud) AS taidetud"
  244. )
  245. group = "GROUP BY t, device"
  246. else:
  247. select = (
  248. "toUInt64(toUnixTimestamp(hour)) * 1000 AS t, device, "
  249. "temperature, humidity, taidetud"
  250. )
  251. group = ""
  252. rows = ch_query(
  253. f"SELECT {select} FROM {CH_DB}.temperatuur WHERE {where} {group} ORDER BY t",
  254. params,
  255. )
  256. series: dict[str, dict] = {}
  257. for row in rows:
  258. s = series.setdefault(
  259. row["device"], {"t": [], "temperature": [], "humidity": [], "taidetud": []}
  260. )
  261. s["t"].append(int(row["t"]))
  262. s["temperature"].append(row["temperature"])
  263. s["humidity"].append(row["humidity"])
  264. s["taidetud"].append(bool(row.get("taidetud")))
  265. return {"from": from_s, "to": to_s, "agg": agg, "series": series}
  266. @app.get("/api/valisilm")
  267. async def valisilm(
  268. from_: str | None = Query(None, alias="from"),
  269. to: str | None = Query(None),
  270. agg: str = Query("hour", pattern="^(hour|day)$"),
  271. ) -> dict:
  272. from_s, to_s = resolve_range(from_, to)
  273. params = {"from": from_s, "to": to_s}
  274. where = (
  275. f"hour BETWEEN toDateTime({{from:String}}, 'Europe/Tallinn') "
  276. f"AND toDateTime({{to:String}}, 'Europe/Tallinn')"
  277. )
  278. if agg == "day":
  279. select = (
  280. "toUInt64(toUnixTimestamp(toStartOfDay(hour))) * 1000 AS t, "
  281. "round(avg(temperature), 2) AS temperature, round(avg(humidity), 2) AS humidity, "
  282. "round(avg(wind), 2) AS wind, round(sum(rain), 2) AS rain, max(taidetud) AS taidetud"
  283. )
  284. group = "GROUP BY t"
  285. else:
  286. select = (
  287. "toUInt64(toUnixTimestamp(hour)) * 1000 AS t, "
  288. "temperature, humidity, wind, rain, taidetud"
  289. )
  290. group = ""
  291. rows = ch_query(
  292. f"SELECT {select} FROM {CH_DB}.valisilm FINAL WHERE {where} {group} ORDER BY t",
  293. params,
  294. )
  295. series: dict[str, list] = {
  296. "t": [],
  297. "temperature": [],
  298. "humidity": [],
  299. "wind": [],
  300. "rain": [],
  301. "taidetud": [],
  302. }
  303. for row in rows:
  304. series["t"].append(int(row["t"]))
  305. series["temperature"].append(row["temperature"])
  306. series["humidity"].append(row["humidity"])
  307. series["wind"].append(row["wind"])
  308. series["rain"].append(row["rain"])
  309. series["taidetud"].append(bool(row.get("taidetud")))
  310. return {"from": from_s, "to": to_s, "agg": agg, "series": series}
  311. @app.get("/api/ukseandur", dependencies=[Depends(require_auth)])
  312. async def ukseandur(
  313. from_: str | None = Query(None, alias="from"),
  314. to: str | None = Query(None),
  315. device: str | None = Query(None),
  316. ) -> dict:
  317. from_s, to_s = resolve_range(from_, to)
  318. params = {"from": from_s, "to": to_s}
  319. where = (
  320. f"ts BETWEEN toDateTime({{from:String}}, 'Europe/Tallinn') "
  321. f"AND toDateTime({{to:String}}, 'Europe/Tallinn')"
  322. )
  323. if device:
  324. where += " AND device = {device:String}"
  325. params["device"] = device
  326. rows = ch_query(
  327. f"SELECT toUInt64(toUnixTimestamp(ts)) * 1000 AS t, device, contact, olek "
  328. f"FROM {CH_DB}.ukseandur WHERE {where} ORDER BY ts",
  329. params,
  330. )
  331. return {
  332. "from": from_s,
  333. "to": to_s,
  334. "events": [
  335. {"t": int(r["t"]), "device": r["device"], "contact": bool(r["contact"]), "olek": r["olek"]}
  336. for r in rows
  337. ],
  338. }
  339. @app.get("/api/vead", dependencies=[Depends(require_auth)])
  340. async def vead(
  341. from_: str | None = Query(None, alias="from"),
  342. to: str | None = Query(None),
  343. device: str | None = Query(None),
  344. ) -> dict:
  345. from_s, to_s = resolve_range(from_, to)
  346. params = {"from": from_s, "to": to_s}
  347. where = (
  348. f"ts BETWEEN toDateTime({{from:String}}, 'Europe/Tallinn') "
  349. f"AND toDateTime({{to:String}}, 'Europe/Tallinn')"
  350. )
  351. if device:
  352. where += " AND device = {device:String}"
  353. params["device"] = device
  354. rows = ch_query(
  355. f"SELECT toUInt64(toUnixTimestamp(ts)) * 1000 AS t, device, tyyp, olek, detail, vaartus "
  356. f"FROM {CH_DB}.vead WHERE {where} ORDER BY ts",
  357. params,
  358. )
  359. return {
  360. "from": from_s,
  361. "to": to_s,
  362. "events": [
  363. {
  364. "t": int(r["t"]),
  365. "device": r["device"],
  366. "tyyp": r["tyyp"],
  367. "olek": r["olek"],
  368. "detail": r["detail"],
  369. "vaartus": r["vaartus"],
  370. }
  371. for r in rows
  372. ],
  373. }
  374. @app.get("/api/liikumine", dependencies=[Depends(require_auth)])
  375. async def liikumine(
  376. from_: str | None = Query(None, alias="from"),
  377. to: str | None = Query(None),
  378. device: str | None = Query(None),
  379. ) -> dict:
  380. from_s, to_s = resolve_range(from_, to)
  381. params = {"from": from_s, "to": to_s}
  382. where = (
  383. f"ts BETWEEN toDateTime({{from:String}}, 'Europe/Tallinn') "
  384. f"AND toDateTime({{to:String}}, 'Europe/Tallinn')"
  385. )
  386. if device:
  387. where += " AND device = {device:String}"
  388. params["device"] = device
  389. rows = ch_query(
  390. f"SELECT toUInt64(toUnixTimestamp(ts)) * 1000 AS t, device, occupancy, illumination, olek "
  391. f"FROM {CH_DB}.liikumine WHERE {where} ORDER BY ts",
  392. params,
  393. )
  394. return {
  395. "from": from_s,
  396. "to": to_s,
  397. "events": [
  398. {
  399. "t": int(r["t"]),
  400. "device": r["device"],
  401. "occupancy": bool(r["occupancy"]),
  402. "illumination": r["illumination"],
  403. "olek": r["olek"],
  404. }
  405. for r in rows
  406. ],
  407. }
  408. @app.get("/api/energia", dependencies=[Depends(require_auth)])
  409. async def energia(
  410. from_: str | None = Query(None, alias="from"),
  411. to: str | None = Query(None),
  412. device: str | None = Query(None),
  413. agg: str = Query("hour", pattern="^(hour|day)$"),
  414. ) -> dict:
  415. from_s, to_s = resolve_range(from_, to)
  416. params = {"from": from_s, "to": to_s}
  417. where = (
  418. f"ts BETWEEN toDateTime({{from:String}}, 'Europe/Tallinn') "
  419. f"AND toDateTime({{to:String}}, 'Europe/Tallinn')"
  420. )
  421. if device:
  422. where += " AND device = {device:String}"
  423. params["device"] = device
  424. if agg == "day":
  425. select = (
  426. "toUInt64(toUnixTimestamp(toStartOfDay(ts))) * 1000 AS t, device, "
  427. "round(avg(power), 2) AS power, round(avg(voltage), 1) AS voltage, "
  428. "round(avg(current), 3) AS current, max(energy) AS energy"
  429. )
  430. group = "GROUP BY t, device"
  431. else:
  432. select = (
  433. "toUInt64(toUnixTimestamp(ts)) * 1000 AS t, device, "
  434. "power, voltage, current, energy"
  435. )
  436. group = ""
  437. rows = ch_query(
  438. f"SELECT {select} FROM {CH_DB}.energia WHERE {where} {group} ORDER BY t",
  439. params,
  440. )
  441. series: dict[str, dict] = {}
  442. for row in rows:
  443. s2 = series.setdefault(
  444. row["device"], {"t": [], "power": [], "voltage": [], "current": [], "energy": []}
  445. )
  446. s2["t"].append(int(row["t"]))
  447. s2["power"].append(row["power"])
  448. s2["voltage"].append(row["voltage"])
  449. s2["current"].append(row["current"])
  450. s2["energy"].append(row["energy"])
  451. return {"from": from_s, "to": to_s, "agg": agg, "series": series}
  452. @app.get("/api/uus67_latest", dependencies=[Depends(require_auth)])
  453. async def uus67_latest() -> dict:
  454. energy = ch_query(
  455. f"SELECT device, argMax(power, ts) AS power, argMax(voltage, ts) AS voltage, "
  456. f"argMax(current, ts) AS current, argMax(energy, ts) AS energy, "
  457. f"toUInt64(toUnixTimestamp(max(ts))) * 1000 AS t "
  458. f"FROM {CH_DB}.energia GROUP BY device ORDER BY device"
  459. )
  460. motion = ch_query(
  461. f"SELECT device, argMax(occupancy, ts) AS occupancy, "
  462. f"argMax(illumination, ts) AS illumination, "
  463. f"toUInt64(toUnixTimestamp(max(ts))) * 1000 AS t "
  464. f"FROM {CH_DB}.liikumine GROUP BY device ORDER BY device"
  465. )
  466. return {
  467. "energy": [
  468. {
  469. "device": r["device"],
  470. "power": r.get("power"),
  471. "voltage": r.get("voltage"),
  472. "current": r.get("current"),
  473. "energy": r.get("energy"),
  474. "t": int(r["t"]) if r.get("t") is not None else None,
  475. }
  476. for r in energy
  477. ],
  478. "motion": [
  479. {
  480. "device": r["device"],
  481. "occupancy": bool(r.get("occupancy")),
  482. "illumination": r.get("illumination"),
  483. "t": int(r["t"]) if r.get("t") is not None else None,
  484. }
  485. for r in motion
  486. ],
  487. }
  488. # --- Värvisensor (uus67.varvus, AS7341) ---
  489. def varv_load_calib() -> dict:
  490. """Loe tume/valge referents (uus67.varvus_calib, viimane kirje liigi kohta)."""
  491. try:
  492. rows = ch_query(
  493. f"SELECT kind, {', '.join(VARV_CALIB_FIELDS)} "
  494. f"FROM {CH_DB}.{VARV_CALIB_TABLE} FINAL"
  495. )
  496. except HTTPException:
  497. return {}
  498. out: dict[str, dict] = {}
  499. for r in rows:
  500. out[r["kind"]] = {f: r.get(f) for f in VARV_CALIB_FIELDS}
  501. return out
  502. def varv_reflectance(channels: dict, dark: dict, white: dict) -> dict:
  503. """R = (S - D) / (W - D) kanali kohta."""
  504. out: dict[str, float] = {}
  505. for band in VARV_BANDS:
  506. v = channels.get(band)
  507. d = float(dark.get(band) or 0.0)
  508. w = float(white.get(band) or 0.0)
  509. if v is not None and (w - d) > 0:
  510. out[band] = max(0.0, (float(v) - d) / (w - d))
  511. return out
  512. @app.get("/api/varv/latest")
  513. async def varv_latest(limit: int = Query(60, ge=1, le=300)) -> dict:
  514. """Värvisensori viimased mõõtmised (avalik; kalibreeritud väljad kui referentsid olemas)."""
  515. cols = ", ".join(VARV_BANDS)
  516. rows = ch_query(
  517. f"SELECT toString(ts) AS ts, toUInt64(toUnixTimestamp(ts)) * 1000 AS t, "
  518. f"rgb_hex, r, g, b, round(x_chrom, 4) AS x_chrom, round(y_chrom, 4) AS y_chrom, "
  519. f"{cols}, clear, nir, gain "
  520. f"FROM {CH_DB}.varvus ORDER BY ts DESC LIMIT {int(limit)}"
  521. )
  522. calib = varv_load_calib()
  523. dark, white = calib.get("dark"), calib.get("white")
  524. ready = bool(dark and white)
  525. out = []
  526. for r in rows:
  527. bands = {b: r.get(b) for b in VARV_BANDS}
  528. raw = color.analyze(bands)
  529. item = {
  530. "ts": r["ts"],
  531. "t": int(r["t"]),
  532. "rgb_hex": raw["rgb_hex"],
  533. "r": raw["r"],
  534. "g": raw["g"],
  535. "b": raw["b"],
  536. "x_chrom": raw["x_chrom"],
  537. "y_chrom": raw["y_chrom"],
  538. "bands": bands,
  539. "clear": r.get("clear"),
  540. "nir": r.get("nir"),
  541. "gain": r.get("gain"),
  542. }
  543. if ready:
  544. cc = color.analyze(varv_reflectance(bands, dark, white))
  545. item["rgb_hex_cal"] = cc["rgb_hex"]
  546. item["x_chrom_cal"] = cc["x_chrom"]
  547. item["y_chrom_cal"] = cc["y_chrom"]
  548. out.append(item)
  549. return {"rows": out, "calibrated": ready}
  550. @app.get("/api/varv/calib")
  551. async def varv_calib_get() -> dict:
  552. """Tume/valge referents (avalik lugemine)."""
  553. calib = varv_load_calib()
  554. return {
  555. "dark": calib.get("dark"),
  556. "white": calib.get("white"),
  557. "ready": bool(calib.get("dark") and calib.get("white")),
  558. }
  559. @app.post("/api/varv/calib", dependencies=[Depends(require_auth)])
  560. async def varv_calib_set(payload: dict = Body(...)) -> dict:
  561. """Salvesta tume/valge referents viimasest N mõõtmisest (ainult sisselogitult)."""
  562. kind = str(payload.get("kind", "")).strip().lower()
  563. if kind not in ("dark", "white"):
  564. raise HTTPException(status_code=422, detail="kind peab olema 'dark' või 'white'")
  565. last = max(1, min(int(payload.get("last", 5)), 60))
  566. rows = ch_query(
  567. f"SELECT {', '.join(VARV_CALIB_FIELDS)} FROM {CH_DB}.varvus "
  568. f"ORDER BY ts DESC LIMIT {last}"
  569. )
  570. if not rows:
  571. raise HTTPException(status_code=409, detail="Mõõtmisi pole")
  572. # Stabiilsuse kontroll: viimased mõõtmised peavad olema samast olekust.
  573. totals = [
  574. sum(float(r[b]) for b in VARV_BANDS if r.get(b) is not None)
  575. for r in rows
  576. ]
  577. tmax = max(totals) if totals else 0.0
  578. if tmax > 0 and (tmax - min(totals)) / tmax > 0.2:
  579. raise HTTPException(
  580. status_code=422,
  581. detail="Mõõtmine pole stabiliseerunud (viimased mõõtmised erinevad). Oota ~30 s pärast katmise/valge pinna muutust ja proovi uuesti.",
  582. )
  583. ref: dict[str, float] = {}
  584. for f in VARV_CALIB_FIELDS:
  585. vals = [float(r[f]) for r in rows if r.get(f) is not None]
  586. ref[f] = round(sum(vals) / len(vals), 3) if vals else 0.0
  587. # Mõistlikkuse kontroll: tume ja valge ei tohi olla sarnased (W-D > 0).
  588. total_new = sum(ref.get(b, 0.0) for b in VARV_BANDS)
  589. if total_new <= 0:
  590. raise HTTPException(status_code=422, detail="Mõõtmine on null — andur on pime või andmed puuduvad.")
  591. calib = varv_load_calib()
  592. other = calib.get("white" if kind == "dark" else "dark")
  593. if other:
  594. total_other = sum(float(other.get(b) or 0.0) for b in VARV_BANDS)
  595. if kind == "white" and total_new <= total_other * 1.05:
  596. raise HTTPException(
  597. status_code=422,
  598. detail="Valge ja tume on liiga sarnased (valge pole tumedast heledam). Kontrolli: tume = andur kaetud; valge = valge pind valgustatud, sama geomeetria.",
  599. )
  600. if kind == "dark" and total_new >= total_other * 0.95:
  601. raise HTTPException(
  602. status_code=422,
  603. detail="Tume ja valge on liiga sarnased (tume pole valgest tumedem). Kontrolli, et andur oli täiesti kaetud.",
  604. )
  605. row = {"kind": kind, **ref}
  606. resp = requests.post(
  607. f"{CH_URL}/",
  608. params={
  609. "database": CH_DB,
  610. "query": f"INSERT INTO {CH_DB}.{VARV_CALIB_TABLE} FORMAT JSONEachRow",
  611. },
  612. data=json.dumps(row) + "\n",
  613. auth=(CH_USER, CH_PASS),
  614. timeout=10,
  615. )
  616. if resp.status_code != 200:
  617. raise HTTPException(status_code=502, detail=f"ClickHouse: {resp.text[:200]}")
  618. return {"kind": kind, "reference": ref, "rows": len(rows)}
  619. @app.get("/api/varv/history")
  620. async def varv_history(hours: int = Query(24, ge=1, le=168)) -> dict:
  621. """Värvitelg: tunnipõhine keskmine värv viimaste tundide jooksul (avalik)."""
  622. rows = ch_query(
  623. f"SELECT toString(toStartOfHour(ts)) AS bucket, "
  624. f"toUInt64(toUnixTimestamp(toStartOfHour(ts))) * 1000 AS t, "
  625. f"toUInt8(round(avg(r))) AS r, toUInt8(round(avg(g))) AS g, toUInt8(round(avg(b))) AS b, "
  626. f"round(avg(x_chrom), 4) AS x_chrom, round(avg(y_chrom), 4) AS y_chrom, count() AS n "
  627. f"FROM {CH_DB}.varvus WHERE ts >= now() - INTERVAL {int(hours)} HOUR "
  628. f"GROUP BY toStartOfHour(ts) ORDER BY t"
  629. )
  630. out = []
  631. for r in rows:
  632. rv, gv, bv = int(r.get("r") or 0), int(r.get("g") or 0), int(r.get("b") or 0)
  633. out.append({
  634. "ts": r["bucket"],
  635. "t": int(r["t"]),
  636. "r": rv, "g": gv, "b": bv,
  637. "rgb_hex": f"#{rv:02X}{gv:02X}{bv:02X}",
  638. "x_chrom": r.get("x_chrom"),
  639. "y_chrom": r.get("y_chrom"),
  640. "n": int(r.get("n") or 0),
  641. })
  642. return {"hours": hours, "rows": out}
  643. # --- Värvisensori mõõtmise sisse/välja lüliti (MQTT, ainult sisselogitult) ---
  644. def _varv_mqtt_client() -> mqtt.Client:
  645. client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
  646. if VARV_MQTT_TLS:
  647. client.tls_set()
  648. if VARV_MQTT_USER:
  649. client.username_pw_set(VARV_MQTT_USER, VARV_MQTT_PASS)
  650. return client
  651. def varv_read_state(timeout: float = 4.0) -> str | None:
  652. """Loe lüliti retained olek edge-brokerist (lühiajaline ühendus)."""
  653. if not VARV_MQTT_HOST:
  654. return None
  655. box: dict[str, str] = {}
  656. def on_connect(c, userdata, flags, rc, props=None):
  657. if rc == 0:
  658. c.subscribe(VARV_STATE_TOPIC)
  659. def on_message(c, userdata, msg):
  660. box["state"] = msg.payload.decode().strip()
  661. client = _varv_mqtt_client()
  662. client.on_connect = on_connect
  663. client.on_message = on_message
  664. try:
  665. client.connect_async(VARV_MQTT_HOST, VARV_MQTT_PORT, 10)
  666. client.loop_start()
  667. deadline = time.monotonic() + timeout
  668. while time.monotonic() < deadline and "state" not in box:
  669. time.sleep(0.05)
  670. finally:
  671. client.loop_stop()
  672. try:
  673. client.disconnect()
  674. except Exception:
  675. pass
  676. state = box.get("state")
  677. return state if state in ("ON", "OFF") else None
  678. def varv_set_power(on: bool) -> None:
  679. if not VARV_MQTT_HOST:
  680. raise HTTPException(status_code=503, detail="Värvisensori MQTT pole seadistatud")
  681. client = _varv_mqtt_client()
  682. try:
  683. client.connect(VARV_MQTT_HOST, VARV_MQTT_PORT, 10)
  684. client.loop_start()
  685. info = client.publish(VARV_CMD_TOPIC, "ON" if on else "OFF", qos=1, retain=True)
  686. info.wait_for_publish(timeout=5)
  687. finally:
  688. client.loop_stop()
  689. try:
  690. client.disconnect()
  691. except Exception:
  692. pass
  693. @app.get("/api/varv/power", dependencies=[Depends(require_auth)])
  694. def varv_power_get() -> dict:
  695. """Värvisensori mõõtmise olek (ainult sisselogitult)."""
  696. state = varv_read_state()
  697. return {
  698. "available": bool(VARV_MQTT_HOST),
  699. "state": state,
  700. "on": None if state is None else (state == "ON"),
  701. }
  702. @app.post("/api/varv/power", dependencies=[Depends(require_auth)])
  703. async def varv_power_set(payload: dict = Body(...)) -> dict:
  704. """Lülita värvisensori mõõtmine sisse/välja (ainult sisselogitult).
  705. OFF peatab ESP32 publitseerimise -> ClickHouse'i ei kirjutata.
  706. """
  707. on = bool(payload.get("on"))
  708. await asyncio.to_thread(varv_set_power, on)
  709. state = await asyncio.to_thread(varv_read_state, 3.0)
  710. return {"on": on, "state": state}
  711. @app.get("/api/latest")
  712. async def latest(request: Request) -> dict:
  713. readings = ch_query(
  714. f"SELECT device, "
  715. f"argMax(temperature, hour) AS temperature, "
  716. f"argMax(humidity, hour) AS humidity, "
  717. f"toString(max(hour)) AS ts_str, "
  718. f"toUInt64(toUnixTimestamp(max(hour))) * 1000 AS t "
  719. f"FROM {CH_DB}.temperatuur GROUP BY device ORDER BY device"
  720. )
  721. faults = ch_query(
  722. f"SELECT device, tyyp, argMax(detail, ts) AS detail_now, "
  723. f"toString(max(ts)) AS ts_str, argMax(olek, ts) AS olek_now "
  724. f"FROM {CH_DB}.vead GROUP BY device, tyyp HAVING olek_now = 'aktiveeritud'"
  725. ) if is_authed(request) else []
  726. outside_rows = ch_query(
  727. f"SELECT toString(max(hour)) AS ts_str, "
  728. f"argMax(temperature, hour) AS temperature, "
  729. f"argMax(humidity, hour) AS humidity, "
  730. f"argMax(wind, hour) AS wind, "
  731. f"argMax(rain, hour) AS rain, "
  732. f"toUInt64(toUnixTimestamp(max(hour))) * 1000 AS t "
  733. f"FROM {CH_DB}.valisilm FINAL"
  734. )
  735. outside: dict = {
  736. "temperature": None,
  737. "humidity": None,
  738. "wind": None,
  739. "rain": None,
  740. "hour": None,
  741. "t": None,
  742. }
  743. if outside_rows:
  744. r = outside_rows[0]
  745. outside = {
  746. "temperature": r.get("temperature"),
  747. "humidity": r.get("humidity"),
  748. "wind": r.get("wind"),
  749. "rain": r.get("rain"),
  750. "hour": r.get("ts_str"),
  751. "t": int(r["t"]) if r.get("t") is not None else None,
  752. }
  753. return {
  754. "readings": [
  755. {
  756. "device": r["device"],
  757. "temperature": r["temperature"],
  758. "humidity": r["humidity"],
  759. "hour": r["ts_str"],
  760. "t": int(r["t"]) if r.get("t") is not None else None,
  761. }
  762. for r in readings
  763. ],
  764. "open_faults": [
  765. {"device": r["device"], "tyyp": r["tyyp"], "detail": r["detail_now"], "ts": r["ts_str"]}
  766. for r in faults
  767. ],
  768. "outside": outside,
  769. }
  770. # --- Transport: bussid (peatus.ee / Digitransit GraphQL) ---
  771. def fetch_bus_departures() -> dict:
  772. """Tänased/tulevased bussiväljumised Suuremõisa küla peatustest."""
  773. fields = (
  774. "name stoptimesWithoutPatterns(numberOfDepartures: 40) { "
  775. "serviceDay scheduledDeparture realtimeDeparture realtime headsign "
  776. "trip { route { shortName longName } } }"
  777. )
  778. aliases = " ".join(
  779. f's{i}: stop(id: "{sid}") {{ {fields} }}' for i, sid in enumerate(BUS_STOPS)
  780. )
  781. try:
  782. resp = requests.post(
  783. BUS_GRAPHQL,
  784. json={"query": "{ " + aliases + " }"},
  785. headers={"User-Agent": UA},
  786. timeout=18,
  787. )
  788. except requests.RequestException as exc:
  789. raise HTTPException(status_code=502, detail=f"Bussi API ühendus: {exc}") from exc
  790. if resp.status_code != 200:
  791. raise HTTPException(status_code=502, detail=f"Bussi API: HTTP {resp.status_code}")
  792. try:
  793. payload = resp.json()
  794. except ValueError as exc:
  795. raise HTTPException(status_code=502, detail="Bussi API: vigane JSON") from exc
  796. if payload.get("errors"):
  797. msg = payload["errors"][0].get("message", "viga")
  798. raise HTTPException(status_code=502, detail=f"Bussi API: {msg}")
  799. departures = []
  800. for stop in (payload.get("data") or {}).values():
  801. if not stop or not stop.get("stoptimesWithoutPatterns"):
  802. continue
  803. stop_name = stop.get("name") or "Suuremõisa"
  804. for st in stop["stoptimesWithoutPatterns"]:
  805. service_day = st.get("serviceDay")
  806. if service_day is None:
  807. continue
  808. sched_s = st.get("scheduledDeparture") or 0
  809. real_s = st.get("realtimeDeparture")
  810. dep_s = real_s if st.get("realtime") and real_s is not None else sched_s
  811. try:
  812. dep_dt = datetime.fromtimestamp(int(service_day) + int(dep_s), TZ)
  813. except (OverflowError, OSError, TypeError, ValueError):
  814. continue
  815. route = (st.get("trip") or {}).get("route") or {}
  816. delay = None
  817. if st.get("realtime") and real_s is not None:
  818. delay = round((int(real_s) - int(sched_s)) / 60)
  819. departures.append({
  820. "t": int(dep_dt.timestamp() * 1000),
  821. "time": dep_dt.strftime("%H:%M"),
  822. "date": dep_dt.strftime("%Y-%m-%d"),
  823. "stop": stop_name,
  824. "route": route.get("shortName") or "",
  825. "headsign": st.get("headsign") or "",
  826. "realtime": bool(st.get("realtime")),
  827. "delay_min": delay,
  828. })
  829. departures.sort(key=lambda d: d["t"])
  830. now = datetime.now(TZ)
  831. return {
  832. "stops": BUS_STOPS,
  833. "today": now.strftime("%Y-%m-%d"),
  834. "departures": departures,
  835. "updated": now.strftime("%Y-%m-%d %H:%M"),
  836. }
  837. @app.get("/api/buss")
  838. async def buss(limit: int = Query(12, ge=1, le=40)) -> dict:
  839. """Järgmised bussiväljumised Suuremõisa külast (avalik)."""
  840. data = cached("buss", TRANSPORT_TTL, fetch_bus_departures)
  841. return {**data, "departures": data["departures"][:limit]}
  842. # --- Transport: praamid (praamid.ee) ---
  843. def _praam_events(day: str, direction: str) -> list[dict]:
  844. try:
  845. resp = requests.get(
  846. PRAAM_API,
  847. params={"direction": direction, "departure-date": day, "time-shift": "0"},
  848. headers={"User-Agent": UA},
  849. timeout=18,
  850. )
  851. except requests.RequestException:
  852. return []
  853. if resp.status_code != 200:
  854. return []
  855. try:
  856. items = (resp.json() or {}).get("items") or []
  857. except ValueError:
  858. return []
  859. out = []
  860. for e in items:
  861. try:
  862. dep_dt = datetime.strptime((e.get("dtstart") or "")[:19], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=TZ)
  863. except ValueError:
  864. continue
  865. ship = e.get("ship")
  866. ship_code = ship.get("code") if isinstance(ship, dict) else ship
  867. status = e.get("status") or "?"
  868. out.append({
  869. "uid": e.get("uid"),
  870. "direction": direction,
  871. "direction_name": PRAAM_DIRECTIONS.get(direction, direction),
  872. "date": dep_dt.strftime("%Y-%m-%d"),
  873. "time": dep_dt.strftime("%H:%M"),
  874. "t": int(dep_dt.timestamp() * 1000),
  875. "ship": SHIP_NAMES.get(ship_code, ship_code or "?"),
  876. "ship_code": ship_code,
  877. "status": status,
  878. "status_et": PRAAM_STATUS.get(status, status),
  879. "disrupted": status != "CONFIRMED",
  880. })
  881. return out
  882. def fetch_weather_warnings() -> list[dict]:
  883. """RII hoiatusleht -> Väinamere-liiklusega seotud aktiivsed hoiatused (parim pingutus)."""
  884. try:
  885. resp = requests.get(RII_HOIATUS_URL, headers={"User-Agent": UA}, timeout=18)
  886. except requests.RequestException:
  887. return []
  888. if resp.status_code != 200:
  889. return []
  890. text = html.unescape(resp.text)
  891. text = re.sub(r"<script.*?</script>", " ", text, flags=re.S)
  892. text = re.sub(r"<[^>]+>", " ", text)
  893. text = re.sub(r"\s+", " ", text)
  894. found, seen = [], set()
  895. for area in SEA_AREAS:
  896. i = 0
  897. while True:
  898. i = text.find(area, i)
  899. if i < 0:
  900. break
  901. seg = text[max(0, i - 100): i + 700]
  902. if any(w in seg.lower() for w in WIND_TYPES):
  903. m = re.search(r"Kehtib[^.]{0,200}", seg)
  904. valid = m.group(0).strip() if m else ""
  905. key = (area, valid or seg[:80])
  906. if key not in seen:
  907. seen.add(key)
  908. found.append({"area": area, "valid": valid, "text": seg.strip()[:300]})
  909. i += len(area)
  910. return found
  911. def fetch_praam(days: int) -> dict:
  912. now = datetime.now(TZ)
  913. day_list = [(now + timedelta(days=n)).strftime("%Y-%m-%d") for n in range(days)]
  914. departures = []
  915. for day in day_list:
  916. for direction in ("HR", "RH"):
  917. departures.extend(_praam_events(day, direction))
  918. departures.sort(key=lambda d: (d["date"], d["time"]))
  919. return {
  920. "date": day_list[0],
  921. "today": now.strftime("%Y-%m-%d"),
  922. "departures": departures,
  923. "warnings": fetch_weather_warnings(),
  924. "disrupted": sum(1 for d in departures if d["disrupted"]),
  925. "updated": now.strftime("%Y-%m-%d %H:%M"),
  926. }
  927. @app.get("/api/praam")
  928. async def praam(days: int = Query(1, ge=1, le=3)) -> dict:
  929. """Heltermaa–Rohuküla praamiväljumised + ilmahoiatuse kontekst (avalik)."""
  930. return cached(f"praam:{days}", TRANSPORT_TTL, lambda: fetch_praam(days))
  931. LOGIN_HTML = """<!doctype html>
  932. <html lang="et"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
  933. <title>Nutikodu — login</title>
  934. <style>
  935. body{font-family:system-ui,sans-serif;background:#0e1116;color:#e6edf3;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0}
  936. form{background:#161b22;padding:28px 24px;border-radius:12px;border:1px solid #30363d;min-width:280px}
  937. h1{font-size:18px;margin:0 0 16px}
  938. input{width:100%;padding:10px;border-radius:8px;border:1px solid #30363d;background:#0d1117;color:#e6edf3;box-sizing:border-box;font-size:16px}
  939. button{margin-top:14px;width:100%;padding:10px;border-radius:8px;border:0;background:#1f6feb;color:#fff;font-size:16px;cursor:pointer}
  940. .err{color:#f85149;font-size:14px;margin-top:10px;min-height:18px}
  941. a{color:#58a6ff;font-size:13px;text-decoration:none}
  942. </style></head><body>
  943. <form method="post" action="/login">
  944. <h1>🔒 Nutikodu — sisselogimine</h1>
  945. <input type="password" name="password" placeholder="Parool" autofocus autocomplete="current-password">
  946. <button type="submit">Logi sisse</button>
  947. <div class="err">{{ERR}}</div>
  948. <div style="margin-top:14px"><a href="/">← Temperatuuri leht (avalik)</a></div>
  949. </form>
  950. </body></html>"""
  951. @app.get("/login")
  952. async def login_page():
  953. return HTMLResponse(LOGIN_HTML.replace("{{ERR}}", ""))
  954. @app.post("/login")
  955. async def login_submit(request: Request, password: str = Form("")):
  956. ip = client_ip(request)
  957. ra = retry_after_seconds(ip)
  958. if ra:
  959. return HTMLResponse(
  960. LOGIN_HTML.replace("{{ERR}}", f"Liiga palju katseid. Proovi {ra} sekundi pärast."),
  961. status_code=429,
  962. )
  963. if WEB_PASSWORD and secrets.compare_digest(password, WEB_PASSWORD):
  964. reset_login_failures(ip)
  965. request.session["auth"] = True
  966. return RedirectResponse("/?auth=1", status_code=303)
  967. register_login_failure(ip)
  968. return HTMLResponse(LOGIN_HTML.replace("{{ERR}}", "Vale parool"), status_code=401)
  969. @app.get("/logout")
  970. async def logout(request: Request):
  971. request.session.clear()
  972. return RedirectResponse("/", status_code=303)
  973. @app.get("/api/me")
  974. async def me(request: Request) -> dict:
  975. return {"authed": is_authed(request)}
  976. def _ha_headers() -> dict:
  977. return {"Authorization": f"Bearer {HA_TOKEN}", "Content-Type": "application/json"}
  978. def ha_get_away() -> bool | None:
  979. if not HA_TOKEN:
  980. return None
  981. try:
  982. r = requests.get(f"{HA_URL}/api/states/{AWAY_ENTITY}", headers=_ha_headers(), timeout=8)
  983. if r.status_code == 200:
  984. return r.json().get("state") == "on"
  985. except requests.RequestException:
  986. pass
  987. return None
  988. def ha_set_away(on: bool) -> None:
  989. service = "turn_on" if on else "turn_off"
  990. r = requests.post(
  991. f"{HA_URL}/api/services/input_boolean/{service}",
  992. headers=_ha_headers(),
  993. json={"entity_id": AWAY_ENTITY},
  994. timeout=8,
  995. )
  996. r.raise_for_status()
  997. @app.get("/api/away", dependencies=[Depends(require_auth)])
  998. async def away_state() -> dict:
  999. """Kohalolu ("kodust eemal") olek."""
  1000. state = ha_get_away()
  1001. return {"away": state, "available": state is not None}
  1002. @app.post("/api/away", dependencies=[Depends(require_auth)])
  1003. async def away_set(payload: dict = Body(...)) -> dict:
  1004. """Lülita "kodust eemal" sisse/välja (keha {"on": true|false})."""
  1005. on = bool(payload.get("on"))
  1006. try:
  1007. ha_set_away(on)
  1008. except requests.RequestException as exc:
  1009. raise HTTPException(status_code=502, detail=f"Home Assistant viga: {exc}") from exc
  1010. return {"away": on, "available": True}
  1011. @app.get("/health")
  1012. async def health() -> dict:
  1013. try:
  1014. ch_query("SELECT 1")
  1015. ch_ok = True
  1016. except HTTPException:
  1017. ch_ok = False
  1018. return {"status": "ok", "clickhouse": ch_ok}
  1019. @app.get("/")
  1020. async def index() -> FileResponse:
  1021. return FileResponse(STATIC_DIR / "index.html", media_type="text/html")
  1022. app.mount("/", StaticFiles(directory=STATIC_DIR, html=True), name="static")
  1023. if __name__ == "__main__":
  1024. import uvicorn
  1025. uvicorn.run("app:app", host="0.0.0.0", port=8095, reload=True)