smart_plugs.py 39 KB

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