smart_plugs.py 32 KB

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