smart_plugs.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  1. """API routes for smart plug management."""
  2. import logging
  3. from fastapi import APIRouter, Body, Depends, HTTPException
  4. from pydantic import BaseModel
  5. from sqlalchemy import select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from backend.app.api.routes.settings import get_setting
  8. from backend.app.core.auth import (
  9. RequestPrinterScope,
  10. RequirePermissionIfAuthEnabled,
  11. RequirePrinterPermissionIfAuthEnabled,
  12. probe_permissions_if_auth_enabled,
  13. )
  14. from backend.app.core.database import get_db
  15. from backend.app.core.permissions import Permission
  16. from backend.app.core.printer_scope import PrinterScope
  17. from backend.app.core.tasks import spawn_background_task
  18. from backend.app.models.printer import Printer
  19. from backend.app.models.smart_plug import SmartPlug
  20. from backend.app.models.user import User
  21. from backend.app.schemas.smart_plug import (
  22. HAEntity,
  23. HASensorEntity,
  24. HATestConnectionRequest,
  25. HATestConnectionResponse,
  26. RESTTestConnectionRequest,
  27. RESTTestConnectionResponse,
  28. SmartPlugControl,
  29. SmartPlugCreate,
  30. SmartPlugEnergy,
  31. SmartPlugResponse,
  32. SmartPlugResponseWithSecret,
  33. SmartPlugStatus,
  34. SmartPlugTestConnection,
  35. SmartPlugUpdate,
  36. )
  37. from backend.app.services.discovery import tasmota_scanner
  38. from backend.app.services.homeassistant import homeassistant_service
  39. from backend.app.services.mqtt_relay import mqtt_relay
  40. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  41. from backend.app.services.plug_energy_history import fill_derived_energy
  42. from backend.app.services.printer_manager import printer_manager
  43. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  44. from backend.app.services.secret_fields import (
  45. REST_PLUG_URLS,
  46. SECRET_PLACEHOLDER,
  47. SMART_PLUG_SECRETS,
  48. SecretConfigError,
  49. merge_partial,
  50. reject_placeholder,
  51. same_value,
  52. )
  53. from backend.app.services.smart_plug_manager import publish_plug_state, smart_plug_manager
  54. from backend.app.services.tasmota import tasmota_service
  55. from backend.app.utils.local_time import utcnow_naive
  56. logger = logging.getLogger(__name__)
  57. router = APIRouter(prefix="/smart-plugs", tags=["smart-plugs"])
  58. # Whether the caller may edit plugs, and so gets the REST URLs and bodies.
  59. CallerEditsPlugs = Depends(probe_permissions_if_auth_enabled(Permission.SMART_PLUGS_UPDATE))
  60. def _serialize_plug(plug: SmartPlug, *, can_edit: bool) -> SmartPlugResponse:
  61. """The response shape that matches the caller's authority.
  62. Routes returning it declare no response_model: validating the reader shape
  63. again would run the REST URL checks on the fields it leaves out.
  64. """
  65. if can_edit:
  66. return SmartPlugResponseWithSecret.model_validate(plug)
  67. return SmartPlugResponse.model_validate(plug)
  68. @router.get("/", response_model=None)
  69. async def list_smart_plugs(
  70. db: AsyncSession = Depends(get_db),
  71. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  72. printer_scope: PrinterScope = RequestPrinterScope,
  73. can_edit: bool = CallerEditsPlugs,
  74. ):
  75. """List all smart plugs, minus those powering printers the caller can't see (#1727)."""
  76. query = select(SmartPlug).order_by(SmartPlug.name)
  77. if (clause := printer_scope.where(SmartPlug.printer_id)) is not None:
  78. query = query.where(clause)
  79. result = await db.execute(query)
  80. return [_serialize_plug(plug, can_edit=can_edit) for plug in result.scalars().all()]
  81. @router.post("/", response_model=SmartPlugResponseWithSecret)
  82. async def create_smart_plug(
  83. data: SmartPlugCreate,
  84. db: AsyncSession = Depends(get_db),
  85. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_CREATE),
  86. printer_scope: PrinterScope = RequestPrinterScope,
  87. ):
  88. """Create a new smart plug."""
  89. try:
  90. reject_placeholder({field: getattr(data, field) for field in SMART_PLUG_SECRETS})
  91. except SecretConfigError as exc:
  92. raise HTTPException(400, str(exc)) from None
  93. # Validate printer_id if provided
  94. if data.printer_id:
  95. printer_scope.ensure(data.printer_id)
  96. result = await db.execute(select(Printer).where(Printer.id == data.printer_id))
  97. if not result.scalar_one_or_none():
  98. raise HTTPException(400, "Printer not found")
  99. # Check if printer already has a plug assigned
  100. # Tasmota plugs: only one per printer (physical power device)
  101. # HA entities: allow multiple per printer (for different automations)
  102. if data.plug_type == "tasmota":
  103. result = await db.execute(
  104. select(SmartPlug).where(
  105. SmartPlug.printer_id == data.printer_id,
  106. SmartPlug.plug_type == "tasmota",
  107. )
  108. )
  109. if result.scalar_one_or_none():
  110. raise HTTPException(400, "This printer already has a Tasmota plug assigned")
  111. # For MQTT plugs, ensure MQTT broker is configured and service is connected
  112. if data.plug_type == "mqtt":
  113. # Try to configure the smart plug service if not already configured
  114. if not mqtt_relay.smart_plug_service.is_configured():
  115. # Get MQTT broker settings from database
  116. mqtt_broker = await get_setting(db, "mqtt_broker") or ""
  117. if not mqtt_broker:
  118. raise HTTPException(
  119. 400,
  120. "MQTT broker not configured. Please set MQTT broker address in Settings → Network → MQTT Publishing.",
  121. )
  122. # Configure the smart plug service with broker settings
  123. mqtt_settings = {
  124. "mqtt_enabled": True, # Enable for smart plug subscription
  125. "mqtt_broker": mqtt_broker,
  126. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  127. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  128. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  129. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  130. }
  131. await mqtt_relay.smart_plug_service.configure(mqtt_settings)
  132. # Check if connection succeeded
  133. if not mqtt_relay.smart_plug_service.is_configured():
  134. raise HTTPException(
  135. 400,
  136. f"Failed to connect to MQTT broker at {mqtt_broker}. Please check your MQTT settings.",
  137. )
  138. plug_data = data.model_dump()
  139. # For HA entities, default auto_on and auto_off to False
  140. # (they're for automations, not power control like Tasmota plugs)
  141. if data.plug_type == "homeassistant":
  142. plug_data["auto_on"] = False
  143. plug_data["auto_off"] = False
  144. plug = SmartPlug(**plug_data)
  145. db.add(plug)
  146. await db.commit()
  147. await db.refresh(plug)
  148. # Subscribe MQTT plugs to their topics
  149. if plug.plug_type == "mqtt":
  150. topics = subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug)
  151. if topics:
  152. logger.info("Created MQTT plug '%s' subscribed to %s", plug.name, ", ".join(topics))
  153. elif plug.plug_type == "homeassistant":
  154. logger.info("Created Home Assistant plug '%s' (%s)", plug.name, plug.ha_entity_id)
  155. else:
  156. logger.info("Created Tasmota plug '%s' at %s", plug.name, plug.ip_address)
  157. return plug
  158. async def _plug_for_secret_test(
  159. db: AsyncSession, plug_id: int | None, can_update: bool, printer_scope: PrinterScope
  160. ) -> SmartPlug:
  161. """The saved plug whose stored secret a connection test may use."""
  162. if plug_id is None:
  163. raise HTTPException(400, "Enter the secret; nothing is saved for a new plug")
  164. if not can_update:
  165. raise HTTPException(403, "Testing a saved plug's secret requires smart_plugs:update")
  166. plug = await db.get(SmartPlug, plug_id)
  167. if plug is None or not printer_scope.allows(plug.printer_id):
  168. raise HTTPException(404, "Smart plug not found")
  169. return plug
  170. def _is_script_plug(plug: SmartPlug) -> bool:
  171. """Whether the plug is a Home Assistant script rather than a switchable device."""
  172. return bool(plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script."))
  173. def _can_be_switched(plug: SmartPlug) -> bool:
  174. """Whether ``control_smart_plug`` can actually turn this plug on and off.
  175. Two kinds cannot, and the card's on/off button is useless on both:
  176. - A Home Assistant script. It can be run, not switched.
  177. - An MQTT plug. Bambuddy subscribes to it and never publishes, so the
  178. control endpoint rejects it outright as monitor-only -- and an MQTT plug
  179. is exactly the kind that reports watts, so without this it would win the
  180. power tiebreak below and take the row off a plug that can be switched.
  181. """
  182. return not _is_script_plug(plug) and plug.plug_type != "mqtt"
  183. def _reports_power(plug: SmartPlug) -> bool:
  184. """Whether the plug is configured with somewhere to read watts from (#2830).
  185. Read from the configuration rather than measured: this runs on every printer
  186. card render, and probing each plug would mean an HTTP round trip per plug.
  187. So it is approximate in both directions -- an HA plug with no dedicated power
  188. sensor may still report watts from the switch entity's own
  189. ``current_power_w`` attribute, and a Tasmota device without energy metering
  190. is counted here as if it had it. Only a live read could tell, and this is
  191. used solely to break a tie between plugs that are otherwise equally
  192. eligible, so neither miss can decide anything on its own.
  193. """
  194. if plug.plug_type == "homeassistant":
  195. return bool(plug.ha_power_entity)
  196. if plug.plug_type == "mqtt":
  197. return bool(plug.mqtt_power_topic or plug.mqtt_topic)
  198. if plug.plug_type == "rest":
  199. return bool(plug.rest_power_path)
  200. return True # Tasmota, whose firmware reports power when the hardware has it
  201. def _main_plug_rank(plug: SmartPlug) -> tuple:
  202. """Sort key for choosing the printer's main power plug, best first (#2830).
  203. A printer's plugs are not interchangeable. The card's Power row carries the
  204. power on/off and auto-off-after-print controls, so it has to land on the plug
  205. that actually feeds the printer -- pointing those at an exhaust fan is the
  206. same harm #2629 fixed for the scheduler's power-on. Ordered:
  207. 1. It can be switched at all -- see ``_can_be_switched``. The row's buttons
  208. are the point of it.
  209. 2. ``controls_printer_power`` -- the flag that says this plug feeds the
  210. printer, as opposed to an accessory that merely follows the print cycle.
  211. 3. ``enabled`` -- a disabled plug ignores automation, so its auto-off toggle
  212. would sit there doing nothing.
  213. 4. ``show_on_printer_card`` -- ranked, not filtered: excluding hidden plugs
  214. outright would strip the Power row, and with it the on/off button, from a
  215. printer whose only plug has the flag off. It sorts below the power flag
  216. because a display preference must not hand power control to an accessory.
  217. 5. Reports power, so the row shows watts rather than "--" where there is a
  218. choice.
  219. 6. Lowest id, so the answer never depends on row order. The query had no
  220. ORDER BY at all, which on Postgres means a plain UPDATE can move a row and
  221. silently swap which plug the card calls the printer's power.
  222. """
  223. return (
  224. not _can_be_switched(plug),
  225. not plug.controls_printer_power,
  226. not plug.enabled,
  227. not plug.show_on_printer_card,
  228. not _reports_power(plug),
  229. plug.id,
  230. )
  231. def _pick_main_plug(plugs: list[SmartPlug]) -> SmartPlug | None:
  232. """The plug the printer card shows as its power, or None if there are none."""
  233. return min(plugs, key=_main_plug_rank, default=None)
  234. async def _plugs_for_printer(db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  235. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id).order_by(SmartPlug.id))
  236. return list(result.scalars().all())
  237. @router.get("/by-printer/{printer_id}", response_model=None)
  238. async def get_smart_plug_by_printer(
  239. printer_id: int,
  240. db: AsyncSession = Depends(get_db),
  241. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  242. can_edit: bool = CallerEditsPlugs,
  243. ):
  244. """Get the main smart plug assigned to a printer.
  245. When several plugs are assigned -- a printer outlet, an enclosure fan, a
  246. script -- returns the one that best fits the card's power controls. See
  247. ``_main_plug_rank`` for the order and why.
  248. """
  249. plug = _pick_main_plug(await _plugs_for_printer(db, printer_id))
  250. return _serialize_plug(plug, can_edit=can_edit) if plug else None
  251. @router.get("/by-printer/{printer_id}/scripts", response_model=list[SmartPlugResponse])
  252. async def get_script_plugs_by_printer(
  253. printer_id: int,
  254. db: AsyncSession = Depends(get_db),
  255. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  256. ):
  257. """Get all HA entities assigned to a printer for display on printer card.
  258. Returns HA entities (switches, scripts, lights, etc.) for the printer that have
  259. show_on_printer_card enabled.
  260. Used to display action buttons alongside the main power plug.
  261. A switchable main plug is left out: it is rendered directly above this row
  262. with its own on/off button, so listing it here draws the same entity twice
  263. (#2830). A script is not, because a printer whose only entities are scripts
  264. falls back to showing one of them in the power row -- taking it out of this
  265. row too would cost the one-click run it has always had there.
  266. """
  267. plugs = await _plugs_for_printer(db, printer_id)
  268. main_plug = _pick_main_plug(plugs)
  269. duplicate_of_power_row = main_plug.id if main_plug and not _is_script_plug(main_plug) else None
  270. # Filter to HA entities with show_on_printer_card enabled
  271. ha_entities = [
  272. plug
  273. for plug in plugs
  274. if plug.plug_type == "homeassistant"
  275. and plug.ha_entity_id
  276. and plug.show_on_printer_card
  277. and plug.id != duplicate_of_power_row
  278. ]
  279. return ha_entities
  280. # Tasmota Discovery Endpoints
  281. # NOTE: These must be defined BEFORE /{plug_id} routes to avoid path conflicts
  282. class TasmotaScanRequest(BaseModel):
  283. """Request to scan for Tasmota devices."""
  284. from_ip: str | None = None # Starting IP (auto-detected if not provided)
  285. to_ip: str | None = None # Ending IP (auto-detected if not provided)
  286. timeout: float = 1.0 # Connection timeout per host
  287. def get_local_network_range() -> tuple[str, str]:
  288. """Auto-detect local network and return IP range to scan."""
  289. import socket
  290. try:
  291. # Get local IP by connecting to a public DNS (doesn't actually send data)
  292. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  293. s.connect(("8.8.8.8", 80))
  294. local_ip = s.getsockname()[0]
  295. s.close()
  296. # Parse IP and create range (assume /24 subnet)
  297. parts = local_ip.split(".")
  298. base = ".".join(parts[:3])
  299. from_ip = f"{base}.1"
  300. to_ip = f"{base}.254"
  301. logger.info("Auto-detected network: %s - %s (local IP: %s)", from_ip, to_ip, local_ip)
  302. return from_ip, to_ip
  303. except OSError as e:
  304. logger.error("Failed to detect local network: %s", e)
  305. # Fallback to common home network
  306. return "192.168.1.1", "192.168.1.254"
  307. class TasmotaScanStatus(BaseModel):
  308. """Tasmota scan status response."""
  309. running: bool
  310. scanned: int
  311. total: int
  312. class DiscoveredTasmotaDevice(BaseModel):
  313. """Discovered Tasmota device."""
  314. ip_address: str
  315. name: str
  316. module: int | None = None
  317. state: str | None = None
  318. discovered_at: str | None = None
  319. @router.post("/discover/scan", response_model=TasmotaScanStatus)
  320. async def start_tasmota_scan(
  321. request: TasmotaScanRequest | None = Body(default=None),
  322. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  323. ):
  324. """Start an IP range scan for Tasmota devices.
  325. Auto-detects local network if no IP range provided.
  326. """
  327. # Auto-detect network
  328. from_ip, to_ip = get_local_network_range()
  329. timeout = request.timeout if request else 1.0
  330. # Start scan in background
  331. spawn_background_task(
  332. tasmota_scanner.scan_range(from_ip, to_ip, timeout),
  333. name="tasmota-scan",
  334. )
  335. # Return immediate status
  336. scanned, total = tasmota_scanner.progress
  337. return TasmotaScanStatus(
  338. running=tasmota_scanner.is_running,
  339. scanned=scanned,
  340. total=total,
  341. )
  342. @router.get("/discover/status", response_model=TasmotaScanStatus)
  343. async def get_tasmota_scan_status(
  344. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  345. ):
  346. """Get the current Tasmota scan status."""
  347. scanned, total = tasmota_scanner.progress
  348. return TasmotaScanStatus(
  349. running=tasmota_scanner.is_running,
  350. scanned=scanned,
  351. total=total,
  352. )
  353. @router.post("/discover/stop", response_model=TasmotaScanStatus)
  354. async def stop_tasmota_scan(
  355. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  356. ):
  357. """Stop the current Tasmota scan."""
  358. tasmota_scanner.stop()
  359. scanned, total = tasmota_scanner.progress
  360. return TasmotaScanStatus(
  361. running=tasmota_scanner.is_running,
  362. scanned=scanned,
  363. total=total,
  364. )
  365. @router.get("/discover/devices", response_model=list[DiscoveredTasmotaDevice])
  366. async def get_discovered_tasmota_devices(
  367. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  368. ):
  369. """Get list of discovered Tasmota devices."""
  370. return [
  371. DiscoveredTasmotaDevice(
  372. ip_address=d["ip_address"],
  373. name=d["name"],
  374. module=d.get("module"),
  375. state=d.get("state"),
  376. discovered_at=d.get("discovered_at"),
  377. )
  378. for d in tasmota_scanner.discovered_devices
  379. ]
  380. # Home Assistant Discovery Endpoints
  381. @router.post("/ha/test-connection", response_model=HATestConnectionResponse)
  382. async def test_ha_connection(
  383. request: HATestConnectionRequest,
  384. db: AsyncSession = Depends(get_db),
  385. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_CONTROL),
  386. can_update_settings: bool = Depends(probe_permissions_if_auth_enabled(Permission.SETTINGS_UPDATE)),
  387. ):
  388. """Test connection to Home Assistant.
  389. The placeholder token tests the stored token, against the stored URL only.
  390. """
  391. token = request.token
  392. if token == SECRET_PLACEHOLDER:
  393. if not can_update_settings:
  394. raise HTTPException(403, "Testing the saved token requires settings:update")
  395. from backend.app.api.routes.settings import get_homeassistant_settings
  396. stored = await get_homeassistant_settings(db)
  397. if not stored.get("ha_token"):
  398. raise HTTPException(400, "Enter the token; none is saved")
  399. if not same_value(request.url, stored.get("ha_url")):
  400. raise HTTPException(400, "Enter the token again: the URL changed")
  401. token = stored["ha_token"]
  402. result = await homeassistant_service.test_connection(request.url, token)
  403. return HATestConnectionResponse(**result)
  404. @router.post("/rest/test-connection", response_model=RESTTestConnectionResponse)
  405. async def test_rest_connection(
  406. request: RESTTestConnectionRequest,
  407. db: AsyncSession = Depends(get_db),
  408. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_CONTROL),
  409. can_update: bool = Depends(probe_permissions_if_auth_enabled(Permission.SMART_PLUGS_UPDATE)),
  410. printer_scope: PrinterScope = RequestPrinterScope,
  411. ):
  412. """Test connection to a REST/HTTP endpoint.
  413. With plug_id, the placeholder headers are the plug's stored headers, for
  414. the plug's own URLs only.
  415. """
  416. headers = request.headers
  417. if headers == SECRET_PLACEHOLDER:
  418. plug = await _plug_for_secret_test(db, request.plug_id, can_update, printer_scope)
  419. if not plug.rest_headers:
  420. raise HTTPException(400, "Enter the headers; none are saved")
  421. if not any(same_value(request.url, getattr(plug, field)) for field in REST_PLUG_URLS):
  422. raise HTTPException(400, "Enter the headers again: the URL is not one of the plug's")
  423. headers = plug.rest_headers
  424. result = await rest_smart_plug_service.test_connection(request.url, request.method, headers)
  425. return RESTTestConnectionResponse(**result)
  426. @router.get("/ha/entities", response_model=list[HAEntity])
  427. async def list_ha_entities(
  428. db: AsyncSession = Depends(get_db),
  429. search: str | None = None,
  430. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  431. ):
  432. """List available Home Assistant entities.
  433. By default, returns switch/light/input_boolean entities.
  434. When search is provided, searches ALL entities by entity_id or friendly_name.
  435. Requires HA connection settings to be configured in Settings.
  436. """
  437. from backend.app.api.routes.settings import get_homeassistant_settings
  438. ha_settings = await get_homeassistant_settings(db)
  439. ha_url = ha_settings["ha_url"]
  440. ha_token = ha_settings["ha_token"]
  441. if not ha_url or not ha_token:
  442. raise HTTPException(
  443. 400, "Home Assistant not configured. Please set HA URL and token in Settings → Network → Home Assistant."
  444. )
  445. entities = await homeassistant_service.list_entities(ha_url, ha_token, search)
  446. return [HAEntity(**e) for e in entities]
  447. @router.get("/ha/sensors", response_model=list[HASensorEntity])
  448. async def list_ha_sensor_entities(
  449. db: AsyncSession = Depends(get_db),
  450. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  451. ):
  452. """List available Home Assistant sensor entities for energy monitoring.
  453. Returns sensors with power/energy units (W, kW, kWh, Wh).
  454. Requires HA connection settings to be configured in Settings.
  455. """
  456. from backend.app.api.routes.settings import get_homeassistant_settings
  457. ha_settings = await get_homeassistant_settings(db)
  458. ha_url = ha_settings["ha_url"]
  459. ha_token = ha_settings["ha_token"]
  460. if not ha_url or not ha_token:
  461. raise HTTPException(
  462. 400, "Home Assistant not configured. Please set HA URL and token in Settings → Network → Home Assistant."
  463. )
  464. sensors = await homeassistant_service.list_sensor_entities(ha_url, ha_token)
  465. return [HASensorEntity(**s) for s in sensors]
  466. @router.get("/{plug_id}", response_model=None)
  467. async def get_smart_plug(
  468. plug_id: int,
  469. db: AsyncSession = Depends(get_db),
  470. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  471. printer_scope: PrinterScope = RequestPrinterScope,
  472. can_edit: bool = CallerEditsPlugs,
  473. ):
  474. """Get a specific smart plug."""
  475. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  476. plug = result.scalar_one_or_none()
  477. if not plug or not printer_scope.allows(plug.printer_id):
  478. raise HTTPException(404, "Smart plug not found")
  479. return _serialize_plug(plug, can_edit=can_edit)
  480. @router.patch("/{plug_id}", response_model=SmartPlugResponseWithSecret)
  481. async def update_smart_plug(
  482. plug_id: int,
  483. data: SmartPlugUpdate,
  484. db: AsyncSession = Depends(get_db),
  485. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_UPDATE),
  486. printer_scope: PrinterScope = RequestPrinterScope,
  487. ):
  488. """Update a smart plug."""
  489. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  490. plug = result.scalar_one_or_none()
  491. if not plug or not printer_scope.allows(plug.printer_id):
  492. raise HTTPException(404, "Smart plug not found")
  493. update_data = data.model_dump(exclude_unset=True)
  494. # Write-only secrets: the placeholder keeps the stored value, and a kept
  495. # secret does not follow a changed address or plug type.
  496. stored = {
  497. field: getattr(plug, field)
  498. for field in {*SMART_PLUG_SECRETS, *(f for fs in SMART_PLUG_SECRETS.values() for f in fs)}
  499. }
  500. try:
  501. update_data = merge_partial(stored, update_data, SMART_PLUG_SECRETS)
  502. except SecretConfigError as exc:
  503. raise HTTPException(400, str(exc)) from None
  504. # Validate new printer_id if being changed
  505. if "printer_id" in update_data and update_data["printer_id"]:
  506. new_printer_id = update_data["printer_id"]
  507. printer_scope.ensure(new_printer_id)
  508. # Check printer exists
  509. result = await db.execute(select(Printer).where(Printer.id == new_printer_id))
  510. if not result.scalar_one_or_none():
  511. raise HTTPException(400, "Printer not found")
  512. # Check if that printer already has a different Tasmota plug assigned
  513. # Tasmota plugs: only one per printer (physical power device)
  514. # HA entities: allow multiple per printer (for different automations)
  515. new_plug_type = update_data.get("plug_type", plug.plug_type)
  516. if new_plug_type == "tasmota":
  517. result = await db.execute(
  518. select(SmartPlug).where(
  519. SmartPlug.printer_id == new_printer_id,
  520. SmartPlug.id != plug_id,
  521. SmartPlug.plug_type == "tasmota",
  522. )
  523. )
  524. if result.scalar_one_or_none():
  525. raise HTTPException(400, "This printer already has a Tasmota plug assigned")
  526. # Track old MQTT settings for comparison
  527. old_plug_type = plug.plug_type
  528. old_mqtt_config = {
  529. "power_topic": plug.mqtt_power_topic or plug.mqtt_topic,
  530. "power_path": plug.mqtt_power_path,
  531. "power_multiplier": plug.mqtt_power_multiplier,
  532. "energy_topic": plug.mqtt_energy_topic or plug.mqtt_topic,
  533. "energy_path": plug.mqtt_energy_path,
  534. "energy_multiplier": plug.mqtt_energy_multiplier,
  535. "state_topic": plug.mqtt_state_topic or plug.mqtt_topic,
  536. "state_path": plug.mqtt_state_path,
  537. "state_on_value": plug.mqtt_state_on_value,
  538. }
  539. for field, value in update_data.items():
  540. setattr(plug, field, value)
  541. await db.commit()
  542. await db.refresh(plug)
  543. # Handle MQTT subscription changes
  544. if old_plug_type == "mqtt" and plug.plug_type != "mqtt":
  545. # Changed away from MQTT - unsubscribe
  546. mqtt_relay.smart_plug_service.unsubscribe(plug.id)
  547. elif plug.plug_type == "mqtt":
  548. # Check if any MQTT config changed
  549. new_mqtt_config = {
  550. "power_topic": plug.mqtt_power_topic or plug.mqtt_topic,
  551. "power_path": plug.mqtt_power_path,
  552. "power_multiplier": plug.mqtt_power_multiplier,
  553. "energy_topic": plug.mqtt_energy_topic or plug.mqtt_topic,
  554. "energy_path": plug.mqtt_energy_path,
  555. "energy_multiplier": plug.mqtt_energy_multiplier,
  556. "state_topic": plug.mqtt_state_topic or plug.mqtt_topic,
  557. "state_path": plug.mqtt_state_path,
  558. "state_on_value": plug.mqtt_state_on_value,
  559. }
  560. mqtt_changed = old_plug_type != "mqtt" or old_mqtt_config != new_mqtt_config
  561. if mqtt_changed:
  562. # Unsubscribe from old topics first
  563. if old_plug_type == "mqtt":
  564. mqtt_relay.smart_plug_service.unsubscribe(plug.id)
  565. # Subscribe via the shared helper (matches startup restore and
  566. # create route) — keeps all three paths in lock-step.
  567. subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug)
  568. logger.info("Updated smart plug '%s'", plug.name)
  569. return plug
  570. async def delete_plug(db: AsyncSession, plug: SmartPlug) -> None:
  571. """Delete a smart plug (the caller commits). An MQTT plug stops listening first."""
  572. smart_plug_manager.forget_plug(plug.id)
  573. if plug.plug_type == "mqtt":
  574. mqtt_relay.smart_plug_service.unsubscribe(plug.id)
  575. await db.delete(plug)
  576. @router.delete("/{plug_id}")
  577. async def delete_smart_plug(
  578. plug_id: int,
  579. db: AsyncSession = Depends(get_db),
  580. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_DELETE),
  581. printer_scope: PrinterScope = RequestPrinterScope,
  582. ):
  583. """Delete a smart plug."""
  584. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  585. plug = result.scalar_one_or_none()
  586. if not plug or not printer_scope.allows(plug.printer_id):
  587. raise HTTPException(404, "Smart plug not found")
  588. plug_name = plug.name
  589. await delete_plug(db, plug)
  590. await db.commit()
  591. logger.info("Deleted smart plug '%s'", plug_name)
  592. return {"message": "Smart plug deleted"}
  593. async def _get_service_for_plug(plug: SmartPlug, db: AsyncSession):
  594. """Get the appropriate service for the plug type.
  595. For HA plugs, configures the service with current settings from DB.
  596. """
  597. if plug.plug_type == "homeassistant":
  598. # Configure HA service with current settings
  599. from backend.app.api.routes.settings import get_homeassistant_settings
  600. ha_settings = await get_homeassistant_settings(db)
  601. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  602. return homeassistant_service
  603. if plug.plug_type == "rest":
  604. return rest_smart_plug_service
  605. return tasmota_service
  606. @router.post("/{plug_id}/control")
  607. async def control_smart_plug(
  608. plug_id: int,
  609. control: SmartPlugControl,
  610. db: AsyncSession = Depends(get_db),
  611. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_CONTROL),
  612. printer_scope: PrinterScope = RequestPrinterScope,
  613. ):
  614. """Manual control: on/off/toggle."""
  615. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  616. plug = result.scalar_one_or_none()
  617. if not plug or not printer_scope.allows(plug.printer_id):
  618. raise HTTPException(404, "Smart plug not found")
  619. # MQTT plugs are monitor-only - cannot control them
  620. if plug.plug_type == "mqtt":
  621. raise HTTPException(
  622. 400,
  623. "MQTT plugs are monitor-only. Use your MQTT broker or home automation system to control them.",
  624. )
  625. service = await _get_service_for_plug(plug, db)
  626. if control.action == "on":
  627. success = await service.turn_on(plug)
  628. expected_state = "ON"
  629. elif control.action == "off":
  630. success = await service.turn_off(plug)
  631. expected_state = "OFF"
  632. elif control.action == "toggle":
  633. success = await service.toggle(plug)
  634. expected_state = None # Unknown after toggle
  635. else:
  636. raise HTTPException(400, f"Invalid action: {control.action}")
  637. if not success:
  638. raise HTTPException(503, "Failed to communicate with device")
  639. # Update last state and reset auto_off_executed when turning on
  640. if expected_state:
  641. plug.last_state = expected_state
  642. if expected_state == "ON":
  643. plug.auto_off_executed = False # Reset flag when manually turning on
  644. elif expected_state == "OFF" and plug.printer_id and plug.controls_printer_power:
  645. # Mark printer offline immediately for faster UI update. Skipped for
  646. # accessory plugs, which are linked to a printer but don't feed it (#2629).
  647. printer_manager.mark_printer_offline(plug.printer_id)
  648. plug.last_checked = utcnow_naive()
  649. await db.commit()
  650. # Trigger associated scripts if this is a main (non-script) plug
  651. is_main_plug = not (
  652. plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script.")
  653. )
  654. if is_main_plug and plug.printer_id and expected_state:
  655. await trigger_associated_scripts(plug.printer_id, expected_state, db)
  656. # MQTT relay - publish smart plug state change. A toggle doesn't say which
  657. # way it went, so read the state it ended in.
  658. published_state = expected_state
  659. if published_state is None:
  660. try:
  661. published_state = (await service.get_status(plug)).get("state")
  662. except Exception:
  663. published_state = None
  664. if published_state in ("ON", "OFF"):
  665. await publish_plug_state(
  666. plug.id, plug.name, plug.printer_id, on=published_state == "ON", ha_entity_id=plug.ha_entity_id
  667. )
  668. return {"success": True, "action": control.action}
  669. async def trigger_associated_scripts(printer_id: int, plug_state: str, db: AsyncSession):
  670. """Trigger scripts linked to a printer based on main plug state change.
  671. When the main plug turns ON, triggers scripts with auto_on=True.
  672. When the main plug turns OFF, triggers scripts with auto_off=True.
  673. """
  674. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  675. plugs = result.scalars().all()
  676. # Find scripts that should be triggered
  677. for plug in plugs:
  678. is_script = plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script.")
  679. if not is_script:
  680. continue
  681. should_trigger = False
  682. if plug_state == "ON" and plug.auto_on:
  683. should_trigger = True
  684. logger.info("Auto-triggering script '%s' on printer power-on", plug.name)
  685. elif plug_state == "OFF" and plug.auto_off:
  686. should_trigger = True
  687. logger.info("Auto-triggering script '%s' on printer power-off", plug.name)
  688. if should_trigger:
  689. try:
  690. service = await _get_service_for_plug(plug, db)
  691. await service.turn_on(plug) # Scripts are triggered by calling turn_on
  692. except Exception as e:
  693. logger.error("Failed to trigger script '%s': %s", plug.name, e)
  694. @router.get("/{plug_id}/status", response_model=SmartPlugStatus)
  695. async def get_plug_status(
  696. plug_id: int,
  697. db: AsyncSession = Depends(get_db),
  698. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  699. printer_scope: PrinterScope = RequestPrinterScope,
  700. ):
  701. """Get current plug status from device including energy data."""
  702. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  703. plug = result.scalar_one_or_none()
  704. if not plug or not printer_scope.allows(plug.printer_id):
  705. raise HTTPException(404, "Smart plug not found")
  706. # Handle MQTT plugs - get data from subscription service
  707. if plug.plug_type == "mqtt":
  708. data = mqtt_relay.smart_plug_service.get_plug_data(plug_id)
  709. is_reachable = mqtt_relay.smart_plug_service.is_reachable(plug_id)
  710. if data:
  711. # Update last state in database
  712. if is_reachable and data.state:
  713. plug.last_state = data.state
  714. plug.last_checked = utcnow_naive()
  715. await db.commit()
  716. energy_data = None
  717. if data.power is not None or data.energy is not None:
  718. energy_data = SmartPlugEnergy(
  719. power=data.power,
  720. today=data.energy,
  721. )
  722. return SmartPlugStatus(
  723. state=data.state,
  724. reachable=is_reachable,
  725. device_name=None,
  726. energy=energy_data,
  727. )
  728. # No data received yet
  729. return SmartPlugStatus(
  730. state=None,
  731. reachable=False,
  732. device_name=None,
  733. energy=None,
  734. )
  735. # Handle Tasmota/HomeAssistant plugs
  736. service = await _get_service_for_plug(plug, db)
  737. status = await service.get_status(plug)
  738. # Update last state in database
  739. if status["reachable"]:
  740. plug.last_state = status["state"]
  741. plug.last_checked = utcnow_naive()
  742. await db.commit()
  743. # Fetch energy data if device is reachable
  744. energy_data = None
  745. if status["reachable"]:
  746. energy = await service.get_energy(plug)
  747. if energy:
  748. # Most plugs report only a lifetime counter — a Shelly has no notion
  749. # of "today" at all, and Home Assistant never reports "yesterday".
  750. # Fill those in from the hourly snapshots (#2539). Tasmota, which
  751. # knows its own daily figures, is left alone.
  752. energy = await fill_derived_energy(db, plug.id, energy)
  753. energy_data = SmartPlugEnergy(**energy)
  754. # Power alerts are checked in the background (services/power_alerts.py),
  755. # not here: this is only read while someone has a printer page open.
  756. return SmartPlugStatus(
  757. state=status["state"],
  758. reachable=status["reachable"],
  759. device_name=status.get("device_name"),
  760. energy=energy_data,
  761. )
  762. @router.post("/test-connection")
  763. async def test_connection(
  764. data: SmartPlugTestConnection,
  765. db: AsyncSession = Depends(get_db),
  766. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_CONTROL),
  767. can_update: bool = Depends(probe_permissions_if_auth_enabled(Permission.SMART_PLUGS_UPDATE)),
  768. printer_scope: PrinterScope = RequestPrinterScope,
  769. ):
  770. """Test connection to a Tasmota device.
  771. With plug_id, the placeholder password is the plug's stored password, for
  772. the plug's own address only.
  773. """
  774. password = data.password
  775. if password == SECRET_PLACEHOLDER:
  776. plug = await _plug_for_secret_test(db, data.plug_id, can_update, printer_scope)
  777. if not plug.password:
  778. raise HTTPException(400, "Enter the password; none is saved")
  779. if not same_value(data.ip_address, plug.ip_address):
  780. raise HTTPException(400, "Enter the password again: the address changed")
  781. password = plug.password
  782. result = await tasmota_service.test_connection(
  783. data.ip_address,
  784. data.username,
  785. password,
  786. )
  787. if not result["success"]:
  788. raise HTTPException(503, result.get("error", "Failed to connect to device"))
  789. return {
  790. "success": True,
  791. "state": result["state"],
  792. "device_name": result.get("device_name"),
  793. }