smart_plugs.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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.notification_service import notification_service
  28. from backend.app.services.printer_manager import printer_manager
  29. from backend.app.services.tasmota import tasmota_service
  30. logger = logging.getLogger(__name__)
  31. router = APIRouter(prefix="/smart-plugs", tags=["smart-plugs"])
  32. @router.get("/", response_model=list[SmartPlugResponse])
  33. async def list_smart_plugs(db: AsyncSession = Depends(get_db)):
  34. """List all smart plugs."""
  35. result = await db.execute(select(SmartPlug).order_by(SmartPlug.name))
  36. return list(result.scalars().all())
  37. @router.post("/", response_model=SmartPlugResponse)
  38. async def create_smart_plug(
  39. data: SmartPlugCreate,
  40. db: AsyncSession = Depends(get_db),
  41. ):
  42. """Create a new smart plug."""
  43. # Validate printer_id if provided
  44. if data.printer_id:
  45. result = await db.execute(select(Printer).where(Printer.id == data.printer_id))
  46. if not result.scalar_one_or_none():
  47. raise HTTPException(400, "Printer not found")
  48. # Check if printer already has a plug assigned
  49. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == data.printer_id))
  50. if result.scalar_one_or_none():
  51. raise HTTPException(400, "This printer already has a smart plug assigned")
  52. plug = SmartPlug(**data.model_dump())
  53. db.add(plug)
  54. await db.commit()
  55. await db.refresh(plug)
  56. if plug.plug_type == "homeassistant":
  57. logger.info(f"Created Home Assistant plug '{plug.name}' ({plug.ha_entity_id})")
  58. else:
  59. logger.info(f"Created Tasmota plug '{plug.name}' at {plug.ip_address}")
  60. return plug
  61. @router.get("/by-printer/{printer_id}", response_model=SmartPlugResponse | None)
  62. async def get_smart_plug_by_printer(printer_id: int, db: AsyncSession = Depends(get_db)):
  63. """Get the smart plug assigned to a printer."""
  64. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  65. plug = result.scalar_one_or_none()
  66. if not plug:
  67. return None
  68. return plug
  69. # Tasmota Discovery Endpoints
  70. # NOTE: These must be defined BEFORE /{plug_id} routes to avoid path conflicts
  71. class TasmotaScanRequest(BaseModel):
  72. """Request to scan for Tasmota devices."""
  73. from_ip: str | None = None # Starting IP (auto-detected if not provided)
  74. to_ip: str | None = None # Ending IP (auto-detected if not provided)
  75. timeout: float = 1.0 # Connection timeout per host
  76. def get_local_network_range() -> tuple[str, str]:
  77. """Auto-detect local network and return IP range to scan."""
  78. import socket
  79. try:
  80. # Get local IP by connecting to a public DNS (doesn't actually send data)
  81. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  82. s.connect(("8.8.8.8", 80))
  83. local_ip = s.getsockname()[0]
  84. s.close()
  85. # Parse IP and create range (assume /24 subnet)
  86. parts = local_ip.split(".")
  87. base = ".".join(parts[:3])
  88. from_ip = f"{base}.1"
  89. to_ip = f"{base}.254"
  90. logger.info(f"Auto-detected network: {from_ip} - {to_ip} (local IP: {local_ip})")
  91. return from_ip, to_ip
  92. except Exception as e:
  93. logger.error(f"Failed to detect local network: {e}")
  94. # Fallback to common home network
  95. return "192.168.1.1", "192.168.1.254"
  96. class TasmotaScanStatus(BaseModel):
  97. """Tasmota scan status response."""
  98. running: bool
  99. scanned: int
  100. total: int
  101. class DiscoveredTasmotaDevice(BaseModel):
  102. """Discovered Tasmota device."""
  103. ip_address: str
  104. name: str
  105. module: int | None = None
  106. state: str | None = None
  107. discovered_at: str | None = None
  108. @router.post("/discover/scan", response_model=TasmotaScanStatus)
  109. async def start_tasmota_scan(request: TasmotaScanRequest | None = Body(default=None)):
  110. """Start an IP range scan for Tasmota devices.
  111. Auto-detects local network if no IP range provided.
  112. """
  113. import asyncio
  114. # Auto-detect network
  115. from_ip, to_ip = get_local_network_range()
  116. timeout = request.timeout if request else 1.0
  117. # Start scan in background
  118. asyncio.create_task(tasmota_scanner.scan_range(from_ip, to_ip, timeout))
  119. # Return immediate status
  120. scanned, total = tasmota_scanner.progress
  121. return TasmotaScanStatus(
  122. running=tasmota_scanner.is_running,
  123. scanned=scanned,
  124. total=total,
  125. )
  126. @router.get("/discover/status", response_model=TasmotaScanStatus)
  127. async def get_tasmota_scan_status():
  128. """Get the current Tasmota scan status."""
  129. scanned, total = tasmota_scanner.progress
  130. return TasmotaScanStatus(
  131. running=tasmota_scanner.is_running,
  132. scanned=scanned,
  133. total=total,
  134. )
  135. @router.post("/discover/stop", response_model=TasmotaScanStatus)
  136. async def stop_tasmota_scan():
  137. """Stop the current Tasmota scan."""
  138. tasmota_scanner.stop()
  139. scanned, total = tasmota_scanner.progress
  140. return TasmotaScanStatus(
  141. running=tasmota_scanner.is_running,
  142. scanned=scanned,
  143. total=total,
  144. )
  145. @router.get("/discover/devices", response_model=list[DiscoveredTasmotaDevice])
  146. async def get_discovered_tasmota_devices():
  147. """Get list of discovered Tasmota devices."""
  148. return [
  149. DiscoveredTasmotaDevice(
  150. ip_address=d["ip_address"],
  151. name=d["name"],
  152. module=d.get("module"),
  153. state=d.get("state"),
  154. discovered_at=d.get("discovered_at"),
  155. )
  156. for d in tasmota_scanner.discovered_devices
  157. ]
  158. # Home Assistant Discovery Endpoints
  159. @router.post("/ha/test-connection", response_model=HATestConnectionResponse)
  160. async def test_ha_connection(request: HATestConnectionRequest):
  161. """Test connection to Home Assistant."""
  162. result = await homeassistant_service.test_connection(request.url, request.token)
  163. return HATestConnectionResponse(**result)
  164. @router.get("/ha/entities", response_model=list[HAEntity])
  165. async def list_ha_entities(db: AsyncSession = Depends(get_db)):
  166. """List available Home Assistant entities.
  167. Requires HA connection settings to be configured in Settings.
  168. """
  169. ha_url = await get_setting(db, "ha_url") or ""
  170. ha_token = await get_setting(db, "ha_token") or ""
  171. if not ha_url or not ha_token:
  172. raise HTTPException(
  173. 400, "Home Assistant not configured. Please set HA URL and token in Settings → Network → Home Assistant."
  174. )
  175. entities = await homeassistant_service.list_entities(ha_url, ha_token)
  176. return [HAEntity(**e) for e in entities]
  177. @router.get("/ha/sensors", response_model=list[HASensorEntity])
  178. async def list_ha_sensor_entities(db: AsyncSession = Depends(get_db)):
  179. """List available Home Assistant sensor entities for energy monitoring.
  180. Returns sensors with power/energy units (W, kW, kWh, Wh).
  181. Requires HA connection settings to be configured in Settings.
  182. """
  183. ha_url = await get_setting(db, "ha_url") or ""
  184. ha_token = await get_setting(db, "ha_token") or ""
  185. if not ha_url or not ha_token:
  186. raise HTTPException(
  187. 400, "Home Assistant not configured. Please set HA URL and token in Settings → Network → Home Assistant."
  188. )
  189. sensors = await homeassistant_service.list_sensor_entities(ha_url, ha_token)
  190. return [HASensorEntity(**s) for s in sensors]
  191. @router.get("/{plug_id}", response_model=SmartPlugResponse)
  192. async def get_smart_plug(plug_id: int, db: AsyncSession = Depends(get_db)):
  193. """Get a specific smart plug."""
  194. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  195. plug = result.scalar_one_or_none()
  196. if not plug:
  197. raise HTTPException(404, "Smart plug not found")
  198. return plug
  199. @router.patch("/{plug_id}", response_model=SmartPlugResponse)
  200. async def update_smart_plug(
  201. plug_id: int,
  202. data: SmartPlugUpdate,
  203. db: AsyncSession = Depends(get_db),
  204. ):
  205. """Update a smart plug."""
  206. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  207. plug = result.scalar_one_or_none()
  208. if not plug:
  209. raise HTTPException(404, "Smart plug not found")
  210. update_data = data.model_dump(exclude_unset=True)
  211. # Validate new printer_id if being changed
  212. if "printer_id" in update_data and update_data["printer_id"]:
  213. new_printer_id = update_data["printer_id"]
  214. # Check printer exists
  215. result = await db.execute(select(Printer).where(Printer.id == new_printer_id))
  216. if not result.scalar_one_or_none():
  217. raise HTTPException(400, "Printer not found")
  218. # Check if that printer already has a different plug assigned
  219. result = await db.execute(
  220. select(SmartPlug).where(
  221. SmartPlug.printer_id == new_printer_id,
  222. SmartPlug.id != plug_id,
  223. )
  224. )
  225. if result.scalar_one_or_none():
  226. raise HTTPException(400, "This printer already has a smart plug assigned")
  227. for field, value in update_data.items():
  228. setattr(plug, field, value)
  229. await db.commit()
  230. await db.refresh(plug)
  231. logger.info(f"Updated smart plug '{plug.name}'")
  232. return plug
  233. @router.delete("/{plug_id}")
  234. async def delete_smart_plug(plug_id: int, db: AsyncSession = Depends(get_db)):
  235. """Delete a smart plug."""
  236. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  237. plug = result.scalar_one_or_none()
  238. if not plug:
  239. raise HTTPException(404, "Smart plug not found")
  240. plug_name = plug.name
  241. await db.delete(plug)
  242. await db.commit()
  243. logger.info(f"Deleted smart plug '{plug_name}'")
  244. return {"message": "Smart plug deleted"}
  245. async def _get_service_for_plug(plug: SmartPlug, db: AsyncSession):
  246. """Get the appropriate service for the plug type.
  247. For HA plugs, configures the service with current settings from DB.
  248. """
  249. if plug.plug_type == "homeassistant":
  250. # Configure HA service with current settings
  251. ha_url = await get_setting(db, "ha_url") or ""
  252. ha_token = await get_setting(db, "ha_token") or ""
  253. homeassistant_service.configure(ha_url, ha_token)
  254. return homeassistant_service
  255. return tasmota_service
  256. @router.post("/{plug_id}/control")
  257. async def control_smart_plug(
  258. plug_id: int,
  259. control: SmartPlugControl,
  260. db: AsyncSession = Depends(get_db),
  261. ):
  262. """Manual control: on/off/toggle."""
  263. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  264. plug = result.scalar_one_or_none()
  265. if not plug:
  266. raise HTTPException(404, "Smart plug not found")
  267. service = await _get_service_for_plug(plug, db)
  268. if control.action == "on":
  269. success = await service.turn_on(plug)
  270. expected_state = "ON"
  271. elif control.action == "off":
  272. success = await service.turn_off(plug)
  273. expected_state = "OFF"
  274. elif control.action == "toggle":
  275. success = await service.toggle(plug)
  276. expected_state = None # Unknown after toggle
  277. else:
  278. raise HTTPException(400, f"Invalid action: {control.action}")
  279. if not success:
  280. raise HTTPException(503, "Failed to communicate with device")
  281. # Update last state and reset auto_off_executed when turning on
  282. if expected_state:
  283. plug.last_state = expected_state
  284. if expected_state == "ON":
  285. plug.auto_off_executed = False # Reset flag when manually turning on
  286. elif expected_state == "OFF" and plug.printer_id:
  287. # Mark printer offline immediately for faster UI update
  288. printer_manager.mark_printer_offline(plug.printer_id)
  289. plug.last_checked = datetime.utcnow()
  290. await db.commit()
  291. # MQTT relay - publish smart plug state change
  292. if expected_state:
  293. try:
  294. from backend.app.services.mqtt_relay import mqtt_relay
  295. # Get printer name if linked
  296. printer_name = None
  297. if plug.printer_id:
  298. result = await db.execute(select(Printer).where(Printer.id == plug.printer_id))
  299. printer = result.scalar_one_or_none()
  300. printer_name = printer.name if printer else None
  301. await mqtt_relay.on_smart_plug_state(
  302. plug_id=plug.id,
  303. plug_name=plug.name,
  304. state="on" if expected_state == "ON" else "off",
  305. printer_id=plug.printer_id,
  306. printer_name=printer_name,
  307. )
  308. except Exception:
  309. pass # Don't fail if MQTT fails
  310. return {"success": True, "action": control.action}
  311. @router.get("/{plug_id}/status", response_model=SmartPlugStatus)
  312. async def get_plug_status(plug_id: int, db: AsyncSession = Depends(get_db)):
  313. """Get current plug status from device including energy data."""
  314. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  315. plug = result.scalar_one_or_none()
  316. if not plug:
  317. raise HTTPException(404, "Smart plug not found")
  318. service = await _get_service_for_plug(plug, db)
  319. status = await service.get_status(plug)
  320. # Update last state in database
  321. if status["reachable"]:
  322. plug.last_state = status["state"]
  323. plug.last_checked = datetime.utcnow()
  324. await db.commit()
  325. # Fetch energy data if device is reachable
  326. energy_data = None
  327. if status["reachable"]:
  328. energy = await service.get_energy(plug)
  329. if energy:
  330. energy_data = SmartPlugEnergy(**energy)
  331. # Check power alerts
  332. await check_power_alerts(plug, energy.get("power"), db)
  333. return SmartPlugStatus(
  334. state=status["state"],
  335. reachable=status["reachable"],
  336. device_name=status.get("device_name"),
  337. energy=energy_data,
  338. )
  339. async def check_power_alerts(plug: SmartPlug, current_power: float | None, db: AsyncSession):
  340. """Check if power crosses alert thresholds and send notifications."""
  341. if not plug.power_alert_enabled or current_power is None:
  342. return
  343. # Cooldown: don't alert more than once per 5 minutes
  344. cooldown_minutes = 5
  345. if plug.power_alert_last_triggered:
  346. time_since_last = datetime.utcnow() - plug.power_alert_last_triggered
  347. if time_since_last < timedelta(minutes=cooldown_minutes):
  348. return
  349. alert_triggered = False
  350. alert_type = None
  351. threshold = None
  352. # Check high threshold
  353. if plug.power_alert_high is not None and current_power > plug.power_alert_high:
  354. alert_triggered = True
  355. alert_type = "high"
  356. threshold = plug.power_alert_high
  357. # Check low threshold
  358. if plug.power_alert_low is not None and current_power < plug.power_alert_low:
  359. alert_triggered = True
  360. alert_type = "low"
  361. threshold = plug.power_alert_low
  362. if alert_triggered:
  363. plug.power_alert_last_triggered = datetime.utcnow()
  364. await db.commit()
  365. # Send notification
  366. title = f"Power Alert: {plug.name}"
  367. if alert_type == "high":
  368. message = f"Power consumption is {current_power:.1f}W, above threshold of {threshold:.1f}W"
  369. else:
  370. message = f"Power consumption is {current_power:.1f}W, below threshold of {threshold:.1f}W"
  371. logger.info(f"Power alert triggered for {plug.name}: {message}")
  372. # Use printer_error event type for power alerts (closest match)
  373. await notification_service.send_notification(
  374. event_type="printer_error",
  375. title=title,
  376. message=message,
  377. printer_id=plug.printer_id,
  378. printer_name=plug.name,
  379. context={
  380. "error_type": f"Power {alert_type.title()}",
  381. "error_detail": message,
  382. },
  383. )
  384. @router.post("/test-connection")
  385. async def test_connection(data: SmartPlugTestConnection):
  386. """Test connection to a Tasmota device."""
  387. result = await tasmota_service.test_connection(
  388. data.ip_address,
  389. data.username,
  390. data.password,
  391. )
  392. if not result["success"]:
  393. raise HTTPException(503, result.get("error", "Failed to connect to device"))
  394. return {
  395. "success": True,
  396. "state": result["state"],
  397. "device_name": result.get("device_name"),
  398. }