smart_plugs.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. """API routes for smart plug management."""
  2. import logging
  3. from datetime import datetime
  4. from fastapi import APIRouter, Depends, HTTPException, Query
  5. from sqlalchemy.ext.asyncio import AsyncSession
  6. from sqlalchemy import select
  7. from backend.app.core.database import get_db
  8. from backend.app.models.smart_plug import SmartPlug
  9. from backend.app.models.printer import Printer
  10. from backend.app.schemas.smart_plug import (
  11. SmartPlugCreate,
  12. SmartPlugUpdate,
  13. SmartPlugResponse,
  14. SmartPlugControl,
  15. SmartPlugStatus,
  16. SmartPlugTestConnection,
  17. )
  18. from backend.app.services.tasmota import tasmota_service
  19. logger = logging.getLogger(__name__)
  20. router = APIRouter(prefix="/smart-plugs", tags=["smart-plugs"])
  21. @router.get("/", response_model=list[SmartPlugResponse])
  22. async def list_smart_plugs(db: AsyncSession = Depends(get_db)):
  23. """List all smart plugs."""
  24. result = await db.execute(select(SmartPlug).order_by(SmartPlug.name))
  25. return list(result.scalars().all())
  26. @router.post("/", response_model=SmartPlugResponse)
  27. async def create_smart_plug(
  28. data: SmartPlugCreate,
  29. db: AsyncSession = Depends(get_db),
  30. ):
  31. """Create a new smart plug."""
  32. # Validate printer_id if provided
  33. if data.printer_id:
  34. result = await db.execute(
  35. select(Printer).where(Printer.id == data.printer_id)
  36. )
  37. if not result.scalar_one_or_none():
  38. raise HTTPException(400, "Printer not found")
  39. # Check if printer already has a plug assigned
  40. result = await db.execute(
  41. select(SmartPlug).where(SmartPlug.printer_id == data.printer_id)
  42. )
  43. if result.scalar_one_or_none():
  44. raise HTTPException(400, "This printer already has a smart plug assigned")
  45. plug = SmartPlug(**data.model_dump())
  46. db.add(plug)
  47. await db.commit()
  48. await db.refresh(plug)
  49. logger.info(f"Created smart plug '{plug.name}' at {plug.ip_address}")
  50. return plug
  51. @router.get("/by-printer/{printer_id}", response_model=SmartPlugResponse | None)
  52. async def get_smart_plug_by_printer(printer_id: int, db: AsyncSession = Depends(get_db)):
  53. """Get the smart plug assigned to a printer."""
  54. result = await db.execute(
  55. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  56. )
  57. plug = result.scalar_one_or_none()
  58. if not plug:
  59. return None
  60. return plug
  61. @router.get("/{plug_id}", response_model=SmartPlugResponse)
  62. async def get_smart_plug(plug_id: int, db: AsyncSession = Depends(get_db)):
  63. """Get a specific smart plug."""
  64. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  65. plug = result.scalar_one_or_none()
  66. if not plug:
  67. raise HTTPException(404, "Smart plug not found")
  68. return plug
  69. @router.patch("/{plug_id}", response_model=SmartPlugResponse)
  70. async def update_smart_plug(
  71. plug_id: int,
  72. data: SmartPlugUpdate,
  73. db: AsyncSession = Depends(get_db),
  74. ):
  75. """Update a smart plug."""
  76. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  77. plug = result.scalar_one_or_none()
  78. if not plug:
  79. raise HTTPException(404, "Smart plug not found")
  80. update_data = data.model_dump(exclude_unset=True)
  81. # Validate new printer_id if being changed
  82. if "printer_id" in update_data and update_data["printer_id"]:
  83. new_printer_id = update_data["printer_id"]
  84. # Check printer exists
  85. result = await db.execute(
  86. select(Printer).where(Printer.id == new_printer_id)
  87. )
  88. if not result.scalar_one_or_none():
  89. raise HTTPException(400, "Printer not found")
  90. # Check if that printer already has a different plug assigned
  91. result = await db.execute(
  92. select(SmartPlug).where(
  93. SmartPlug.printer_id == new_printer_id,
  94. SmartPlug.id != plug_id,
  95. )
  96. )
  97. if result.scalar_one_or_none():
  98. raise HTTPException(400, "This printer already has a smart plug assigned")
  99. for field, value in update_data.items():
  100. setattr(plug, field, value)
  101. await db.commit()
  102. await db.refresh(plug)
  103. logger.info(f"Updated smart plug '{plug.name}'")
  104. return plug
  105. @router.delete("/{plug_id}")
  106. async def delete_smart_plug(plug_id: int, db: AsyncSession = Depends(get_db)):
  107. """Delete a smart plug."""
  108. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  109. plug = result.scalar_one_or_none()
  110. if not plug:
  111. raise HTTPException(404, "Smart plug not found")
  112. plug_name = plug.name
  113. await db.delete(plug)
  114. await db.commit()
  115. logger.info(f"Deleted smart plug '{plug_name}'")
  116. return {"message": "Smart plug deleted"}
  117. @router.post("/{plug_id}/control")
  118. async def control_smart_plug(
  119. plug_id: int,
  120. control: SmartPlugControl,
  121. db: AsyncSession = Depends(get_db),
  122. ):
  123. """Manual control: on/off/toggle."""
  124. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  125. plug = result.scalar_one_or_none()
  126. if not plug:
  127. raise HTTPException(404, "Smart plug not found")
  128. if control.action == "on":
  129. success = await tasmota_service.turn_on(plug)
  130. expected_state = "ON"
  131. elif control.action == "off":
  132. success = await tasmota_service.turn_off(plug)
  133. expected_state = "OFF"
  134. elif control.action == "toggle":
  135. success = await tasmota_service.toggle(plug)
  136. expected_state = None # Unknown after toggle
  137. else:
  138. raise HTTPException(400, f"Invalid action: {control.action}")
  139. if not success:
  140. raise HTTPException(503, "Failed to communicate with device")
  141. # Update last state
  142. if expected_state:
  143. plug.last_state = expected_state
  144. plug.last_checked = datetime.utcnow()
  145. await db.commit()
  146. return {"success": True, "action": control.action}
  147. @router.get("/{plug_id}/status", response_model=SmartPlugStatus)
  148. async def get_plug_status(plug_id: int, db: AsyncSession = Depends(get_db)):
  149. """Get current plug status from device."""
  150. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  151. plug = result.scalar_one_or_none()
  152. if not plug:
  153. raise HTTPException(404, "Smart plug not found")
  154. status = await tasmota_service.get_status(plug)
  155. # Update last state in database
  156. if status["reachable"]:
  157. plug.last_state = status["state"]
  158. plug.last_checked = datetime.utcnow()
  159. await db.commit()
  160. return SmartPlugStatus(
  161. state=status["state"],
  162. reachable=status["reachable"],
  163. device_name=status.get("device_name"),
  164. )
  165. @router.post("/test-connection")
  166. async def test_connection(data: SmartPlugTestConnection):
  167. """Test connection to a Tasmota device."""
  168. result = await tasmota_service.test_connection(
  169. data.ip_address,
  170. data.username,
  171. data.password,
  172. )
  173. if not result["success"]:
  174. raise HTTPException(503, result.get("error", "Failed to connect to device"))
  175. return {
  176. "success": True,
  177. "state": result["state"],
  178. "device_name": result.get("device_name"),
  179. }