print_queue.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. """API routes for print queue management."""
  2. import json
  3. import logging
  4. from datetime import datetime
  5. from fastapi import APIRouter, Depends, HTTPException, Query
  6. from sqlalchemy import func, select
  7. from sqlalchemy.ext.asyncio import AsyncSession
  8. from sqlalchemy.orm import selectinload
  9. from backend.app.core.database import get_db
  10. from backend.app.models.archive import PrintArchive
  11. from backend.app.models.library import LibraryFile
  12. from backend.app.models.print_queue import PrintQueueItem
  13. from backend.app.models.printer import Printer
  14. from backend.app.schemas.print_queue import (
  15. PrintQueueBulkUpdate,
  16. PrintQueueBulkUpdateResponse,
  17. PrintQueueItemCreate,
  18. PrintQueueItemResponse,
  19. PrintQueueItemUpdate,
  20. PrintQueueReorder,
  21. )
  22. logger = logging.getLogger(__name__)
  23. router = APIRouter(prefix="/queue", tags=["queue"])
  24. def _enrich_response(item: PrintQueueItem) -> PrintQueueItemResponse:
  25. """Add nested archive/printer/library_file info to response."""
  26. # Parse ams_mapping from JSON string BEFORE model_validate
  27. ams_mapping_parsed = None
  28. if item.ams_mapping:
  29. try:
  30. ams_mapping_parsed = json.loads(item.ams_mapping)
  31. except json.JSONDecodeError:
  32. ams_mapping_parsed = None
  33. # Create response with parsed ams_mapping
  34. item_dict = {
  35. "id": item.id,
  36. "printer_id": item.printer_id,
  37. "archive_id": item.archive_id,
  38. "library_file_id": item.library_file_id,
  39. "position": item.position,
  40. "scheduled_time": item.scheduled_time,
  41. "require_previous_success": item.require_previous_success,
  42. "auto_off_after": item.auto_off_after,
  43. "manual_start": item.manual_start,
  44. "ams_mapping": ams_mapping_parsed,
  45. "plate_id": item.plate_id,
  46. "bed_levelling": item.bed_levelling,
  47. "flow_cali": item.flow_cali,
  48. "vibration_cali": item.vibration_cali,
  49. "layer_inspect": item.layer_inspect,
  50. "timelapse": item.timelapse,
  51. "use_ams": item.use_ams,
  52. "status": item.status,
  53. "started_at": item.started_at,
  54. "completed_at": item.completed_at,
  55. "error_message": item.error_message,
  56. "created_at": item.created_at,
  57. }
  58. response = PrintQueueItemResponse(**item_dict)
  59. if item.archive:
  60. response.archive_name = item.archive.print_name or item.archive.filename
  61. response.archive_thumbnail = item.archive.thumbnail_path
  62. response.print_time_seconds = item.archive.print_time_seconds
  63. if item.library_file:
  64. response.library_file_name = (
  65. item.library_file.file_metadata.get("print_name") if item.library_file.file_metadata else None
  66. )
  67. if not response.library_file_name:
  68. response.library_file_name = item.library_file.filename
  69. response.library_file_thumbnail = item.library_file.thumbnail_path
  70. # Get print time from library file metadata if no archive
  71. if not item.archive and item.library_file.file_metadata:
  72. response.print_time_seconds = item.library_file.file_metadata.get("print_time_seconds")
  73. if item.printer:
  74. response.printer_name = item.printer.name
  75. return response
  76. @router.get("/", response_model=list[PrintQueueItemResponse])
  77. async def list_queue(
  78. printer_id: int | None = Query(None, description="Filter by printer (-1 for unassigned)"),
  79. status: str | None = Query(None, description="Filter by status"),
  80. db: AsyncSession = Depends(get_db),
  81. ):
  82. """List all queue items, optionally filtered by printer or status."""
  83. query = (
  84. select(PrintQueueItem)
  85. .options(
  86. selectinload(PrintQueueItem.archive),
  87. selectinload(PrintQueueItem.printer),
  88. selectinload(PrintQueueItem.library_file),
  89. )
  90. .order_by(PrintQueueItem.printer_id.nulls_first(), PrintQueueItem.position)
  91. )
  92. if printer_id is not None:
  93. if printer_id == -1:
  94. # Special value: filter for unassigned items
  95. query = query.where(PrintQueueItem.printer_id.is_(None))
  96. else:
  97. query = query.where(PrintQueueItem.printer_id == printer_id)
  98. if status:
  99. query = query.where(PrintQueueItem.status == status)
  100. result = await db.execute(query)
  101. items = result.scalars().all()
  102. return [_enrich_response(item) for item in items]
  103. @router.post("/", response_model=PrintQueueItemResponse)
  104. async def add_to_queue(
  105. data: PrintQueueItemCreate,
  106. db: AsyncSession = Depends(get_db),
  107. ):
  108. """Add an item to the print queue."""
  109. # Validate that either archive_id or library_file_id is provided
  110. if not data.archive_id and not data.library_file_id:
  111. raise HTTPException(400, "Either archive_id or library_file_id must be provided")
  112. # Validate printer exists (if assigned)
  113. if data.printer_id is not None:
  114. result = await db.execute(select(Printer).where(Printer.id == data.printer_id))
  115. if not result.scalar_one_or_none():
  116. raise HTTPException(400, "Printer not found")
  117. # Validate archive exists (if provided)
  118. if data.archive_id:
  119. result = await db.execute(select(PrintArchive).where(PrintArchive.id == data.archive_id))
  120. if not result.scalar_one_or_none():
  121. raise HTTPException(400, "Archive not found")
  122. # Validate library file exists (if provided)
  123. if data.library_file_id:
  124. result = await db.execute(select(LibraryFile).where(LibraryFile.id == data.library_file_id))
  125. if not result.scalar_one_or_none():
  126. raise HTTPException(400, "Library file not found")
  127. # Get next position for this printer (or for unassigned items)
  128. if data.printer_id is not None:
  129. result = await db.execute(
  130. select(func.max(PrintQueueItem.position))
  131. .where(PrintQueueItem.printer_id == data.printer_id)
  132. .where(PrintQueueItem.status == "pending")
  133. )
  134. else:
  135. # For unassigned items, get max position across all unassigned
  136. result = await db.execute(
  137. select(func.max(PrintQueueItem.position))
  138. .where(PrintQueueItem.printer_id.is_(None))
  139. .where(PrintQueueItem.status == "pending")
  140. )
  141. max_pos = result.scalar() or 0
  142. item = PrintQueueItem(
  143. printer_id=data.printer_id,
  144. archive_id=data.archive_id,
  145. library_file_id=data.library_file_id,
  146. scheduled_time=data.scheduled_time,
  147. require_previous_success=data.require_previous_success,
  148. auto_off_after=data.auto_off_after,
  149. manual_start=data.manual_start,
  150. ams_mapping=json.dumps(data.ams_mapping) if data.ams_mapping else None,
  151. plate_id=data.plate_id,
  152. bed_levelling=data.bed_levelling,
  153. flow_cali=data.flow_cali,
  154. vibration_cali=data.vibration_cali,
  155. layer_inspect=data.layer_inspect,
  156. timelapse=data.timelapse,
  157. use_ams=data.use_ams,
  158. position=max_pos + 1,
  159. status="pending",
  160. )
  161. db.add(item)
  162. await db.commit()
  163. await db.refresh(item)
  164. # Load relationships for response
  165. await db.refresh(item, ["archive", "printer", "library_file"])
  166. source_name = f"archive {data.archive_id}" if data.archive_id else f"library file {data.library_file_id}"
  167. logger.info(f"Added {source_name} to queue for printer {data.printer_id or 'unassigned'}")
  168. # MQTT relay - publish queue job added
  169. try:
  170. from backend.app.services.mqtt_relay import mqtt_relay
  171. await mqtt_relay.on_queue_job_added(
  172. job_id=item.id,
  173. filename=item.archive.filename if item.archive else "",
  174. printer_id=item.printer_id,
  175. printer_name=item.printer.name if item.printer else None,
  176. )
  177. except Exception:
  178. pass # Don't fail queue add if MQTT fails
  179. return _enrich_response(item)
  180. @router.patch("/bulk", response_model=PrintQueueBulkUpdateResponse)
  181. async def bulk_update_queue_items(
  182. data: PrintQueueBulkUpdate,
  183. db: AsyncSession = Depends(get_db),
  184. ):
  185. """Bulk update multiple queue items with the same values.
  186. Only pending items can be updated. Non-pending items are skipped.
  187. """
  188. if not data.item_ids:
  189. raise HTTPException(400, "No item IDs provided")
  190. # Get fields to update (exclude item_ids and unset fields)
  191. update_data = data.model_dump(exclude={"item_ids"}, exclude_unset=True)
  192. if not update_data:
  193. raise HTTPException(400, "No fields to update")
  194. # Validate printer_id if being changed
  195. if "printer_id" in update_data and update_data["printer_id"] is not None:
  196. result = await db.execute(select(Printer).where(Printer.id == update_data["printer_id"]))
  197. if not result.scalar_one_or_none():
  198. raise HTTPException(400, "Printer not found")
  199. # Fetch all items
  200. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id.in_(data.item_ids)))
  201. items = result.scalars().all()
  202. updated_count = 0
  203. skipped_count = 0
  204. for item in items:
  205. if item.status != "pending":
  206. skipped_count += 1
  207. continue
  208. for field, value in update_data.items():
  209. setattr(item, field, value)
  210. updated_count += 1
  211. await db.commit()
  212. logger.info(f"Bulk updated {updated_count} queue items, skipped {skipped_count}")
  213. return PrintQueueBulkUpdateResponse(
  214. updated_count=updated_count,
  215. skipped_count=skipped_count,
  216. message=f"Updated {updated_count} items" + (f", skipped {skipped_count} non-pending" if skipped_count else ""),
  217. )
  218. @router.get("/{item_id}", response_model=PrintQueueItemResponse)
  219. async def get_queue_item(item_id: int, db: AsyncSession = Depends(get_db)):
  220. """Get a specific queue item."""
  221. result = await db.execute(
  222. select(PrintQueueItem)
  223. .options(
  224. selectinload(PrintQueueItem.archive),
  225. selectinload(PrintQueueItem.printer),
  226. selectinload(PrintQueueItem.library_file),
  227. )
  228. .where(PrintQueueItem.id == item_id)
  229. )
  230. item = result.scalar_one_or_none()
  231. if not item:
  232. raise HTTPException(404, "Queue item not found")
  233. return _enrich_response(item)
  234. @router.patch("/{item_id}", response_model=PrintQueueItemResponse)
  235. async def update_queue_item(
  236. item_id: int,
  237. data: PrintQueueItemUpdate,
  238. db: AsyncSession = Depends(get_db),
  239. ):
  240. """Update a queue item."""
  241. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  242. item = result.scalar_one_or_none()
  243. if not item:
  244. raise HTTPException(404, "Queue item not found")
  245. if item.status != "pending":
  246. raise HTTPException(400, "Can only update pending items")
  247. update_data = data.model_dump(exclude_unset=True)
  248. # Validate new printer_id if being changed (and not None)
  249. if "printer_id" in update_data and update_data["printer_id"] is not None:
  250. result = await db.execute(select(Printer).where(Printer.id == update_data["printer_id"]))
  251. if not result.scalar_one_or_none():
  252. raise HTTPException(400, "Printer not found")
  253. # Serialize ams_mapping to JSON for TEXT column storage
  254. if "ams_mapping" in update_data:
  255. update_data["ams_mapping"] = json.dumps(update_data["ams_mapping"]) if update_data["ams_mapping"] else None
  256. for field, value in update_data.items():
  257. setattr(item, field, value)
  258. await db.commit()
  259. await db.refresh(item, ["archive", "printer", "library_file"])
  260. logger.info(f"Updated queue item {item_id}")
  261. return _enrich_response(item)
  262. @router.delete("/{item_id}")
  263. async def delete_queue_item(item_id: int, db: AsyncSession = Depends(get_db)):
  264. """Remove an item from the queue."""
  265. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  266. item = result.scalar_one_or_none()
  267. if not item:
  268. raise HTTPException(404, "Queue item not found")
  269. if item.status == "printing":
  270. raise HTTPException(400, "Cannot delete item that is currently printing")
  271. await db.delete(item)
  272. await db.commit()
  273. logger.info(f"Deleted queue item {item_id}")
  274. return {"message": "Queue item deleted"}
  275. @router.post("/reorder")
  276. async def reorder_queue(
  277. data: PrintQueueReorder,
  278. db: AsyncSession = Depends(get_db),
  279. ):
  280. """Bulk update positions for queue items."""
  281. for reorder_item in data.items:
  282. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == reorder_item.id))
  283. item = result.scalar_one_or_none()
  284. if item and item.status == "pending":
  285. item.position = reorder_item.position
  286. await db.commit()
  287. logger.info(f"Reordered {len(data.items)} queue items")
  288. return {"message": f"Reordered {len(data.items)} items"}
  289. @router.post("/{item_id}/cancel")
  290. async def cancel_queue_item(item_id: int, db: AsyncSession = Depends(get_db)):
  291. """Cancel a pending queue item."""
  292. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  293. item = result.scalar_one_or_none()
  294. if not item:
  295. raise HTTPException(404, "Queue item not found")
  296. if item.status not in ("pending",):
  297. raise HTTPException(400, f"Cannot cancel item with status '{item.status}'")
  298. item.status = "cancelled"
  299. item.completed_at = datetime.now()
  300. await db.commit()
  301. logger.info(f"Cancelled queue item {item_id}")
  302. return {"message": "Queue item cancelled"}
  303. @router.post("/{item_id}/stop")
  304. async def stop_queue_item(
  305. item_id: int,
  306. db: AsyncSession = Depends(get_db),
  307. ):
  308. """Stop an actively printing queue item."""
  309. import asyncio
  310. from backend.app.models.smart_plug import SmartPlug
  311. from backend.app.services.printer_manager import printer_manager
  312. from backend.app.services.tasmota import tasmota_service
  313. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  314. item = result.scalar_one_or_none()
  315. if not item:
  316. raise HTTPException(404, "Queue item not found")
  317. if item.status != "printing":
  318. raise HTTPException(400, f"Can only stop items that are printing, current status: '{item.status}'")
  319. # Capture values we need for background task
  320. printer_id = item.printer_id
  321. auto_off_after = item.auto_off_after
  322. # Try to send stop command to printer
  323. stop_sent = False
  324. try:
  325. stop_sent = printer_manager.stop_print(printer_id)
  326. if not stop_sent:
  327. logger.warning(f"stop_print returned False for printer {printer_id} - printer may not be connected")
  328. except Exception as e:
  329. logger.error(f"Error sending stop command for queue item {item_id}: {e}")
  330. # Update queue item status regardless - if printer is off, print is already stopped
  331. item.status = "cancelled"
  332. item.completed_at = datetime.now()
  333. item.error_message = "Stopped by user" if stop_sent else "Stopped by user (printer was offline)"
  334. await db.commit()
  335. # Get smart plug info if auto-off is enabled
  336. plug_ip = None
  337. if auto_off_after:
  338. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  339. plug = result.scalar_one_or_none()
  340. if plug and plug.enabled:
  341. plug_ip = plug.ip_address
  342. logger.info(f"Stopped printing queue item {item_id} (stop command sent: {stop_sent})")
  343. # Schedule background task for cooldown + power off
  344. if plug_ip:
  345. async def cooldown_and_poweroff():
  346. logger.info(f"Auto-off: Waiting for printer {printer_id} to cool down before power off...")
  347. await printer_manager.wait_for_cooldown(printer_id, target_temp=50.0, timeout=600)
  348. # Re-fetch plug since we're in a new async context
  349. from backend.app.core.database import async_session
  350. async with async_session() as new_db:
  351. result = await new_db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  352. plug = result.scalar_one_or_none()
  353. if plug and plug.enabled:
  354. logger.info(f"Auto-off: Powering off printer {printer_id}")
  355. await tasmota_service.turn_off(plug)
  356. asyncio.create_task(cooldown_and_poweroff())
  357. return {"message": "Print stopped" if stop_sent else "Queue item cancelled (printer was offline)"}
  358. @router.post("/{item_id}/start")
  359. async def start_queue_item(
  360. item_id: int,
  361. db: AsyncSession = Depends(get_db),
  362. ):
  363. """Manually start a staged (manual_start) queue item.
  364. This clears the manual_start flag so the scheduler will pick it up,
  365. or starts immediately if the printer is ready.
  366. """
  367. result = await db.execute(
  368. select(PrintQueueItem)
  369. .options(selectinload(PrintQueueItem.archive), selectinload(PrintQueueItem.printer))
  370. .where(PrintQueueItem.id == item_id)
  371. )
  372. item = result.scalar_one_or_none()
  373. if not item:
  374. raise HTTPException(404, "Queue item not found")
  375. if item.status != "pending":
  376. raise HTTPException(400, f"Can only start pending items, current status: '{item.status}'")
  377. # Clear manual_start flag so scheduler picks it up
  378. item.manual_start = False
  379. await db.commit()
  380. await db.refresh(item, ["archive", "printer", "library_file"])
  381. logger.info(f"Manually started queue item {item_id} (cleared manual_start flag)")
  382. return _enrich_response(item)