smart_plugs.py 7.4 KB

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