smart_plugs.py 32 KB

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