smart_plugs.py 36 KB

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