smart_plugs.py 16 KB

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