smart_plugs.py 35 KB

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