smart_plugs.py 29 KB

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