app.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  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. item = {
  529. "ts": r["ts"],
  530. "t": int(r["t"]),
  531. "rgb_hex": r.get("rgb_hex") or "#000000",
  532. "r": int(r.get("r") or 0),
  533. "g": int(r.get("g") or 0),
  534. "b": int(r.get("b") or 0),
  535. "x_chrom": r.get("x_chrom"),
  536. "y_chrom": r.get("y_chrom"),
  537. "bands": bands,
  538. "clear": r.get("clear"),
  539. "nir": r.get("nir"),
  540. "gain": r.get("gain"),
  541. }
  542. if ready:
  543. cc = color.analyze(varv_reflectance(bands, dark, white))
  544. item["rgb_hex_cal"] = cc["rgb_hex"]
  545. item["x_chrom_cal"] = cc["x_chrom"]
  546. item["y_chrom_cal"] = cc["y_chrom"]
  547. out.append(item)
  548. return {"rows": out, "calibrated": ready}
  549. @app.get("/api/varv/calib")
  550. async def varv_calib_get() -> dict:
  551. """Tume/valge referents (avalik lugemine)."""
  552. calib = varv_load_calib()
  553. return {
  554. "dark": calib.get("dark"),
  555. "white": calib.get("white"),
  556. "ready": bool(calib.get("dark") and calib.get("white")),
  557. }
  558. @app.post("/api/varv/calib", dependencies=[Depends(require_auth)])
  559. async def varv_calib_set(payload: dict = Body(...)) -> dict:
  560. """Salvesta tume/valge referents viimasest N mõõtmisest (ainult sisselogitult)."""
  561. kind = str(payload.get("kind", "")).strip().lower()
  562. if kind not in ("dark", "white"):
  563. raise HTTPException(status_code=422, detail="kind peab olema 'dark' või 'white'")
  564. last = max(1, min(int(payload.get("last", 5)), 60))
  565. rows = ch_query(
  566. f"SELECT {', '.join(VARV_CALIB_FIELDS)} FROM {CH_DB}.varvus "
  567. f"ORDER BY ts DESC LIMIT {last}"
  568. )
  569. if not rows:
  570. raise HTTPException(status_code=409, detail="Mõõtmisi pole")
  571. ref: dict[str, float] = {}
  572. for f in VARV_CALIB_FIELDS:
  573. vals = [float(r[f]) for r in rows if r.get(f) is not None]
  574. ref[f] = round(sum(vals) / len(vals), 3) if vals else 0.0
  575. row = {"kind": kind, **ref}
  576. resp = requests.post(
  577. f"{CH_URL}/",
  578. params={
  579. "database": CH_DB,
  580. "query": f"INSERT INTO {CH_DB}.{VARV_CALIB_TABLE} FORMAT JSONEachRow",
  581. },
  582. data=json.dumps(row) + "\n",
  583. auth=(CH_USER, CH_PASS),
  584. timeout=10,
  585. )
  586. if resp.status_code != 200:
  587. raise HTTPException(status_code=502, detail=f"ClickHouse: {resp.text[:200]}")
  588. return {"kind": kind, "reference": ref, "rows": len(rows)}
  589. @app.get("/api/varv/history")
  590. async def varv_history(hours: int = Query(24, ge=1, le=168)) -> dict:
  591. """Värvitelg: tunnipõhine keskmine värv viimaste tundide jooksul (avalik)."""
  592. rows = ch_query(
  593. f"SELECT toString(toStartOfHour(ts)) AS bucket, "
  594. f"toUInt64(toUnixTimestamp(toStartOfHour(ts))) * 1000 AS t, "
  595. f"toUInt8(round(avg(r))) AS r, toUInt8(round(avg(g))) AS g, toUInt8(round(avg(b))) AS b, "
  596. f"round(avg(x_chrom), 4) AS x_chrom, round(avg(y_chrom), 4) AS y_chrom, count() AS n "
  597. f"FROM {CH_DB}.varvus WHERE ts >= now() - INTERVAL {int(hours)} HOUR "
  598. f"GROUP BY toStartOfHour(ts) ORDER BY t"
  599. )
  600. out = []
  601. for r in rows:
  602. rv, gv, bv = int(r.get("r") or 0), int(r.get("g") or 0), int(r.get("b") or 0)
  603. out.append({
  604. "ts": r["bucket"],
  605. "t": int(r["t"]),
  606. "r": rv, "g": gv, "b": bv,
  607. "rgb_hex": f"#{rv:02X}{gv:02X}{bv:02X}",
  608. "x_chrom": r.get("x_chrom"),
  609. "y_chrom": r.get("y_chrom"),
  610. "n": int(r.get("n") or 0),
  611. })
  612. return {"hours": hours, "rows": out}
  613. # --- Värvisensori mõõtmise sisse/välja lüliti (MQTT, ainult sisselogitult) ---
  614. def _varv_mqtt_client() -> mqtt.Client:
  615. client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
  616. if VARV_MQTT_TLS:
  617. client.tls_set()
  618. if VARV_MQTT_USER:
  619. client.username_pw_set(VARV_MQTT_USER, VARV_MQTT_PASS)
  620. return client
  621. def varv_read_state(timeout: float = 4.0) -> str | None:
  622. """Loe lüliti retained olek edge-brokerist (lühiajaline ühendus)."""
  623. if not VARV_MQTT_HOST:
  624. return None
  625. box: dict[str, str] = {}
  626. def on_connect(c, userdata, flags, rc, props=None):
  627. if rc == 0:
  628. c.subscribe(VARV_STATE_TOPIC)
  629. def on_message(c, userdata, msg):
  630. box["state"] = msg.payload.decode().strip()
  631. client = _varv_mqtt_client()
  632. client.on_connect = on_connect
  633. client.on_message = on_message
  634. try:
  635. client.connect_async(VARV_MQTT_HOST, VARV_MQTT_PORT, 10)
  636. client.loop_start()
  637. deadline = time.monotonic() + timeout
  638. while time.monotonic() < deadline and "state" not in box:
  639. time.sleep(0.05)
  640. finally:
  641. client.loop_stop()
  642. try:
  643. client.disconnect()
  644. except Exception:
  645. pass
  646. state = box.get("state")
  647. return state if state in ("ON", "OFF") else None
  648. def varv_set_power(on: bool) -> None:
  649. if not VARV_MQTT_HOST:
  650. raise HTTPException(status_code=503, detail="Värvisensori MQTT pole seadistatud")
  651. client = _varv_mqtt_client()
  652. try:
  653. client.connect(VARV_MQTT_HOST, VARV_MQTT_PORT, 10)
  654. client.loop_start()
  655. info = client.publish(VARV_CMD_TOPIC, "ON" if on else "OFF", qos=1, retain=True)
  656. info.wait_for_publish(timeout=5)
  657. finally:
  658. client.loop_stop()
  659. try:
  660. client.disconnect()
  661. except Exception:
  662. pass
  663. @app.get("/api/varv/power", dependencies=[Depends(require_auth)])
  664. def varv_power_get() -> dict:
  665. """Värvisensori mõõtmise olek (ainult sisselogitult)."""
  666. state = varv_read_state()
  667. return {
  668. "available": bool(VARV_MQTT_HOST),
  669. "state": state,
  670. "on": None if state is None else (state == "ON"),
  671. }
  672. @app.post("/api/varv/power", dependencies=[Depends(require_auth)])
  673. async def varv_power_set(payload: dict = Body(...)) -> dict:
  674. """Lülita värvisensori mõõtmine sisse/välja (ainult sisselogitult).
  675. OFF peatab ESP32 publitseerimise -> ClickHouse'i ei kirjutata.
  676. """
  677. on = bool(payload.get("on"))
  678. await asyncio.to_thread(varv_set_power, on)
  679. state = await asyncio.to_thread(varv_read_state, 3.0)
  680. return {"on": on, "state": state}
  681. @app.get("/api/latest")
  682. async def latest(request: Request) -> dict:
  683. readings = ch_query(
  684. f"SELECT device, "
  685. f"argMax(temperature, hour) AS temperature, "
  686. f"argMax(humidity, hour) AS humidity, "
  687. f"toString(max(hour)) AS ts_str, "
  688. f"toUInt64(toUnixTimestamp(max(hour))) * 1000 AS t "
  689. f"FROM {CH_DB}.temperatuur GROUP BY device ORDER BY device"
  690. )
  691. faults = ch_query(
  692. f"SELECT device, tyyp, argMax(detail, ts) AS detail_now, "
  693. f"toString(max(ts)) AS ts_str, argMax(olek, ts) AS olek_now "
  694. f"FROM {CH_DB}.vead GROUP BY device, tyyp HAVING olek_now = 'aktiveeritud'"
  695. ) if is_authed(request) else []
  696. outside_rows = ch_query(
  697. f"SELECT toString(max(hour)) AS ts_str, "
  698. f"argMax(temperature, hour) AS temperature, "
  699. f"argMax(humidity, hour) AS humidity, "
  700. f"argMax(wind, hour) AS wind, "
  701. f"argMax(rain, hour) AS rain, "
  702. f"toUInt64(toUnixTimestamp(max(hour))) * 1000 AS t "
  703. f"FROM {CH_DB}.valisilm FINAL"
  704. )
  705. outside: dict = {
  706. "temperature": None,
  707. "humidity": None,
  708. "wind": None,
  709. "rain": None,
  710. "hour": None,
  711. "t": None,
  712. }
  713. if outside_rows:
  714. r = outside_rows[0]
  715. outside = {
  716. "temperature": r.get("temperature"),
  717. "humidity": r.get("humidity"),
  718. "wind": r.get("wind"),
  719. "rain": r.get("rain"),
  720. "hour": r.get("ts_str"),
  721. "t": int(r["t"]) if r.get("t") is not None else None,
  722. }
  723. return {
  724. "readings": [
  725. {
  726. "device": r["device"],
  727. "temperature": r["temperature"],
  728. "humidity": r["humidity"],
  729. "hour": r["ts_str"],
  730. "t": int(r["t"]) if r.get("t") is not None else None,
  731. }
  732. for r in readings
  733. ],
  734. "open_faults": [
  735. {"device": r["device"], "tyyp": r["tyyp"], "detail": r["detail_now"], "ts": r["ts_str"]}
  736. for r in faults
  737. ],
  738. "outside": outside,
  739. }
  740. # --- Transport: bussid (peatus.ee / Digitransit GraphQL) ---
  741. def fetch_bus_departures() -> dict:
  742. """Tänased/tulevased bussiväljumised Suuremõisa küla peatustest."""
  743. fields = (
  744. "name stoptimesWithoutPatterns(numberOfDepartures: 40) { "
  745. "serviceDay scheduledDeparture realtimeDeparture realtime headsign "
  746. "trip { route { shortName longName } } }"
  747. )
  748. aliases = " ".join(
  749. f's{i}: stop(id: "{sid}") {{ {fields} }}' for i, sid in enumerate(BUS_STOPS)
  750. )
  751. try:
  752. resp = requests.post(
  753. BUS_GRAPHQL,
  754. json={"query": "{ " + aliases + " }"},
  755. headers={"User-Agent": UA},
  756. timeout=18,
  757. )
  758. except requests.RequestException as exc:
  759. raise HTTPException(status_code=502, detail=f"Bussi API ühendus: {exc}") from exc
  760. if resp.status_code != 200:
  761. raise HTTPException(status_code=502, detail=f"Bussi API: HTTP {resp.status_code}")
  762. try:
  763. payload = resp.json()
  764. except ValueError as exc:
  765. raise HTTPException(status_code=502, detail="Bussi API: vigane JSON") from exc
  766. if payload.get("errors"):
  767. msg = payload["errors"][0].get("message", "viga")
  768. raise HTTPException(status_code=502, detail=f"Bussi API: {msg}")
  769. departures = []
  770. for stop in (payload.get("data") or {}).values():
  771. if not stop or not stop.get("stoptimesWithoutPatterns"):
  772. continue
  773. stop_name = stop.get("name") or "Suuremõisa"
  774. for st in stop["stoptimesWithoutPatterns"]:
  775. service_day = st.get("serviceDay")
  776. if service_day is None:
  777. continue
  778. sched_s = st.get("scheduledDeparture") or 0
  779. real_s = st.get("realtimeDeparture")
  780. dep_s = real_s if st.get("realtime") and real_s is not None else sched_s
  781. try:
  782. dep_dt = datetime.fromtimestamp(int(service_day) + int(dep_s), TZ)
  783. except (OverflowError, OSError, TypeError, ValueError):
  784. continue
  785. route = (st.get("trip") or {}).get("route") or {}
  786. delay = None
  787. if st.get("realtime") and real_s is not None:
  788. delay = round((int(real_s) - int(sched_s)) / 60)
  789. departures.append({
  790. "t": int(dep_dt.timestamp() * 1000),
  791. "time": dep_dt.strftime("%H:%M"),
  792. "date": dep_dt.strftime("%Y-%m-%d"),
  793. "stop": stop_name,
  794. "route": route.get("shortName") or "",
  795. "headsign": st.get("headsign") or "",
  796. "realtime": bool(st.get("realtime")),
  797. "delay_min": delay,
  798. })
  799. departures.sort(key=lambda d: d["t"])
  800. now = datetime.now(TZ)
  801. return {
  802. "stops": BUS_STOPS,
  803. "today": now.strftime("%Y-%m-%d"),
  804. "departures": departures,
  805. "updated": now.strftime("%Y-%m-%d %H:%M"),
  806. }
  807. @app.get("/api/buss")
  808. async def buss(limit: int = Query(12, ge=1, le=40)) -> dict:
  809. """Järgmised bussiväljumised Suuremõisa külast (avalik)."""
  810. data = cached("buss", TRANSPORT_TTL, fetch_bus_departures)
  811. return {**data, "departures": data["departures"][:limit]}
  812. # --- Transport: praamid (praamid.ee) ---
  813. def _praam_events(day: str, direction: str) -> list[dict]:
  814. try:
  815. resp = requests.get(
  816. PRAAM_API,
  817. params={"direction": direction, "departure-date": day, "time-shift": "0"},
  818. headers={"User-Agent": UA},
  819. timeout=18,
  820. )
  821. except requests.RequestException:
  822. return []
  823. if resp.status_code != 200:
  824. return []
  825. try:
  826. items = (resp.json() or {}).get("items") or []
  827. except ValueError:
  828. return []
  829. out = []
  830. for e in items:
  831. try:
  832. dep_dt = datetime.strptime((e.get("dtstart") or "")[:19], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=TZ)
  833. except ValueError:
  834. continue
  835. ship = e.get("ship")
  836. ship_code = ship.get("code") if isinstance(ship, dict) else ship
  837. status = e.get("status") or "?"
  838. out.append({
  839. "uid": e.get("uid"),
  840. "direction": direction,
  841. "direction_name": PRAAM_DIRECTIONS.get(direction, direction),
  842. "date": dep_dt.strftime("%Y-%m-%d"),
  843. "time": dep_dt.strftime("%H:%M"),
  844. "t": int(dep_dt.timestamp() * 1000),
  845. "ship": SHIP_NAMES.get(ship_code, ship_code or "?"),
  846. "ship_code": ship_code,
  847. "status": status,
  848. "status_et": PRAAM_STATUS.get(status, status),
  849. "disrupted": status != "CONFIRMED",
  850. })
  851. return out
  852. def fetch_weather_warnings() -> list[dict]:
  853. """RII hoiatusleht -> Väinamere-liiklusega seotud aktiivsed hoiatused (parim pingutus)."""
  854. try:
  855. resp = requests.get(RII_HOIATUS_URL, headers={"User-Agent": UA}, timeout=18)
  856. except requests.RequestException:
  857. return []
  858. if resp.status_code != 200:
  859. return []
  860. text = html.unescape(resp.text)
  861. text = re.sub(r"<script.*?</script>", " ", text, flags=re.S)
  862. text = re.sub(r"<[^>]+>", " ", text)
  863. text = re.sub(r"\s+", " ", text)
  864. found, seen = [], set()
  865. for area in SEA_AREAS:
  866. i = 0
  867. while True:
  868. i = text.find(area, i)
  869. if i < 0:
  870. break
  871. seg = text[max(0, i - 100): i + 700]
  872. if any(w in seg.lower() for w in WIND_TYPES):
  873. m = re.search(r"Kehtib[^.]{0,200}", seg)
  874. valid = m.group(0).strip() if m else ""
  875. key = (area, valid or seg[:80])
  876. if key not in seen:
  877. seen.add(key)
  878. found.append({"area": area, "valid": valid, "text": seg.strip()[:300]})
  879. i += len(area)
  880. return found
  881. def fetch_praam(days: int) -> dict:
  882. now = datetime.now(TZ)
  883. day_list = [(now + timedelta(days=n)).strftime("%Y-%m-%d") for n in range(days)]
  884. departures = []
  885. for day in day_list:
  886. for direction in ("HR", "RH"):
  887. departures.extend(_praam_events(day, direction))
  888. departures.sort(key=lambda d: (d["date"], d["time"]))
  889. return {
  890. "date": day_list[0],
  891. "today": now.strftime("%Y-%m-%d"),
  892. "departures": departures,
  893. "warnings": fetch_weather_warnings(),
  894. "disrupted": sum(1 for d in departures if d["disrupted"]),
  895. "updated": now.strftime("%Y-%m-%d %H:%M"),
  896. }
  897. @app.get("/api/praam")
  898. async def praam(days: int = Query(1, ge=1, le=3)) -> dict:
  899. """Heltermaa–Rohuküla praamiväljumised + ilmahoiatuse kontekst (avalik)."""
  900. return cached(f"praam:{days}", TRANSPORT_TTL, lambda: fetch_praam(days))
  901. LOGIN_HTML = """<!doctype html>
  902. <html lang="et"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
  903. <title>Nutikodu — login</title>
  904. <style>
  905. body{font-family:system-ui,sans-serif;background:#0e1116;color:#e6edf3;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0}
  906. form{background:#161b22;padding:28px 24px;border-radius:12px;border:1px solid #30363d;min-width:280px}
  907. h1{font-size:18px;margin:0 0 16px}
  908. input{width:100%;padding:10px;border-radius:8px;border:1px solid #30363d;background:#0d1117;color:#e6edf3;box-sizing:border-box;font-size:16px}
  909. button{margin-top:14px;width:100%;padding:10px;border-radius:8px;border:0;background:#1f6feb;color:#fff;font-size:16px;cursor:pointer}
  910. .err{color:#f85149;font-size:14px;margin-top:10px;min-height:18px}
  911. a{color:#58a6ff;font-size:13px;text-decoration:none}
  912. </style></head><body>
  913. <form method="post" action="/login">
  914. <h1>🔒 Nutikodu — sisselogimine</h1>
  915. <input type="password" name="password" placeholder="Parool" autofocus autocomplete="current-password">
  916. <button type="submit">Logi sisse</button>
  917. <div class="err">{{ERR}}</div>
  918. <div style="margin-top:14px"><a href="/">← Temperatuuri leht (avalik)</a></div>
  919. </form>
  920. </body></html>"""
  921. @app.get("/login")
  922. async def login_page():
  923. return HTMLResponse(LOGIN_HTML.replace("{{ERR}}", ""))
  924. @app.post("/login")
  925. async def login_submit(request: Request, password: str = Form("")):
  926. ip = client_ip(request)
  927. ra = retry_after_seconds(ip)
  928. if ra:
  929. return HTMLResponse(
  930. LOGIN_HTML.replace("{{ERR}}", f"Liiga palju katseid. Proovi {ra} sekundi pärast."),
  931. status_code=429,
  932. )
  933. if WEB_PASSWORD and secrets.compare_digest(password, WEB_PASSWORD):
  934. reset_login_failures(ip)
  935. request.session["auth"] = True
  936. return RedirectResponse("/?auth=1", status_code=303)
  937. register_login_failure(ip)
  938. return HTMLResponse(LOGIN_HTML.replace("{{ERR}}", "Vale parool"), status_code=401)
  939. @app.get("/logout")
  940. async def logout(request: Request):
  941. request.session.clear()
  942. return RedirectResponse("/", status_code=303)
  943. @app.get("/api/me")
  944. async def me(request: Request) -> dict:
  945. return {"authed": is_authed(request)}
  946. def _ha_headers() -> dict:
  947. return {"Authorization": f"Bearer {HA_TOKEN}", "Content-Type": "application/json"}
  948. def ha_get_away() -> bool | None:
  949. if not HA_TOKEN:
  950. return None
  951. try:
  952. r = requests.get(f"{HA_URL}/api/states/{AWAY_ENTITY}", headers=_ha_headers(), timeout=8)
  953. if r.status_code == 200:
  954. return r.json().get("state") == "on"
  955. except requests.RequestException:
  956. pass
  957. return None
  958. def ha_set_away(on: bool) -> None:
  959. service = "turn_on" if on else "turn_off"
  960. r = requests.post(
  961. f"{HA_URL}/api/services/input_boolean/{service}",
  962. headers=_ha_headers(),
  963. json={"entity_id": AWAY_ENTITY},
  964. timeout=8,
  965. )
  966. r.raise_for_status()
  967. @app.get("/api/away", dependencies=[Depends(require_auth)])
  968. async def away_state() -> dict:
  969. """Kohalolu ("kodust eemal") olek."""
  970. state = ha_get_away()
  971. return {"away": state, "available": state is not None}
  972. @app.post("/api/away", dependencies=[Depends(require_auth)])
  973. async def away_set(payload: dict = Body(...)) -> dict:
  974. """Lülita "kodust eemal" sisse/välja (keha {"on": true|false})."""
  975. on = bool(payload.get("on"))
  976. try:
  977. ha_set_away(on)
  978. except requests.RequestException as exc:
  979. raise HTTPException(status_code=502, detail=f"Home Assistant viga: {exc}") from exc
  980. return {"away": on, "available": True}
  981. @app.get("/health")
  982. async def health() -> dict:
  983. try:
  984. ch_query("SELECT 1")
  985. ch_ok = True
  986. except HTTPException:
  987. ch_ok = False
  988. return {"status": "ok", "clickhouse": ch_ok}
  989. @app.get("/")
  990. async def index() -> FileResponse:
  991. return FileResponse(STATIC_DIR / "index.html", media_type="text/html")
  992. app.mount("/", StaticFiles(directory=STATIC_DIR, html=True), name="static")
  993. if __name__ == "__main__":
  994. import uvicorn
  995. uvicorn.run("app:app", host="0.0.0.0", port=8095, reload=True)