print_scheduler.py 16 KB

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