smart_plugs.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. """API routes for smart plug management."""
  2. import logging
  3. from datetime import datetime, 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 RequirePermissionIfAuthEnabled
  10. from backend.app.core.database import get_db
  11. from backend.app.core.permissions import Permission
  12. from backend.app.models.printer import Printer
  13. from backend.app.models.smart_plug import SmartPlug
  14. from backend.app.models.user import User
  15. from backend.app.schemas.smart_plug import (
  16. HAEntity,
  17. HASensorEntity,
  18. HATestConnectionRequest,
  19. HATestConnectionResponse,
  20. SmartPlugControl,
  21. SmartPlugCreate,
  22. SmartPlugEnergy,
  23. SmartPlugResponse,
  24. SmartPlugStatus,
  25. SmartPlugTestConnection,
  26. SmartPlugUpdate,
  27. )
  28. from backend.app.services.discovery import tasmota_scanner
  29. from backend.app.services.homeassistant import homeassistant_service
  30. from backend.app.services.mqtt_relay import mqtt_relay
  31. from backend.app.services.notification_service import notification_service
  32. from backend.app.services.printer_manager import printer_manager
  33. from backend.app.services.tasmota import tasmota_service
  34. logger = logging.getLogger(__name__)
  35. router = APIRouter(prefix="/smart-plugs", tags=["smart-plugs"])
  36. @router.get("/", response_model=list[SmartPlugResponse])
  37. async def list_smart_plugs(
  38. db: AsyncSession = Depends(get_db),
  39. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  40. ):
  41. """List all smart plugs."""
  42. result = await db.execute(select(SmartPlug).order_by(SmartPlug.name))
  43. return list(result.scalars().all())
  44. @router.post("/", response_model=SmartPlugResponse)
  45. async def create_smart_plug(
  46. data: SmartPlugCreate,
  47. db: AsyncSession = Depends(get_db),
  48. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_CREATE),
  49. ):
  50. """Create a new smart plug."""
  51. # Validate printer_id if provided
  52. if data.printer_id:
  53. result = await db.execute(select(Printer).where(Printer.id == data.printer_id))
  54. if not result.scalar_one_or_none():
  55. raise HTTPException(400, "Printer not found")
  56. # Check if printer already has a plug assigned
  57. # Tasmota plugs: only one per printer (physical power device)
  58. # HA entities: allow multiple per printer (for different automations)
  59. if data.plug_type == "tasmota":
  60. result = await db.execute(
  61. select(SmartPlug).where(
  62. SmartPlug.printer_id == data.printer_id,
  63. SmartPlug.plug_type == "tasmota",
  64. )
  65. )
  66. if result.scalar_one_or_none():
  67. raise HTTPException(400, "This printer already has a Tasmota plug assigned")
  68. # For MQTT plugs, ensure MQTT broker is configured and service is connected
  69. if data.plug_type == "mqtt":
  70. # Try to configure the smart plug service if not already configured
  71. if not mqtt_relay.smart_plug_service.is_configured():
  72. # Get MQTT broker settings from database
  73. mqtt_broker = await get_setting(db, "mqtt_broker") or ""
  74. if not mqtt_broker:
  75. raise HTTPException(
  76. 400,
  77. "MQTT broker not configured. Please set MQTT broker address in Settings → Network → MQTT Publishing.",
  78. )
  79. # Configure the smart plug service with broker settings
  80. mqtt_settings = {
  81. "mqtt_enabled": True, # Enable for smart plug subscription
  82. "mqtt_broker": mqtt_broker,
  83. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  84. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  85. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  86. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  87. }
  88. await mqtt_relay.smart_plug_service.configure(mqtt_settings)
  89. # Check if connection succeeded
  90. if not mqtt_relay.smart_plug_service.is_configured():
  91. raise HTTPException(
  92. 400,
  93. f"Failed to connect to MQTT broker at {mqtt_broker}. Please check your MQTT settings.",
  94. )
  95. plug_data = data.model_dump()
  96. # For HA entities, default auto_on and auto_off to False
  97. # (they're for automations, not power control like Tasmota plugs)
  98. if data.plug_type == "homeassistant":
  99. plug_data["auto_on"] = False
  100. plug_data["auto_off"] = False
  101. plug = SmartPlug(**plug_data)
  102. db.add(plug)
  103. await db.commit()
  104. await db.refresh(plug)
  105. # Subscribe MQTT plugs to their topics
  106. if plug.plug_type == "mqtt":
  107. # Determine effective topics (new fields take priority, fall back to legacy)
  108. power_topic = plug.mqtt_power_topic or plug.mqtt_topic
  109. energy_topic = plug.mqtt_energy_topic
  110. state_topic = plug.mqtt_state_topic
  111. # Only subscribe if at least one topic is configured
  112. if power_topic or energy_topic or state_topic:
  113. mqtt_relay.smart_plug_service.subscribe(
  114. plug_id=plug.id,
  115. # Power source (path is optional)
  116. power_topic=power_topic,
  117. power_path=plug.mqtt_power_path,
  118. power_multiplier=plug.mqtt_power_multiplier or plug.mqtt_multiplier or 1.0,
  119. # Energy source (path is optional)
  120. energy_topic=energy_topic,
  121. energy_path=plug.mqtt_energy_path,
  122. energy_multiplier=plug.mqtt_energy_multiplier or plug.mqtt_multiplier or 1.0,
  123. # State source (path is optional)
  124. state_topic=state_topic,
  125. state_path=plug.mqtt_state_path,
  126. state_on_value=plug.mqtt_state_on_value,
  127. )
  128. topics = [t for t in [power_topic, energy_topic, state_topic] if t]
  129. logger.info("Created MQTT plug '%s' subscribed to %s", plug.name, ", ".join(set(topics)))
  130. elif plug.plug_type == "homeassistant":
  131. logger.info("Created Home Assistant plug '%s' (%s)", plug.name, plug.ha_entity_id)
  132. else:
  133. logger.info("Created Tasmota plug '%s' at %s", plug.name, plug.ip_address)
  134. return plug
  135. @router.get("/by-printer/{printer_id}", response_model=SmartPlugResponse | None)
  136. async def get_smart_plug_by_printer(
  137. printer_id: int,
  138. db: AsyncSession = Depends(get_db),
  139. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  140. ):
  141. """Get the main smart plug assigned to a printer.
  142. When multiple plugs are assigned (e.g., a regular plug + script),
  143. returns the main (non-script) plug for power control.
  144. """
  145. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  146. plugs = result.scalars().all()
  147. if not plugs:
  148. return None
  149. # If multiple plugs, prefer the non-script one (main power plug)
  150. for plug in plugs:
  151. is_script = plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script.")
  152. if not is_script:
  153. return plug
  154. # All are scripts, return the first one
  155. return plugs[0]
  156. @router.get("/by-printer/{printer_id}/scripts", response_model=list[SmartPlugResponse])
  157. async def get_script_plugs_by_printer(
  158. printer_id: int,
  159. db: AsyncSession = Depends(get_db),
  160. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  161. ):
  162. """Get all HA entities assigned to a printer for display on printer card.
  163. Returns HA entities (switches, scripts, lights, etc.) for the printer that have
  164. show_on_printer_card enabled.
  165. Used to display action buttons alongside the main power plug.
  166. """
  167. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  168. plugs = result.scalars().all()
  169. # Filter to HA entities with show_on_printer_card enabled
  170. ha_entities = [
  171. plug for plug in plugs if plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.show_on_printer_card
  172. ]
  173. return ha_entities
  174. # Tasmota Discovery Endpoints
  175. # NOTE: These must be defined BEFORE /{plug_id} routes to avoid path conflicts
  176. class TasmotaScanRequest(BaseModel):
  177. """Request to scan for Tasmota devices."""
  178. from_ip: str | None = None # Starting IP (auto-detected if not provided)
  179. to_ip: str | None = None # Ending IP (auto-detected if not provided)
  180. timeout: float = 1.0 # Connection timeout per host
  181. def get_local_network_range() -> tuple[str, str]:
  182. """Auto-detect local network and return IP range to scan."""
  183. import socket
  184. try:
  185. # Get local IP by connecting to a public DNS (doesn't actually send data)
  186. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  187. s.connect(("8.8.8.8", 80))
  188. local_ip = s.getsockname()[0]
  189. s.close()
  190. # Parse IP and create range (assume /24 subnet)
  191. parts = local_ip.split(".")
  192. base = ".".join(parts[:3])
  193. from_ip = f"{base}.1"
  194. to_ip = f"{base}.254"
  195. logger.info("Auto-detected network: %s - %s (local IP: %s)", from_ip, to_ip, local_ip)
  196. return from_ip, to_ip
  197. except OSError as e:
  198. logger.error("Failed to detect local network: %s", e)
  199. # Fallback to common home network
  200. return "192.168.1.1", "192.168.1.254"
  201. class TasmotaScanStatus(BaseModel):
  202. """Tasmota scan status response."""
  203. running: bool
  204. scanned: int
  205. total: int
  206. class DiscoveredTasmotaDevice(BaseModel):
  207. """Discovered Tasmota device."""
  208. ip_address: str
  209. name: str
  210. module: int | None = None
  211. state: str | None = None
  212. discovered_at: str | None = None
  213. @router.post("/discover/scan", response_model=TasmotaScanStatus)
  214. async def start_tasmota_scan(
  215. request: TasmotaScanRequest | None = Body(default=None),
  216. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  217. ):
  218. """Start an IP range scan for Tasmota devices.
  219. Auto-detects local network if no IP range provided.
  220. """
  221. import asyncio
  222. # Auto-detect network
  223. from_ip, to_ip = get_local_network_range()
  224. timeout = request.timeout if request else 1.0
  225. # Start scan in background
  226. asyncio.create_task(tasmota_scanner.scan_range(from_ip, to_ip, timeout))
  227. # Return immediate status
  228. scanned, total = tasmota_scanner.progress
  229. return TasmotaScanStatus(
  230. running=tasmota_scanner.is_running,
  231. scanned=scanned,
  232. total=total,
  233. )
  234. @router.get("/discover/status", response_model=TasmotaScanStatus)
  235. async def get_tasmota_scan_status(
  236. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  237. ):
  238. """Get the current Tasmota scan status."""
  239. scanned, total = tasmota_scanner.progress
  240. return TasmotaScanStatus(
  241. running=tasmota_scanner.is_running,
  242. scanned=scanned,
  243. total=total,
  244. )
  245. @router.post("/discover/stop", response_model=TasmotaScanStatus)
  246. async def stop_tasmota_scan(
  247. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  248. ):
  249. """Stop the current Tasmota scan."""
  250. tasmota_scanner.stop()
  251. scanned, total = tasmota_scanner.progress
  252. return TasmotaScanStatus(
  253. running=tasmota_scanner.is_running,
  254. scanned=scanned,
  255. total=total,
  256. )
  257. @router.get("/discover/devices", response_model=list[DiscoveredTasmotaDevice])
  258. async def get_discovered_tasmota_devices(
  259. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  260. ):
  261. """Get list of discovered Tasmota devices."""
  262. return [
  263. DiscoveredTasmotaDevice(
  264. ip_address=d["ip_address"],
  265. name=d["name"],
  266. module=d.get("module"),
  267. state=d.get("state"),
  268. discovered_at=d.get("discovered_at"),
  269. )
  270. for d in tasmota_scanner.discovered_devices
  271. ]
  272. # Home Assistant Discovery Endpoints
  273. @router.post("/ha/test-connection", response_model=HATestConnectionResponse)
  274. async def test_ha_connection(
  275. request: HATestConnectionRequest,
  276. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_CONTROL),
  277. ):
  278. """Test connection to Home Assistant."""
  279. result = await homeassistant_service.test_connection(request.url, request.token)
  280. return HATestConnectionResponse(**result)
  281. @router.get("/ha/entities", response_model=list[HAEntity])
  282. async def list_ha_entities(
  283. db: AsyncSession = Depends(get_db),
  284. search: str | None = None,
  285. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  286. ):
  287. """List available Home Assistant entities.
  288. By default, returns switch/light/input_boolean entities.
  289. When search is provided, searches ALL entities by entity_id or friendly_name.
  290. Requires HA connection settings to be configured in Settings.
  291. """
  292. ha_url = await get_setting(db, "ha_url") or ""
  293. ha_token = await get_setting(db, "ha_token") or ""
  294. if not ha_url or not ha_token:
  295. raise HTTPException(
  296. 400, "Home Assistant not configured. Please set HA URL and token in Settings → Network → Home Assistant."
  297. )
  298. entities = await homeassistant_service.list_entities(ha_url, ha_token, search)
  299. return [HAEntity(**e) for e in entities]
  300. @router.get("/ha/sensors", response_model=list[HASensorEntity])
  301. async def list_ha_sensor_entities(
  302. db: AsyncSession = Depends(get_db),
  303. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  304. ):
  305. """List available Home Assistant sensor entities for energy monitoring.
  306. Returns sensors with power/energy units (W, kW, kWh, Wh).
  307. Requires HA connection settings to be configured in Settings.
  308. """
  309. ha_url = await get_setting(db, "ha_url") or ""
  310. ha_token = await get_setting(db, "ha_token") or ""
  311. if not ha_url or not ha_token:
  312. raise HTTPException(
  313. 400, "Home Assistant not configured. Please set HA URL and token in Settings → Network → Home Assistant."
  314. )
  315. sensors = await homeassistant_service.list_sensor_entities(ha_url, ha_token)
  316. return [HASensorEntity(**s) for s in sensors]
  317. @router.get("/{plug_id}", response_model=SmartPlugResponse)
  318. async def get_smart_plug(
  319. plug_id: int,
  320. db: AsyncSession = Depends(get_db),
  321. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  322. ):
  323. """Get a specific smart plug."""
  324. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  325. plug = result.scalar_one_or_none()
  326. if not plug:
  327. raise HTTPException(404, "Smart plug not found")
  328. return plug
  329. @router.patch("/{plug_id}", response_model=SmartPlugResponse)
  330. async def update_smart_plug(
  331. plug_id: int,
  332. data: SmartPlugUpdate,
  333. db: AsyncSession = Depends(get_db),
  334. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_UPDATE),
  335. ):
  336. """Update a smart plug."""
  337. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  338. plug = result.scalar_one_or_none()
  339. if not plug:
  340. raise HTTPException(404, "Smart plug not found")
  341. update_data = data.model_dump(exclude_unset=True)
  342. # Validate new printer_id if being changed
  343. if "printer_id" in update_data and update_data["printer_id"]:
  344. new_printer_id = update_data["printer_id"]
  345. # Check printer exists
  346. result = await db.execute(select(Printer).where(Printer.id == new_printer_id))
  347. if not result.scalar_one_or_none():
  348. raise HTTPException(400, "Printer not found")
  349. # Check if that printer already has a different Tasmota plug assigned
  350. # Tasmota plugs: only one per printer (physical power device)
  351. # HA entities: allow multiple per printer (for different automations)
  352. new_plug_type = update_data.get("plug_type", plug.plug_type)
  353. if new_plug_type == "tasmota":
  354. result = await db.execute(
  355. select(SmartPlug).where(
  356. SmartPlug.printer_id == new_printer_id,
  357. SmartPlug.id != plug_id,
  358. SmartPlug.plug_type == "tasmota",
  359. )
  360. )
  361. if result.scalar_one_or_none():
  362. raise HTTPException(400, "This printer already has a Tasmota plug assigned")
  363. # Track old MQTT settings for comparison
  364. old_plug_type = plug.plug_type
  365. old_mqtt_config = {
  366. "power_topic": plug.mqtt_power_topic or plug.mqtt_topic,
  367. "power_path": plug.mqtt_power_path,
  368. "power_multiplier": plug.mqtt_power_multiplier,
  369. "energy_topic": plug.mqtt_energy_topic or plug.mqtt_topic,
  370. "energy_path": plug.mqtt_energy_path,
  371. "energy_multiplier": plug.mqtt_energy_multiplier,
  372. "state_topic": plug.mqtt_state_topic or plug.mqtt_topic,
  373. "state_path": plug.mqtt_state_path,
  374. "state_on_value": plug.mqtt_state_on_value,
  375. }
  376. for field, value in update_data.items():
  377. setattr(plug, field, value)
  378. await db.commit()
  379. await db.refresh(plug)
  380. # Handle MQTT subscription changes
  381. if old_plug_type == "mqtt" and plug.plug_type != "mqtt":
  382. # Changed away from MQTT - unsubscribe
  383. mqtt_relay.smart_plug_service.unsubscribe(plug.id)
  384. elif plug.plug_type == "mqtt":
  385. # Check if any MQTT config changed
  386. new_mqtt_config = {
  387. "power_topic": plug.mqtt_power_topic or plug.mqtt_topic,
  388. "power_path": plug.mqtt_power_path,
  389. "power_multiplier": plug.mqtt_power_multiplier,
  390. "energy_topic": plug.mqtt_energy_topic or plug.mqtt_topic,
  391. "energy_path": plug.mqtt_energy_path,
  392. "energy_multiplier": plug.mqtt_energy_multiplier,
  393. "state_topic": plug.mqtt_state_topic or plug.mqtt_topic,
  394. "state_path": plug.mqtt_state_path,
  395. "state_on_value": plug.mqtt_state_on_value,
  396. }
  397. mqtt_changed = old_plug_type != "mqtt" or old_mqtt_config != new_mqtt_config
  398. if mqtt_changed:
  399. # Unsubscribe from old topics first
  400. if old_plug_type == "mqtt":
  401. mqtt_relay.smart_plug_service.unsubscribe(plug.id)
  402. # Subscribe to new topics
  403. power_topic = plug.mqtt_power_topic or plug.mqtt_topic
  404. energy_topic = plug.mqtt_energy_topic
  405. state_topic = plug.mqtt_state_topic
  406. # Only subscribe if at least one topic is configured
  407. if power_topic or energy_topic or state_topic:
  408. mqtt_relay.smart_plug_service.subscribe(
  409. plug_id=plug.id,
  410. # Power source (path is optional)
  411. power_topic=power_topic,
  412. power_path=plug.mqtt_power_path,
  413. power_multiplier=plug.mqtt_power_multiplier or plug.mqtt_multiplier or 1.0,
  414. # Energy source (path is optional)
  415. energy_topic=energy_topic,
  416. energy_path=plug.mqtt_energy_path,
  417. energy_multiplier=plug.mqtt_energy_multiplier or plug.mqtt_multiplier or 1.0,
  418. # State source (path is optional)
  419. state_topic=state_topic,
  420. state_path=plug.mqtt_state_path,
  421. state_on_value=plug.mqtt_state_on_value,
  422. )
  423. logger.info("Updated smart plug '%s'", plug.name)
  424. return plug
  425. @router.delete("/{plug_id}")
  426. async def delete_smart_plug(
  427. plug_id: int,
  428. db: AsyncSession = Depends(get_db),
  429. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_DELETE),
  430. ):
  431. """Delete a smart plug."""
  432. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  433. plug = result.scalar_one_or_none()
  434. if not plug:
  435. raise HTTPException(404, "Smart plug not found")
  436. plug_name = plug.name
  437. plug_type = plug.plug_type
  438. # Unsubscribe MQTT plug before deletion
  439. if plug_type == "mqtt":
  440. mqtt_relay.smart_plug_service.unsubscribe(plug_id)
  441. await db.delete(plug)
  442. await db.commit()
  443. logger.info("Deleted smart plug '%s'", plug_name)
  444. return {"message": "Smart plug deleted"}
  445. async def _get_service_for_plug(plug: SmartPlug, db: AsyncSession):
  446. """Get the appropriate service for the plug type.
  447. For HA plugs, configures the service with current settings from DB.
  448. """
  449. if plug.plug_type == "homeassistant":
  450. # Configure HA service with current settings
  451. ha_url = await get_setting(db, "ha_url") or ""
  452. ha_token = await get_setting(db, "ha_token") or ""
  453. homeassistant_service.configure(ha_url, ha_token)
  454. return homeassistant_service
  455. return tasmota_service
  456. @router.post("/{plug_id}/control")
  457. async def control_smart_plug(
  458. plug_id: int,
  459. control: SmartPlugControl,
  460. db: AsyncSession = Depends(get_db),
  461. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_CONTROL),
  462. ):
  463. """Manual control: on/off/toggle."""
  464. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  465. plug = result.scalar_one_or_none()
  466. if not plug:
  467. raise HTTPException(404, "Smart plug not found")
  468. # MQTT plugs are monitor-only - cannot control them
  469. if plug.plug_type == "mqtt":
  470. raise HTTPException(
  471. 400,
  472. "MQTT plugs are monitor-only. Use your MQTT broker or home automation system to control them.",
  473. )
  474. service = await _get_service_for_plug(plug, db)
  475. if control.action == "on":
  476. success = await service.turn_on(plug)
  477. expected_state = "ON"
  478. elif control.action == "off":
  479. success = await service.turn_off(plug)
  480. expected_state = "OFF"
  481. elif control.action == "toggle":
  482. success = await service.toggle(plug)
  483. expected_state = None # Unknown after toggle
  484. else:
  485. raise HTTPException(400, f"Invalid action: {control.action}")
  486. if not success:
  487. raise HTTPException(503, "Failed to communicate with device")
  488. # Update last state and reset auto_off_executed when turning on
  489. if expected_state:
  490. plug.last_state = expected_state
  491. if expected_state == "ON":
  492. plug.auto_off_executed = False # Reset flag when manually turning on
  493. elif expected_state == "OFF" and plug.printer_id:
  494. # Mark printer offline immediately for faster UI update
  495. printer_manager.mark_printer_offline(plug.printer_id)
  496. plug.last_checked = datetime.utcnow()
  497. await db.commit()
  498. # Trigger associated scripts if this is a main (non-script) plug
  499. is_main_plug = not (
  500. plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script.")
  501. )
  502. if is_main_plug and plug.printer_id and expected_state:
  503. await trigger_associated_scripts(plug.printer_id, expected_state, db)
  504. # MQTT relay - publish smart plug state change
  505. if expected_state:
  506. try:
  507. from backend.app.services.mqtt_relay import mqtt_relay
  508. # Get printer name if linked
  509. printer_name = None
  510. if plug.printer_id:
  511. result = await db.execute(select(Printer).where(Printer.id == plug.printer_id))
  512. printer = result.scalar_one_or_none()
  513. printer_name = printer.name if printer else None
  514. await mqtt_relay.on_smart_plug_state(
  515. plug_id=plug.id,
  516. plug_name=plug.name,
  517. state="on" if expected_state == "ON" else "off",
  518. printer_id=plug.printer_id,
  519. printer_name=printer_name,
  520. )
  521. except Exception:
  522. pass # Don't fail if MQTT fails
  523. return {"success": True, "action": control.action}
  524. async def trigger_associated_scripts(printer_id: int, plug_state: str, db: AsyncSession):
  525. """Trigger scripts linked to a printer based on main plug state change.
  526. When the main plug turns ON, triggers scripts with auto_on=True.
  527. When the main plug turns OFF, triggers scripts with auto_off=True.
  528. """
  529. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  530. plugs = result.scalars().all()
  531. # Find scripts that should be triggered
  532. for plug in plugs:
  533. is_script = plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script.")
  534. if not is_script:
  535. continue
  536. should_trigger = False
  537. if plug_state == "ON" and plug.auto_on:
  538. should_trigger = True
  539. logger.info("Auto-triggering script '%s' on printer power-on", plug.name)
  540. elif plug_state == "OFF" and plug.auto_off:
  541. should_trigger = True
  542. logger.info("Auto-triggering script '%s' on printer power-off", plug.name)
  543. if should_trigger:
  544. try:
  545. service = await _get_service_for_plug(plug, db)
  546. await service.turn_on(plug) # Scripts are triggered by calling turn_on
  547. except Exception as e:
  548. logger.error("Failed to trigger script '%s': %s", plug.name, e)
  549. @router.get("/{plug_id}/status", response_model=SmartPlugStatus)
  550. async def get_plug_status(
  551. plug_id: int,
  552. db: AsyncSession = Depends(get_db),
  553. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_READ),
  554. ):
  555. """Get current plug status from device including energy data."""
  556. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  557. plug = result.scalar_one_or_none()
  558. if not plug:
  559. raise HTTPException(404, "Smart plug not found")
  560. # Handle MQTT plugs - get data from subscription service
  561. if plug.plug_type == "mqtt":
  562. data = mqtt_relay.smart_plug_service.get_plug_data(plug_id)
  563. is_reachable = mqtt_relay.smart_plug_service.is_reachable(plug_id)
  564. if data:
  565. # Update last state in database
  566. if is_reachable and data.state:
  567. plug.last_state = data.state
  568. plug.last_checked = datetime.utcnow()
  569. await db.commit()
  570. energy_data = None
  571. if data.power is not None or data.energy is not None:
  572. energy_data = SmartPlugEnergy(
  573. power=data.power,
  574. today=data.energy,
  575. )
  576. # Check power alerts
  577. if data.power is not None:
  578. await check_power_alerts(plug, data.power, db)
  579. return SmartPlugStatus(
  580. state=data.state,
  581. reachable=is_reachable,
  582. device_name=None,
  583. energy=energy_data,
  584. )
  585. # No data received yet
  586. return SmartPlugStatus(
  587. state=None,
  588. reachable=False,
  589. device_name=None,
  590. energy=None,
  591. )
  592. # Handle Tasmota/HomeAssistant plugs
  593. service = await _get_service_for_plug(plug, db)
  594. status = await service.get_status(plug)
  595. # Update last state in database
  596. if status["reachable"]:
  597. plug.last_state = status["state"]
  598. plug.last_checked = datetime.utcnow()
  599. await db.commit()
  600. # Fetch energy data if device is reachable
  601. energy_data = None
  602. if status["reachable"]:
  603. energy = await service.get_energy(plug)
  604. if energy:
  605. energy_data = SmartPlugEnergy(**energy)
  606. # Check power alerts
  607. await check_power_alerts(plug, energy.get("power"), db)
  608. return SmartPlugStatus(
  609. state=status["state"],
  610. reachable=status["reachable"],
  611. device_name=status.get("device_name"),
  612. energy=energy_data,
  613. )
  614. async def check_power_alerts(plug: SmartPlug, current_power: float | None, db: AsyncSession):
  615. """Check if power crosses alert thresholds and send notifications."""
  616. if not plug.power_alert_enabled or current_power is None:
  617. return
  618. # Cooldown: don't alert more than once per 5 minutes
  619. cooldown_minutes = 5
  620. if plug.power_alert_last_triggered:
  621. time_since_last = datetime.utcnow() - plug.power_alert_last_triggered
  622. if time_since_last < timedelta(minutes=cooldown_minutes):
  623. return
  624. alert_triggered = False
  625. alert_type = None
  626. threshold = None
  627. # Check high threshold
  628. if plug.power_alert_high is not None and current_power > plug.power_alert_high:
  629. alert_triggered = True
  630. alert_type = "high"
  631. threshold = plug.power_alert_high
  632. # Check low threshold
  633. if plug.power_alert_low is not None and current_power < plug.power_alert_low:
  634. alert_triggered = True
  635. alert_type = "low"
  636. threshold = plug.power_alert_low
  637. if alert_triggered:
  638. plug.power_alert_last_triggered = datetime.utcnow()
  639. await db.commit()
  640. # Send notification
  641. title = f"Power Alert: {plug.name}"
  642. if alert_type == "high":
  643. message = f"Power consumption is {current_power:.1f}W, above threshold of {threshold:.1f}W"
  644. else:
  645. message = f"Power consumption is {current_power:.1f}W, below threshold of {threshold:.1f}W"
  646. logger.info("Power alert triggered for %s: %s", plug.name, message)
  647. # Use printer_error event type for power alerts (closest match)
  648. await notification_service.send_notification(
  649. event_type="printer_error",
  650. title=title,
  651. message=message,
  652. printer_id=plug.printer_id,
  653. printer_name=plug.name,
  654. context={
  655. "error_type": f"Power {alert_type.title()}",
  656. "error_detail": message,
  657. },
  658. )
  659. @router.post("/test-connection")
  660. async def test_connection(
  661. data: SmartPlugTestConnection,
  662. _: User | None = RequirePermissionIfAuthEnabled(Permission.SMART_PLUGS_CONTROL),
  663. ):
  664. """Test connection to a Tasmota device."""
  665. result = await tasmota_service.test_connection(
  666. data.ip_address,
  667. data.username,
  668. data.password,
  669. )
  670. if not result["success"]:
  671. raise HTTPException(503, result.get("error", "Failed to connect to device"))
  672. return {
  673. "success": True,
  674. "state": result["state"],
  675. "device_name": result.get("device_name"),
  676. }