app.py 36 KB

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