smart_plugs.py 29 KB

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