smart_plugs.py 29 KB

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