print_queue.py 18 KB

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