print_scheduler.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import logging
  4. from datetime import datetime
  5. from sqlalchemy import select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from backend.app.core.config import settings
  8. from backend.app.core.database import async_session
  9. from backend.app.models.archive import PrintArchive
  10. from backend.app.models.library import LibraryFile
  11. from backend.app.models.print_queue import PrintQueueItem
  12. from backend.app.models.printer import Printer
  13. from backend.app.models.smart_plug import SmartPlug
  14. from backend.app.services.bambu_ftp import delete_file_async, get_ftp_retry_settings, upload_file_async, with_ftp_retry
  15. from backend.app.services.printer_manager import printer_manager
  16. from backend.app.services.tasmota import tasmota_service
  17. logger = logging.getLogger(__name__)
  18. class PrintScheduler:
  19. """Background scheduler that processes the print queue."""
  20. def __init__(self):
  21. self._running = False
  22. self._check_interval = 30 # seconds
  23. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  24. self._power_on_check_interval = 10 # seconds between connection checks
  25. async def run(self):
  26. """Main loop - check queue every interval."""
  27. self._running = True
  28. logger.info("Print scheduler started")
  29. while self._running:
  30. try:
  31. await self.check_queue()
  32. except Exception as e:
  33. logger.error(f"Scheduler error: {e}")
  34. await asyncio.sleep(self._check_interval)
  35. def stop(self):
  36. """Stop the scheduler."""
  37. self._running = False
  38. logger.info("Print scheduler stopped")
  39. async def check_queue(self):
  40. """Check for prints ready to start."""
  41. async with async_session() as db:
  42. # Get all pending items, ordered by printer and position
  43. result = await db.execute(
  44. select(PrintQueueItem)
  45. .where(PrintQueueItem.status == "pending")
  46. .order_by(PrintQueueItem.printer_id, PrintQueueItem.position)
  47. )
  48. items = list(result.scalars().all())
  49. if not items:
  50. return
  51. # Group by printer - only process first item per printer
  52. processed_printers = set()
  53. for item in items:
  54. if item.printer_id in processed_printers:
  55. continue
  56. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  57. if item.scheduled_time and item.scheduled_time > datetime.utcnow():
  58. continue
  59. # Skip items that require manual start
  60. if item.manual_start:
  61. continue
  62. # Check if printer is idle
  63. printer_idle = self._is_printer_idle(item.printer_id)
  64. printer_connected = printer_manager.is_connected(item.printer_id)
  65. # If printer not connected, try to power on via smart plug
  66. if not printer_connected:
  67. plug = await self._get_smart_plug(db, item.printer_id)
  68. if plug and plug.auto_on and plug.enabled:
  69. logger.info(f"Printer {item.printer_id} offline, attempting to power on via smart plug")
  70. powered_on = await self._power_on_and_wait(plug, item.printer_id, db)
  71. if powered_on:
  72. printer_connected = True
  73. printer_idle = self._is_printer_idle(item.printer_id)
  74. else:
  75. logger.warning(f"Could not power on printer {item.printer_id} via smart plug")
  76. processed_printers.add(item.printer_id)
  77. continue
  78. else:
  79. # No plug or auto_on disabled
  80. processed_printers.add(item.printer_id)
  81. continue
  82. # Check if printer is idle (busy with another print)
  83. if not printer_idle:
  84. processed_printers.add(item.printer_id)
  85. continue
  86. # Check condition (previous print success)
  87. if item.require_previous_success:
  88. if not await self._check_previous_success(db, item):
  89. item.status = "skipped"
  90. item.error_message = "Previous print failed or was aborted"
  91. item.completed_at = datetime.now()
  92. await db.commit()
  93. logger.info(f"Skipped queue item {item.id} - previous print failed")
  94. continue
  95. # Start the print
  96. await self._start_print(db, item)
  97. processed_printers.add(item.printer_id)
  98. def _is_printer_idle(self, printer_id: int) -> bool:
  99. """Check if a printer is connected and idle."""
  100. if not printer_manager.is_connected(printer_id):
  101. return False
  102. state = printer_manager.get_status(printer_id)
  103. if not state:
  104. return False
  105. # Printer is idle if state is IDLE, FINISH, FAILED, or unknown
  106. # FAILED means previous print failed, printer is ready for new print
  107. return state.state in ("IDLE", "FINISH", "FAILED", "unknown")
  108. async def _get_smart_plug(self, db: AsyncSession, printer_id: int) -> SmartPlug | None:
  109. """Get the smart plug associated with a printer."""
  110. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  111. return result.scalar_one_or_none()
  112. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  113. """Turn on smart plug and wait for printer to connect.
  114. Returns True if printer connected successfully within timeout.
  115. """
  116. # Check current plug state
  117. status = await tasmota_service.get_status(plug)
  118. if not status.get("reachable"):
  119. logger.warning(f"Smart plug '{plug.name}' is not reachable")
  120. return False
  121. # Turn on if not already on
  122. if status.get("state") != "ON":
  123. success = await tasmota_service.turn_on(plug)
  124. if not success:
  125. logger.warning(f"Failed to turn on smart plug '{plug.name}'")
  126. return False
  127. logger.info(f"Powered on smart plug '{plug.name}' for printer {printer_id}")
  128. # Get printer from database for connection
  129. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  130. printer = result.scalar_one_or_none()
  131. if not printer:
  132. logger.error(f"Printer {printer_id} not found in database")
  133. return False
  134. # Wait for printer to boot (give it some time before trying to connect)
  135. logger.info(f"Waiting 30s for printer {printer_id} to boot...")
  136. await asyncio.sleep(30)
  137. # Try to connect to the printer periodically
  138. elapsed = 30 # Already waited 30s
  139. while elapsed < self._power_on_wait_time:
  140. # Try to connect
  141. logger.info(f"Attempting to connect to printer {printer_id}...")
  142. try:
  143. connected = await printer_manager.connect_printer(printer)
  144. if connected:
  145. logger.info(f"Printer {printer_id} connected after {elapsed}s")
  146. # Give it a moment to stabilize and get status
  147. await asyncio.sleep(5)
  148. return True
  149. except Exception as e:
  150. logger.debug(f"Connection attempt failed: {e}")
  151. await asyncio.sleep(self._power_on_check_interval)
  152. elapsed += self._power_on_check_interval
  153. logger.debug(f"Waiting for printer {printer_id} to connect... ({elapsed}s)")
  154. logger.warning(f"Printer {printer_id} did not connect within {self._power_on_wait_time}s after power on")
  155. return False
  156. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  157. """Check if the previous print on this printer succeeded."""
  158. # Find the most recent completed queue item for this printer
  159. result = await db.execute(
  160. select(PrintQueueItem)
  161. .where(PrintQueueItem.printer_id == item.printer_id)
  162. .where(PrintQueueItem.id != item.id)
  163. .where(PrintQueueItem.status.in_(["completed", "failed", "skipped", "aborted"]))
  164. .order_by(PrintQueueItem.completed_at.desc())
  165. .limit(1)
  166. )
  167. prev_item = result.scalar_one_or_none()
  168. # If no previous item, assume success (first in queue)
  169. if not prev_item:
  170. return True
  171. return prev_item.status == "completed"
  172. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  173. """Power off printer if auto_off_after is enabled (waits for cooldown)."""
  174. if not item.auto_off_after:
  175. return
  176. plug = await self._get_smart_plug(db, item.printer_id)
  177. if plug and plug.enabled:
  178. logger.info(f"Auto-off: Waiting for printer {item.printer_id} to cool down before power off...")
  179. # Wait for cooldown (up to 10 minutes)
  180. await printer_manager.wait_for_cooldown(item.printer_id, target_temp=50.0, timeout=600)
  181. logger.info(f"Auto-off: Powering off printer {item.printer_id}")
  182. await tasmota_service.turn_off(plug)
  183. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  184. """Upload file and start print for a queue item.
  185. Supports two sources:
  186. - archive_id: Print from an existing archive
  187. - library_file_id: Print from a library file (file manager)
  188. """
  189. logger.info(f"Starting queue item {item.id}")
  190. # Get printer first (needed for both paths)
  191. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  192. printer = result.scalar_one_or_none()
  193. if not printer:
  194. item.status = "failed"
  195. item.error_message = "Printer not found"
  196. item.completed_at = datetime.utcnow()
  197. await db.commit()
  198. logger.error(f"Queue item {item.id}: Printer {item.printer_id} not found")
  199. await self._power_off_if_needed(db, item)
  200. return
  201. # Check printer is connected
  202. if not printer_manager.is_connected(item.printer_id):
  203. item.status = "failed"
  204. item.error_message = "Printer not connected"
  205. item.completed_at = datetime.utcnow()
  206. await db.commit()
  207. logger.error(f"Queue item {item.id}: Printer {item.printer_id} not connected")
  208. await self._power_off_if_needed(db, item)
  209. return
  210. # Determine source: archive or library file
  211. archive = None
  212. library_file = None
  213. file_path = None
  214. filename = None
  215. if item.archive_id:
  216. # Print from archive
  217. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  218. archive = result.scalar_one_or_none()
  219. if not archive:
  220. item.status = "failed"
  221. item.error_message = "Archive not found"
  222. item.completed_at = datetime.utcnow()
  223. await db.commit()
  224. logger.error(f"Queue item {item.id}: Archive {item.archive_id} not found")
  225. await self._power_off_if_needed(db, item)
  226. return
  227. file_path = settings.base_dir / archive.file_path
  228. filename = archive.filename
  229. elif item.library_file_id:
  230. # Print from library file (file manager)
  231. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  232. library_file = result.scalar_one_or_none()
  233. if not library_file:
  234. item.status = "failed"
  235. item.error_message = "Library file not found"
  236. item.completed_at = datetime.utcnow()
  237. await db.commit()
  238. logger.error(f"Queue item {item.id}: Library file {item.library_file_id} not found")
  239. await self._power_off_if_needed(db, item)
  240. return
  241. # Library files store absolute paths
  242. from pathlib import Path
  243. lib_path = Path(library_file.file_path)
  244. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  245. filename = library_file.filename
  246. else:
  247. # Neither archive nor library file specified
  248. item.status = "failed"
  249. item.error_message = "No source file specified"
  250. item.completed_at = datetime.utcnow()
  251. await db.commit()
  252. logger.error(f"Queue item {item.id}: No archive_id or library_file_id specified")
  253. await self._power_off_if_needed(db, item)
  254. return
  255. # Check file exists on disk
  256. if not file_path.exists():
  257. item.status = "failed"
  258. item.error_message = "Source file not found on disk"
  259. item.completed_at = datetime.utcnow()
  260. await db.commit()
  261. logger.error(f"Queue item {item.id}: File not found: {file_path}")
  262. await self._power_off_if_needed(db, item)
  263. return
  264. # Upload file to printer via FTP
  265. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  266. base_name = filename
  267. if base_name.endswith(".gcode.3mf"):
  268. base_name = base_name[:-10] # Remove .gcode.3mf
  269. elif base_name.endswith(".3mf"):
  270. base_name = base_name[:-4] # Remove .3mf
  271. remote_filename = f"{base_name}.3mf"
  272. # Upload to root directory (not /cache/) - the start_print command references
  273. # files by name only (ftp://{filename}), so they must be in the root
  274. remote_path = f"/{remote_filename}"
  275. # Get FTP retry settings
  276. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  277. # Delete existing file if present (avoids 553 error on overwrite)
  278. try:
  279. await delete_file_async(
  280. printer.ip_address,
  281. printer.access_code,
  282. remote_path,
  283. socket_timeout=ftp_timeout,
  284. printer_model=printer.model,
  285. )
  286. except Exception:
  287. pass # File may not exist, that's fine
  288. try:
  289. if ftp_retry_enabled:
  290. uploaded = await with_ftp_retry(
  291. upload_file_async,
  292. printer.ip_address,
  293. printer.access_code,
  294. file_path,
  295. remote_path,
  296. socket_timeout=ftp_timeout,
  297. printer_model=printer.model,
  298. max_retries=ftp_retry_count,
  299. retry_delay=ftp_retry_delay,
  300. operation_name=f"Upload print to {printer.name}",
  301. )
  302. else:
  303. uploaded = await upload_file_async(
  304. printer.ip_address,
  305. printer.access_code,
  306. file_path,
  307. remote_path,
  308. socket_timeout=ftp_timeout,
  309. printer_model=printer.model,
  310. )
  311. except Exception as e:
  312. uploaded = False
  313. logger.error(f"Queue item {item.id}: FTP error: {e}")
  314. if not uploaded:
  315. item.status = "failed"
  316. item.error_message = "Failed to upload file to printer"
  317. item.completed_at = datetime.utcnow()
  318. await db.commit()
  319. logger.error(f"Queue item {item.id}: FTP upload failed")
  320. await self._power_off_if_needed(db, item)
  321. return
  322. # Register as expected print so we don't create a duplicate archive
  323. # Only applicable for archive-based prints
  324. if archive:
  325. from backend.app.main import register_expected_print
  326. register_expected_print(item.printer_id, remote_filename, archive.id)
  327. # Parse AMS mapping if stored
  328. ams_mapping = None
  329. if item.ams_mapping:
  330. try:
  331. import json
  332. ams_mapping = json.loads(item.ams_mapping)
  333. except json.JSONDecodeError:
  334. logger.warning(f"Queue item {item.id}: Invalid AMS mapping JSON, ignoring")
  335. # Start the print with AMS mapping, plate_id and print options
  336. started = printer_manager.start_print(
  337. item.printer_id,
  338. remote_filename,
  339. plate_id=item.plate_id or 1,
  340. ams_mapping=ams_mapping,
  341. bed_levelling=item.bed_levelling,
  342. flow_cali=item.flow_cali,
  343. vibration_cali=item.vibration_cali,
  344. layer_inspect=item.layer_inspect,
  345. timelapse=item.timelapse,
  346. use_ams=item.use_ams,
  347. )
  348. if started:
  349. item.status = "printing"
  350. item.started_at = datetime.utcnow()
  351. await db.commit()
  352. logger.info(f"Queue item {item.id}: Print started - {filename}")
  353. # MQTT relay - publish queue job started
  354. try:
  355. from backend.app.services.mqtt_relay import mqtt_relay
  356. await mqtt_relay.on_queue_job_started(
  357. job_id=item.id,
  358. filename=filename,
  359. printer_id=printer.id,
  360. printer_name=printer.name,
  361. printer_serial=printer.serial_number,
  362. )
  363. except Exception:
  364. pass # Don't fail if MQTT fails
  365. else:
  366. item.status = "failed"
  367. item.error_message = "Failed to send print command"
  368. item.completed_at = datetime.utcnow()
  369. await db.commit()
  370. logger.error(f"Queue item {item.id}: Failed to start print")
  371. await self._power_off_if_needed(db, item)
  372. # Global scheduler instance
  373. scheduler = PrintScheduler()