smart_plugs.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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(400, "Home Assistant not configured. Please set HA URL and token in Settings.")
  172. entities = await homeassistant_service.list_entities(ha_url, ha_token)
  173. return [HAEntity(**e) for e in entities]
  174. @router.get("/{plug_id}", response_model=SmartPlugResponse)
  175. async def get_smart_plug(plug_id: int, db: AsyncSession = Depends(get_db)):
  176. """Get a specific smart plug."""
  177. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  178. plug = result.scalar_one_or_none()
  179. if not plug:
  180. raise HTTPException(404, "Smart plug not found")
  181. return plug
  182. @router.patch("/{plug_id}", response_model=SmartPlugResponse)
  183. async def update_smart_plug(
  184. plug_id: int,
  185. data: SmartPlugUpdate,
  186. db: AsyncSession = Depends(get_db),
  187. ):
  188. """Update a smart plug."""
  189. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  190. plug = result.scalar_one_or_none()
  191. if not plug:
  192. raise HTTPException(404, "Smart plug not found")
  193. update_data = data.model_dump(exclude_unset=True)
  194. # Validate new printer_id if being changed
  195. if "printer_id" in update_data and update_data["printer_id"]:
  196. new_printer_id = update_data["printer_id"]
  197. # Check printer exists
  198. result = await db.execute(select(Printer).where(Printer.id == new_printer_id))
  199. if not result.scalar_one_or_none():
  200. raise HTTPException(400, "Printer not found")
  201. # Check if that printer already has a different plug assigned
  202. result = await db.execute(
  203. select(SmartPlug).where(
  204. SmartPlug.printer_id == new_printer_id,
  205. SmartPlug.id != plug_id,
  206. )
  207. )
  208. if result.scalar_one_or_none():
  209. raise HTTPException(400, "This printer already has a smart plug assigned")
  210. for field, value in update_data.items():
  211. setattr(plug, field, value)
  212. await db.commit()
  213. await db.refresh(plug)
  214. logger.info(f"Updated smart plug '{plug.name}'")
  215. return plug
  216. @router.delete("/{plug_id}")
  217. async def delete_smart_plug(plug_id: int, db: AsyncSession = Depends(get_db)):
  218. """Delete a smart plug."""
  219. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  220. plug = result.scalar_one_or_none()
  221. if not plug:
  222. raise HTTPException(404, "Smart plug not found")
  223. plug_name = plug.name
  224. await db.delete(plug)
  225. await db.commit()
  226. logger.info(f"Deleted smart plug '{plug_name}'")
  227. return {"message": "Smart plug deleted"}
  228. async def _get_service_for_plug(plug: SmartPlug, db: AsyncSession):
  229. """Get the appropriate service for the plug type.
  230. For HA plugs, configures the service with current settings from DB.
  231. """
  232. if plug.plug_type == "homeassistant":
  233. # Configure HA service with current settings
  234. ha_url = await get_setting(db, "ha_url") or ""
  235. ha_token = await get_setting(db, "ha_token") or ""
  236. homeassistant_service.configure(ha_url, ha_token)
  237. return homeassistant_service
  238. return tasmota_service
  239. @router.post("/{plug_id}/control")
  240. async def control_smart_plug(
  241. plug_id: int,
  242. control: SmartPlugControl,
  243. db: AsyncSession = Depends(get_db),
  244. ):
  245. """Manual control: on/off/toggle."""
  246. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  247. plug = result.scalar_one_or_none()
  248. if not plug:
  249. raise HTTPException(404, "Smart plug not found")
  250. service = await _get_service_for_plug(plug, db)
  251. if control.action == "on":
  252. success = await service.turn_on(plug)
  253. expected_state = "ON"
  254. elif control.action == "off":
  255. success = await service.turn_off(plug)
  256. expected_state = "OFF"
  257. elif control.action == "toggle":
  258. success = await service.toggle(plug)
  259. expected_state = None # Unknown after toggle
  260. else:
  261. raise HTTPException(400, f"Invalid action: {control.action}")
  262. if not success:
  263. raise HTTPException(503, "Failed to communicate with device")
  264. # Update last state and reset auto_off_executed when turning on
  265. if expected_state:
  266. plug.last_state = expected_state
  267. if expected_state == "ON":
  268. plug.auto_off_executed = False # Reset flag when manually turning on
  269. elif expected_state == "OFF" and plug.printer_id:
  270. # Mark printer offline immediately for faster UI update
  271. printer_manager.mark_printer_offline(plug.printer_id)
  272. plug.last_checked = datetime.utcnow()
  273. await db.commit()
  274. # MQTT relay - publish smart plug state change
  275. if expected_state:
  276. try:
  277. from backend.app.services.mqtt_relay import mqtt_relay
  278. # Get printer name if linked
  279. printer_name = None
  280. if plug.printer_id:
  281. result = await db.execute(select(Printer).where(Printer.id == plug.printer_id))
  282. printer = result.scalar_one_or_none()
  283. printer_name = printer.name if printer else None
  284. await mqtt_relay.on_smart_plug_state(
  285. plug_id=plug.id,
  286. plug_name=plug.name,
  287. state="on" if expected_state == "ON" else "off",
  288. printer_id=plug.printer_id,
  289. printer_name=printer_name,
  290. )
  291. except Exception:
  292. pass # Don't fail if MQTT fails
  293. return {"success": True, "action": control.action}
  294. @router.get("/{plug_id}/status", response_model=SmartPlugStatus)
  295. async def get_plug_status(plug_id: int, db: AsyncSession = Depends(get_db)):
  296. """Get current plug status from device including energy data."""
  297. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  298. plug = result.scalar_one_or_none()
  299. if not plug:
  300. raise HTTPException(404, "Smart plug not found")
  301. service = await _get_service_for_plug(plug, db)
  302. status = await service.get_status(plug)
  303. # Update last state in database
  304. if status["reachable"]:
  305. plug.last_state = status["state"]
  306. plug.last_checked = datetime.utcnow()
  307. await db.commit()
  308. # Fetch energy data if device is reachable
  309. energy_data = None
  310. if status["reachable"]:
  311. energy = await service.get_energy(plug)
  312. if energy:
  313. energy_data = SmartPlugEnergy(**energy)
  314. # Check power alerts
  315. await check_power_alerts(plug, energy.get("power"), db)
  316. return SmartPlugStatus(
  317. state=status["state"],
  318. reachable=status["reachable"],
  319. device_name=status.get("device_name"),
  320. energy=energy_data,
  321. )
  322. async def check_power_alerts(plug: SmartPlug, current_power: float | None, db: AsyncSession):
  323. """Check if power crosses alert thresholds and send notifications."""
  324. if not plug.power_alert_enabled or current_power is None:
  325. return
  326. # Cooldown: don't alert more than once per 5 minutes
  327. cooldown_minutes = 5
  328. if plug.power_alert_last_triggered:
  329. time_since_last = datetime.utcnow() - plug.power_alert_last_triggered
  330. if time_since_last < timedelta(minutes=cooldown_minutes):
  331. return
  332. alert_triggered = False
  333. alert_type = None
  334. threshold = None
  335. # Check high threshold
  336. if plug.power_alert_high is not None and current_power > plug.power_alert_high:
  337. alert_triggered = True
  338. alert_type = "high"
  339. threshold = plug.power_alert_high
  340. # Check low threshold
  341. if plug.power_alert_low is not None and current_power < plug.power_alert_low:
  342. alert_triggered = True
  343. alert_type = "low"
  344. threshold = plug.power_alert_low
  345. if alert_triggered:
  346. plug.power_alert_last_triggered = datetime.utcnow()
  347. await db.commit()
  348. # Send notification
  349. title = f"Power Alert: {plug.name}"
  350. if alert_type == "high":
  351. message = f"Power consumption is {current_power:.1f}W, above threshold of {threshold:.1f}W"
  352. else:
  353. message = f"Power consumption is {current_power:.1f}W, below threshold of {threshold:.1f}W"
  354. logger.info(f"Power alert triggered for {plug.name}: {message}")
  355. # Use printer_error event type for power alerts (closest match)
  356. await notification_service.send_notification(
  357. event_type="printer_error",
  358. title=title,
  359. message=message,
  360. printer_id=plug.printer_id,
  361. printer_name=plug.name,
  362. context={
  363. "error_type": f"Power {alert_type.title()}",
  364. "error_detail": message,
  365. },
  366. )
  367. @router.post("/test-connection")
  368. async def test_connection(data: SmartPlugTestConnection):
  369. """Test connection to a Tasmota device."""
  370. result = await tasmota_service.test_connection(
  371. data.ip_address,
  372. data.username,
  373. data.password,
  374. )
  375. if not result["success"]:
  376. raise HTTPException(503, result.get("error", "Failed to connect to device"))
  377. return {
  378. "success": True,
  379. "state": result["state"],
  380. "device_name": result.get("device_name"),
  381. }