print_scheduler.py 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. from datetime import datetime, timezone
  7. from pathlib import Path
  8. from sqlalchemy import func, select
  9. from sqlalchemy.ext.asyncio import AsyncSession
  10. from backend.app.core.config import settings
  11. from backend.app.core.database import async_session, run_with_retry
  12. from backend.app.models.archive import PrintArchive
  13. from backend.app.models.library import LibraryFile
  14. from backend.app.models.print_queue import PrintQueueItem
  15. from backend.app.models.printer import Printer
  16. from backend.app.models.settings import Settings
  17. from backend.app.models.smart_plug import SmartPlug
  18. from backend.app.services.bambu_ftp import (
  19. cache_3mf_download,
  20. delete_file_async,
  21. get_ftp_retry_settings,
  22. upload_file_async,
  23. with_ftp_retry,
  24. )
  25. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  26. from backend.app.services.notification_service import notification_service
  27. from backend.app.services.printer_manager import printer_manager, supports_drying
  28. from backend.app.services.smart_plug_manager import smart_plug_manager
  29. from backend.app.utils.printer_models import normalize_printer_model
  30. logger = logging.getLogger(__name__)
  31. # Bambu firmware states that mean the project_file has actually been accepted
  32. # and the printer is now processing / running / paused mid-print. Used by the
  33. # dispatch watchdog (#1370): a transition into one of these states means the
  34. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  35. # a post-print prompt) is NOT a valid "command landed" signal even though the
  36. # state value did change. SLICING is included because some firmwares park
  37. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  38. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  39. # Filament type equivalence groups — types within the same group are
  40. # interchangeable on the printer side (Bambu Lab firmware treats them as compatible).
  41. _FILAMENT_TYPE_GROUPS: list[list[str]] = [
  42. ["PA-CF", "PA12-CF", "PAHT-CF"],
  43. ]
  44. _FILAMENT_EQUIV_MAP: dict[str, str] = {}
  45. for _group in _FILAMENT_TYPE_GROUPS:
  46. _canonical = _group[0].upper()
  47. for _t in _group:
  48. _FILAMENT_EQUIV_MAP[_t.upper()] = _canonical
  49. def _canonical_filament_type(ftype: str) -> str:
  50. """Return canonical type for equivalence matching."""
  51. upper = ftype.upper()
  52. return _FILAMENT_EQUIV_MAP.get(upper, upper)
  53. class PrintScheduler:
  54. """Background scheduler that processes the print queue."""
  55. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  56. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  57. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  58. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  59. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  60. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  61. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  62. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  63. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  64. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  65. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  66. }
  67. def __init__(self):
  68. self._running = False
  69. self._check_interval = 30 # seconds
  70. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  71. self._power_on_check_interval = 10 # seconds between connection checks
  72. self._min_drying_seconds = 1800 # 30 minutes minimum before humidity re-check can stop drying
  73. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  74. self._drying_in_progress: dict[int, float] = {}
  75. # Defensive in-memory dispatch hold (#1157): a printer that just received
  76. # a project_file command must not get a second dispatch until either it
  77. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  78. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  79. # during that window the DB busy_printers seed is empirically unreliable
  80. # (multi-plate batches double-/triple-dispatched onto the same printer
  81. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  82. # or revert.
  83. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  84. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  85. # Minimum cooldown between dispatches to the same printer (covers the
  86. # H2D's project_file digestion window).
  87. self._dispatch_min_cooldown = 60.0
  88. # Hard timeout — drop the hold even if we never observed a transition,
  89. # so a lost MQTT session can't lock a printer out of the queue forever.
  90. # Matches the watchdog timeout (90 s) plus a safety margin so the
  91. # watchdog runs first on the unhappy path.
  92. self._dispatch_max_hold = 180.0
  93. async def run(self):
  94. """Main loop - check queue every interval."""
  95. self._running = True
  96. logger.info("Print scheduler started")
  97. while self._running:
  98. try:
  99. await self.check_queue()
  100. except Exception as e:
  101. logger.error("Scheduler error: %s", e)
  102. await asyncio.sleep(self._check_interval)
  103. def stop(self):
  104. """Stop the scheduler."""
  105. self._running = False
  106. logger.info("Print scheduler stopped")
  107. async def check_queue(self):
  108. """Check for prints ready to start."""
  109. async with async_session() as db:
  110. # Check if shortest-job-first scheduling is enabled
  111. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  112. # Get all pending items, ordered by printer and position (or SJF order)
  113. if sjf_enabled:
  114. # SJF: group by printer (and target_model for model-based jobs),
  115. # then items already jumped get top priority (starvation guard),
  116. # then sort by print_time ascending. Items with no print time go last.
  117. result = await db.execute(
  118. select(PrintQueueItem)
  119. .where(PrintQueueItem.status == "pending")
  120. .order_by(
  121. PrintQueueItem.printer_id,
  122. PrintQueueItem.target_model,
  123. PrintQueueItem.been_jumped.desc(),
  124. PrintQueueItem.print_time_seconds.asc().nullslast(),
  125. PrintQueueItem.position,
  126. )
  127. )
  128. else:
  129. result = await db.execute(
  130. select(PrintQueueItem)
  131. .where(PrintQueueItem.status == "pending")
  132. .order_by(PrintQueueItem.printer_id, PrintQueueItem.position)
  133. )
  134. items = list(result.scalars().all())
  135. # Read plate-clear setting once per queue check
  136. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=True)
  137. if not items:
  138. # No pending items — still check auto-drying on idle printers
  139. await self._check_auto_drying(db, [], set(), require_plate_clear=require_plate_clear)
  140. return
  141. logger.info(
  142. "Queue check: found %d pending items: %s",
  143. len(items),
  144. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  145. )
  146. # Seed busy_printers with printers that already have an item in 'printing'
  147. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  148. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  149. # lag several seconds behind the print command, so the next check_queue
  150. # tick still sees IDLE and would double-dispatch onto the same printer.
  151. # Without this guard, two pending items targeting the same printer
  152. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  153. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  154. busy_result = await db.execute(
  155. select(PrintQueueItem.printer_id)
  156. .where(PrintQueueItem.status == "printing")
  157. .where(PrintQueueItem.printer_id.is_not(None))
  158. )
  159. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  160. # Defense-in-depth (#1157): augment busy_printers with any printer
  161. # still in its post-dispatch hold window. Empirically, the DB seed
  162. # above can miss in-flight items in a multi-plate batch — same-file
  163. # plates were being dispatched 30 s apart while the H2D was still
  164. # digesting the first project_file. The hold is keyed in-memory and
  165. # released by the watchdog on the success path, so it adds a layer
  166. # that doesn't depend on DB row visibility or completion-callback
  167. # timing.
  168. for held_printer_id in list(self._dispatch_holds.keys()):
  169. if self._printer_in_dispatch_hold(held_printer_id):
  170. busy_printers.add(held_printer_id)
  171. # Log skip reasons once per queue check (not per item)
  172. skip_reasons: dict[str, int] = {}
  173. for item in items:
  174. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  175. if item.scheduled_time:
  176. sched = item.scheduled_time
  177. if sched.tzinfo is None:
  178. sched = sched.replace(tzinfo=timezone.utc)
  179. if sched > datetime.now(timezone.utc):
  180. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  181. continue
  182. # Skip items that require manual start
  183. if item.manual_start:
  184. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  185. continue
  186. if item.printer_id:
  187. # Specific printer assignment (existing behavior)
  188. if item.printer_id in busy_printers:
  189. continue
  190. # Check if printer is idle
  191. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  192. printer_connected = printer_manager.is_connected(item.printer_id)
  193. # If printer not connected, try to power on via smart plug
  194. if not printer_connected:
  195. plugs = await self._get_smart_plugs(db, item.printer_id)
  196. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  197. if auto_on_plugs:
  198. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  199. # Power on using the first auto_on plug (the printer power plug)
  200. powered_on = await self._power_on_and_wait(auto_on_plugs[0], item.printer_id, db)
  201. if powered_on:
  202. # Also turn on any remaining auto_on plugs (e.g., filter)
  203. for extra_plug in auto_on_plugs[1:]:
  204. try:
  205. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  206. await service.turn_on(extra_plug)
  207. logger.info(
  208. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  209. )
  210. except Exception as e:
  211. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  212. printer_connected = True
  213. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  214. else:
  215. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  216. busy_printers.add(item.printer_id)
  217. continue
  218. else:
  219. # No plug or auto_on disabled
  220. busy_printers.add(item.printer_id)
  221. continue
  222. # Check if printer is idle (busy with another print)
  223. if not printer_idle:
  224. # If printer is drying (not truly busy), handle based on queue_drying_block
  225. if self._drying_in_progress.get(item.printer_id):
  226. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  227. if block_for_drying:
  228. # Drying blocks queue — skip this printer
  229. busy_printers.add(item.printer_id)
  230. continue
  231. else:
  232. # Print takes priority — stop drying
  233. await self._stop_drying(item.printer_id)
  234. # Re-check idle after stopping drying
  235. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  236. if not printer_idle:
  237. busy_printers.add(item.printer_id)
  238. continue
  239. else:
  240. busy_printers.add(item.printer_id)
  241. continue
  242. # Check condition (previous print success)
  243. if item.require_previous_success:
  244. if not await self._check_previous_success(db, item):
  245. item.status = "skipped"
  246. item.error_message = "Previous print failed or was aborted"
  247. item.completed_at = datetime.now(timezone.utc)
  248. await db.commit()
  249. logger.info("Skipped queue item %s - previous print failed", item.id)
  250. # Send notification
  251. job_name = await self._get_job_name(db, item)
  252. printer = await self._get_printer(db, item.printer_id)
  253. await notification_service.on_queue_job_skipped(
  254. job_name=job_name,
  255. printer_id=item.printer_id,
  256. printer_name=printer.name if printer else "Unknown",
  257. reason="Previous print failed or was aborted",
  258. db=db,
  259. )
  260. continue
  261. # Compute AMS mapping if not already set
  262. if not item.ams_mapping:
  263. computed_mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item)
  264. if computed_mapping:
  265. item.ams_mapping = json.dumps(computed_mapping)
  266. logger.info(
  267. f"Queue item {item.id}: Computed AMS mapping for printer {item.printer_id}: {computed_mapping}"
  268. )
  269. await db.commit()
  270. # Filament-deficit pre-dispatch check (#1496). If the
  271. # assigned spool can't satisfy any required slot grams,
  272. # promote the item to manual_start so the user must
  273. # acknowledge via the ▶ button (which re-checks live).
  274. if await self._block_on_filament_deficit(db, item):
  275. continue
  276. # Start the print
  277. await self._start_print(db, item)
  278. busy_printers.add(item.printer_id)
  279. # SJF starvation guard: mark items that were jumped
  280. if sjf_enabled and item.print_time_seconds is not None:
  281. for other in items:
  282. if (
  283. other.id != item.id
  284. and other.status == "pending"
  285. and other.printer_id == item.printer_id
  286. and not other.been_jumped
  287. and other.position < item.position
  288. and (
  289. other.print_time_seconds is None
  290. or other.print_time_seconds > item.print_time_seconds
  291. )
  292. ):
  293. other.been_jumped = True
  294. await db.commit()
  295. elif item.target_model:
  296. # Model-based assignment - find any idle printer of matching model
  297. # Parse required filament types if present
  298. required_types = None
  299. if item.required_filament_types:
  300. try:
  301. required_types = json.loads(item.required_filament_types)
  302. except json.JSONDecodeError:
  303. pass # Ignore malformed filament types; treat as no constraint
  304. # Parse filament overrides if present
  305. filament_overrides = None
  306. if item.filament_overrides:
  307. try:
  308. filament_overrides = json.loads(item.filament_overrides)
  309. except json.JSONDecodeError:
  310. pass
  311. # If overrides exist, use override types for validation instead
  312. effective_types = required_types
  313. if filament_overrides:
  314. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  315. if override_types:
  316. # Merge: keep original types for non-overridden slots, add override types
  317. effective_types = sorted(set(required_types or []) | set(override_types))
  318. printer_id, waiting_reason = await self._find_idle_printer_for_model(
  319. db,
  320. item.target_model,
  321. busy_printers,
  322. effective_types,
  323. item.target_location,
  324. filament_overrides=filament_overrides,
  325. require_plate_clear=require_plate_clear,
  326. )
  327. # Update waiting_reason if changed and send notification when first waiting
  328. if item.waiting_reason != waiting_reason:
  329. was_waiting = item.waiting_reason is not None
  330. item.waiting_reason = waiting_reason
  331. await db.commit()
  332. # Send waiting notification only when transitioning to waiting state
  333. # and the reason requires user action (not just "all printers busy")
  334. if waiting_reason and not was_waiting and not self._is_busy_only(waiting_reason):
  335. job_name = await self._get_job_name(db, item)
  336. await notification_service.on_queue_job_waiting(
  337. job_name=job_name,
  338. target_model=item.target_model,
  339. waiting_reason=waiting_reason,
  340. db=db,
  341. )
  342. if printer_id:
  343. # Check condition (previous print success) before assigning
  344. if item.require_previous_success:
  345. if not await self._check_previous_success(db, item):
  346. item.status = "skipped"
  347. item.error_message = "Previous print failed or was aborted"
  348. item.completed_at = datetime.now(timezone.utc)
  349. await db.commit()
  350. logger.info("Skipped queue item %s - previous print failed", item.id)
  351. # Send notification
  352. job_name = await self._get_job_name(db, item)
  353. printer = await self._get_printer(db, printer_id)
  354. await notification_service.on_queue_job_skipped(
  355. job_name=job_name,
  356. printer_id=printer_id,
  357. printer_name=printer.name if printer else "Unknown",
  358. reason="Previous print failed or was aborted",
  359. db=db,
  360. )
  361. continue
  362. # Assign printer and start - clear waiting reason
  363. item.printer_id = printer_id
  364. item.waiting_reason = None
  365. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  366. # Send assignment notification
  367. job_name = await self._get_job_name(db, item)
  368. printer = await self._get_printer(db, printer_id)
  369. await notification_service.on_queue_job_assigned(
  370. job_name=job_name,
  371. printer_id=printer_id,
  372. printer_name=printer.name if printer else "Unknown",
  373. target_model=item.target_model,
  374. db=db,
  375. )
  376. # Compute AMS mapping for the assigned printer if not already set
  377. # This is critical for model-based jobs where mapping wasn't computed upfront
  378. if not item.ams_mapping:
  379. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  380. if computed_mapping:
  381. item.ams_mapping = json.dumps(computed_mapping)
  382. logger.info(
  383. f"Queue item {item.id}: Computed AMS mapping for printer {printer_id}: {computed_mapping}"
  384. )
  385. await db.commit()
  386. # Filament-deficit pre-dispatch check (#1496).
  387. if await self._block_on_filament_deficit(db, item):
  388. continue
  389. await self._start_print(db, item)
  390. busy_printers.add(printer_id)
  391. # SJF starvation guard: mark model-based items that were jumped
  392. if sjf_enabled and item.print_time_seconds is not None:
  393. for other in items:
  394. if (
  395. other.id != item.id
  396. and other.status == "pending"
  397. and other.printer_id is None
  398. and other.target_model
  399. and other.target_model.upper() == item.target_model.upper()
  400. and not other.been_jumped
  401. and other.position < item.position
  402. and (
  403. other.print_time_seconds is None
  404. or other.print_time_seconds > item.print_time_seconds
  405. )
  406. ):
  407. other.been_jumped = True
  408. await db.commit()
  409. # Log summary of skip reasons (helps diagnose why queue items aren't starting)
  410. if skip_reasons:
  411. logger.info("Queue skip summary: %s", skip_reasons)
  412. if busy_printers:
  413. # Log why each printer was busy (first time it was checked)
  414. for pid in busy_printers:
  415. state = printer_manager.get_status(pid)
  416. connected = printer_manager.is_connected(pid)
  417. awaiting = printer_manager.is_awaiting_plate_clear(pid)
  418. state_name = state.state if state else "NO_STATUS"
  419. logger.info(
  420. "Queue: printer %d not available — connected=%s, state=%s, awaiting_plate_clear=%s",
  421. pid,
  422. connected,
  423. state_name,
  424. awaiting,
  425. )
  426. # Auto-drying: start drying on idle printers that have no pending queue items
  427. await self._check_auto_drying(db, items, busy_printers, require_plate_clear=require_plate_clear)
  428. async def _find_idle_printer_for_model(
  429. self,
  430. db: AsyncSession,
  431. model: str,
  432. exclude_ids: set[int],
  433. required_filament_types: list[str] | None = None,
  434. target_location: str | None = None,
  435. filament_overrides: list[dict] | None = None,
  436. require_plate_clear: bool = True,
  437. ) -> tuple[int | None, str | None]:
  438. """Find an idle, connected printer matching the model with compatible filaments.
  439. Args:
  440. db: Database session
  441. model: Printer model to match (e.g., "X1C", "P1S")
  442. exclude_ids: Printer IDs to exclude (already busy)
  443. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  444. If provided, only printers with all required types loaded will match.
  445. target_location: Optional location filter. If provided, only printers in this location are considered.
  446. filament_overrides: Optional list of override dicts. Each entry may include
  447. ``force_color_match: true`` to require an exact type+color match
  448. on the printer for that slot. Without the flag the existing
  449. colour-preference logic applies.
  450. Returns:
  451. Tuple of (printer_id, waiting_reason):
  452. - (printer_id, None) if a matching printer was found
  453. - (None, reason) if no printer is available, with explanation
  454. """
  455. # Normalize model name and use case-insensitive matching
  456. normalized_model = normalize_printer_model(model) or model
  457. query = (
  458. select(Printer)
  459. .where(func.lower(Printer.model) == normalized_model.lower())
  460. .where(Printer.is_active == True) # noqa: E712
  461. )
  462. # Add location filter if specified
  463. if target_location:
  464. query = query.where(Printer.location == target_location)
  465. result = await db.execute(query)
  466. printers = list(result.scalars().all())
  467. location_suffix = f" in {target_location}" if target_location else ""
  468. if not printers:
  469. return None, f"No active {normalized_model} printers{location_suffix} configured"
  470. # Separate force-matched overrides from preference-only overrides
  471. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  472. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  473. # Track reasons for skipping printers
  474. printers_busy = []
  475. printers_offline = []
  476. printers_missing_filament: list[tuple[str, list[str]]] = []
  477. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  478. for printer in printers:
  479. if printer.id in exclude_ids:
  480. # Printer is already claimed by another job in this scheduling run.
  481. # For force-color jobs, still check if the color would match — if not,
  482. # report it as a color mismatch rather than plain "Busy" so the user
  483. # knows the job needs a filament change, not just to wait for availability.
  484. if force_overrides and not pref_overrides:
  485. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  486. if missing_colors:
  487. printers_missing_filament.append((printer.name, missing_colors))
  488. continue
  489. printers_busy.append(printer.name)
  490. continue
  491. is_connected = printer_manager.is_connected(printer.id)
  492. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  493. if not is_connected:
  494. printers_offline.append(printer.name)
  495. continue
  496. if not is_idle:
  497. # Printer is currently printing. For force-color jobs, check whether the
  498. # loaded color would satisfy the requirement — if not, surface it as a
  499. # color-mismatch reason rather than plain "Busy" so the user understands
  500. # that the job is waiting for a filament change, not just printer availability.
  501. if force_overrides and not pref_overrides:
  502. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  503. if missing_colors:
  504. printers_missing_filament.append((printer.name, missing_colors))
  505. logger.debug(
  506. "Printer %s (%s) is busy but also has wrong force-color: %s",
  507. printer.id,
  508. printer.name,
  509. missing_colors,
  510. )
  511. continue
  512. printers_busy.append(printer.name)
  513. continue
  514. # Validate filament compatibility if required types are specified
  515. if required_filament_types:
  516. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  517. if missing:
  518. # When force_overrides are present, enrich missing entries with color info
  519. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  520. if force_overrides:
  521. force_color_map = {
  522. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  523. for o in force_overrides
  524. }
  525. missing_enriched = [
  526. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  527. for t in missing
  528. ]
  529. printers_missing_filament.append((printer.name, missing_enriched))
  530. else:
  531. printers_missing_filament.append((printer.name, missing))
  532. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  533. continue
  534. # Force color match: ALL flagged slots must have an exact type+color match
  535. if force_overrides:
  536. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  537. if missing_colors:
  538. printers_missing_filament.append((printer.name, missing_colors))
  539. logger.debug(
  540. "Skipping printer %s (%s) - missing force-matched colors: %s",
  541. printer.id,
  542. printer.name,
  543. missing_colors,
  544. )
  545. continue
  546. # If preference-only overrides exist, rank by color matches (existing behaviour)
  547. if pref_overrides:
  548. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  549. if color_matches > 0:
  550. candidates.append((printer.id, color_matches))
  551. else:
  552. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  553. printers_missing_filament.append((printer.name, override_colors))
  554. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  555. continue
  556. elif force_overrides:
  557. # Passed all force checks — immediately eligible (no preference ordering needed)
  558. return printer.id, None
  559. else:
  560. # No overrides at all - take first available (existing behavior)
  561. return printer.id, None
  562. # If we have candidates from preference override matching, pick the one with most color matches
  563. if candidates:
  564. candidates.sort(key=lambda c: c[1], reverse=True)
  565. return candidates[0][0], None
  566. # Build waiting reason from what we found
  567. reasons = []
  568. if printers_missing_filament:
  569. # Filament/color mismatch is most actionable - show first
  570. if force_overrides and not pref_overrides:
  571. # All mismatches are force-color failures — use descriptive message only;
  572. # but only if there are no busy printers that DO have the matching color.
  573. # If a printer has the right color but is busy, surface "Busy" instead so
  574. # the user knows the job will start automatically once that printer is free.
  575. if not printers_busy:
  576. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  577. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  578. # else: fall through — printers_busy will be appended below
  579. else:
  580. names_and_missing = [
  581. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  582. ]
  583. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  584. if printers_busy:
  585. reasons.append(f"Busy: {', '.join(printers_busy)}")
  586. if printers_offline:
  587. reasons.append(f"Offline: {', '.join(printers_offline)}")
  588. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  589. @staticmethod
  590. def _is_busy_only(waiting_reason: str) -> bool:
  591. """Check if the waiting reason only contains 'Busy' entries.
  592. When all matching printers are simply busy printing, the queued job
  593. will start automatically once a printer finishes — no user action
  594. is required, so we skip the notification.
  595. """
  596. parts = [p.strip() for p in waiting_reason.split(" | ")]
  597. return all(p.startswith("Busy:") for p in parts)
  598. def _get_missing_force_color_slots(self, printer_id: int, force_overrides: list[dict]) -> list[str]:
  599. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  600. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  601. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  602. with an exact type+color match.
  603. Returns:
  604. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  605. """
  606. status = printer_manager.get_status(printer_id)
  607. if not status:
  608. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  609. # Build set of loaded type+colour pairs from AMS and external spool
  610. loaded: set[tuple[str, str]] = set()
  611. for ams_unit in status.raw_data.get("ams", []):
  612. for tray in ams_unit.get("tray", []):
  613. tray_type = tray.get("tray_type")
  614. tray_color = tray.get("tray_color", "")
  615. if tray_type:
  616. color_norm = tray_color.replace("#", "").lower()[:6]
  617. loaded.add((_canonical_filament_type(tray_type), color_norm))
  618. for vt in status.raw_data.get("vt_tray") or []:
  619. vt_type = vt.get("tray_type")
  620. if vt_type:
  621. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  622. loaded.add((_canonical_filament_type(vt_type), color_norm))
  623. missing = []
  624. for o in force_overrides:
  625. o_type = _canonical_filament_type(o.get("type") or "")
  626. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  627. if (o_type, o_color) not in loaded:
  628. color_label = o.get("color_name") or o.get("color", "?")
  629. missing.append(f"{o_type} ({color_label})")
  630. return missing
  631. def _get_missing_filament_types(self, printer_id: int, required_types: list[str]) -> list[str]:
  632. """Get the list of required filament types that are not loaded on the printer.
  633. Args:
  634. printer_id: The printer ID
  635. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  636. Returns:
  637. List of missing filament types (empty if all are loaded)
  638. """
  639. status = printer_manager.get_status(printer_id)
  640. if not status:
  641. return required_types # Can't determine, assume all missing
  642. # Collect all filament types loaded on this printer (AMS units + external spool)
  643. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  644. loaded_types: set[str] = set()
  645. # Check AMS units (stored in raw_data["ams"])
  646. ams_data = status.raw_data.get("ams", [])
  647. if ams_data:
  648. for ams_unit in ams_data:
  649. for tray in ams_unit.get("tray", []):
  650. tray_type = tray.get("tray_type")
  651. if tray_type:
  652. loaded_types.add(_canonical_filament_type(tray_type))
  653. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  654. for vt in status.raw_data.get("vt_tray") or []:
  655. vt_type = vt.get("tray_type")
  656. if vt_type:
  657. loaded_types.add(_canonical_filament_type(vt_type))
  658. # Find which required types are missing (using canonical type for equivalence)
  659. missing = []
  660. for req_type in required_types:
  661. if _canonical_filament_type(req_type) not in loaded_types:
  662. missing.append(req_type)
  663. return missing
  664. def _count_override_color_matches(self, printer_id: int, overrides: list[dict]) -> int:
  665. """Count how many filament overrides have an exact color match on the printer.
  666. Used to prefer printers that already have the desired override colors loaded.
  667. """
  668. status = printer_manager.get_status(printer_id)
  669. if not status:
  670. return 0
  671. # Collect loaded filaments' type+color pairs
  672. loaded: set[tuple[str, str]] = set()
  673. for ams_unit in status.raw_data.get("ams", []):
  674. for tray in ams_unit.get("tray", []):
  675. tray_type = tray.get("tray_type")
  676. tray_color = tray.get("tray_color", "")
  677. if tray_type:
  678. color_norm = tray_color.replace("#", "").lower()[:6]
  679. loaded.add((tray_type.upper(), color_norm))
  680. for vt in status.raw_data.get("vt_tray") or []:
  681. vt_type = vt.get("tray_type")
  682. if vt_type:
  683. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  684. loaded.add((vt_type.upper(), color_norm))
  685. matches = 0
  686. for o in overrides:
  687. o_type = (o.get("type") or "").upper()
  688. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  689. if (o_type, o_color) in loaded:
  690. matches += 1
  691. return matches
  692. async def _compute_ams_mapping_for_printer(
  693. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  694. ) -> list[int] | None:
  695. """Compute AMS mapping for a printer based on filament requirements.
  696. Called when a queue item has no ams_mapping set — either for model-based
  697. items after printer assignment, or printer-specific items (e.g. from VP).
  698. Args:
  699. db: Database session
  700. printer_id: The assigned printer ID
  701. item: The queue item (contains archive_id or library_file_id)
  702. Returns:
  703. AMS mapping array or None if no mapping needed/possible
  704. """
  705. # Get printer status
  706. status = printer_manager.get_status(printer_id)
  707. if not status:
  708. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  709. return None
  710. # Get filament requirements from source file
  711. filament_reqs = await self._get_filament_requirements(db, item)
  712. if not filament_reqs:
  713. # When the 3MF can't be read but force-color overrides are present, build a
  714. # direct mapping from the overrides so the printer uses the correct AMS slot.
  715. if item.filament_overrides:
  716. try:
  717. overrides = json.loads(item.filament_overrides)
  718. force_overrides = [o for o in overrides if o.get("force_color_match")]
  719. if force_overrides:
  720. logger.info(
  721. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  722. "force-color override(s)",
  723. item.id,
  724. len(force_overrides),
  725. )
  726. return self._build_override_direct_mapping(force_overrides, status)
  727. except (json.JSONDecodeError, KeyError, TypeError) as e:
  728. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  729. logger.debug("No filament requirements found for queue item %s", item.id)
  730. return None
  731. # Apply filament overrides if present
  732. if item.filament_overrides:
  733. try:
  734. overrides = json.loads(item.filament_overrides)
  735. override_map = {o["slot_id"]: o for o in overrides}
  736. for req in filament_reqs:
  737. if req["slot_id"] in override_map:
  738. override = override_map[req["slot_id"]]
  739. req["type"] = override["type"]
  740. req["color"] = override["color"]
  741. # Clear tray_info_idx so matching uses type+color instead of
  742. # the original 3MF's tray_info_idx (which would match the old filament)
  743. req["tray_info_idx"] = ""
  744. logger.debug(
  745. "Queue item %s: Override slot %d -> %s %s",
  746. item.id,
  747. req["slot_id"],
  748. override["type"],
  749. override["color"],
  750. )
  751. except (json.JSONDecodeError, KeyError, TypeError) as e:
  752. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  753. # Build loaded filaments from printer status
  754. loaded_filaments = self._build_loaded_filaments(status)
  755. if not loaded_filaments:
  756. logger.debug("No filaments loaded on printer %s", printer_id)
  757. return None
  758. # Check if user prefers lowest remaining filament when multiple spools match
  759. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  760. # Compute mapping: match required filaments to available slots
  761. return self._match_filaments_to_slots(filament_reqs, loaded_filaments, prefer_lowest)
  762. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  763. """Build an AMS mapping directly from force-color overrides without a 3MF.
  764. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  765. slice_info is missing or unreadable) but ``force_color_match`` overrides
  766. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  767. treated as the filament requirement for that slot and matched against the
  768. current AMS state of the printer.
  769. Returns the same format as ``_match_filaments_to_slots``, or None when
  770. the AMS has no loaded filaments.
  771. """
  772. loaded = self._build_loaded_filaments(status)
  773. if not loaded:
  774. return None
  775. reqs = [
  776. {
  777. "slot_id": o["slot_id"],
  778. "type": o.get("type", ""),
  779. "color": o.get("color", ""),
  780. "tray_info_idx": "",
  781. }
  782. for o in force_overrides
  783. ]
  784. return self._match_filaments_to_slots(reqs, loaded)
  785. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  786. """Resolve the queue item's source 3MF and parse the per-slot
  787. filament requirements out of it. Thin DB-resolver wrapper around
  788. ``filament_requirements.extract_filament_requirements`` so the VP
  789. queue-mode write path (#1188) can reuse the same parser at upload
  790. time.
  791. """
  792. from backend.app.services.filament_requirements import extract_filament_requirements
  793. file_path: Path | None = None
  794. if item.archive_id:
  795. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  796. archive = result.scalar_one_or_none()
  797. if archive:
  798. file_path = settings.base_dir / archive.file_path
  799. elif item.library_file_id:
  800. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  801. library_file = result.scalar_one_or_none()
  802. if library_file:
  803. lib_path = Path(library_file.file_path)
  804. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  805. if not file_path or not file_path.exists():
  806. return None
  807. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  808. return filaments if filaments else None
  809. def _build_loaded_filaments(self, status) -> list[dict]:
  810. """Build list of loaded filaments from printer status.
  811. Args:
  812. status: PrinterState from printer_manager
  813. Returns:
  814. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  815. """
  816. filaments = []
  817. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  818. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  819. # Parse AMS units from raw_data
  820. ams_data = status.raw_data.get("ams", [])
  821. for ams_unit in ams_data:
  822. ams_id = int(ams_unit.get("id", 0))
  823. trays = ams_unit.get("tray", [])
  824. is_ht = len(trays) == 1 # AMS-HT has single tray
  825. for tray in trays:
  826. tray_type = tray.get("tray_type")
  827. if tray_type:
  828. tray_id = int(tray.get("id", 0))
  829. tray_color = tray.get("tray_color", "")
  830. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  831. tray_info_idx = tray.get("tray_info_idx", "")
  832. # Normalize color: remove alpha, add hash
  833. color = self._normalize_color(tray_color)
  834. # Calculate global tray ID
  835. # AMS-HT units have IDs starting at 128 with a single tray
  836. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  837. filaments.append(
  838. {
  839. "type": tray_type,
  840. "color": color,
  841. "tray_info_idx": tray_info_idx,
  842. "ams_id": ams_id,
  843. "tray_id": tray_id,
  844. "is_ht": is_ht,
  845. "is_external": False,
  846. "global_tray_id": global_tray_id,
  847. "extruder_id": ams_extruder_map.get(str(ams_id)),
  848. "remain": tray.get("remain", -1),
  849. }
  850. )
  851. # Check external spool(s) (vt_tray is a list)
  852. for idx, vt in enumerate(status.raw_data.get("vt_tray") or []):
  853. if vt.get("tray_type"):
  854. color = self._normalize_color(vt.get("tray_color", ""))
  855. tray_id = int(vt.get("id", 254))
  856. filaments.append(
  857. {
  858. "type": vt["tray_type"],
  859. "color": color,
  860. "tray_info_idx": vt.get("tray_info_idx", ""),
  861. "ams_id": -1,
  862. "tray_id": idx,
  863. "is_ht": False,
  864. "is_external": True,
  865. "global_tray_id": tray_id,
  866. "extruder_id": (255 - tray_id) if ams_extruder_map else None,
  867. "remain": vt.get("remain", -1),
  868. }
  869. )
  870. return filaments
  871. def _normalize_color(self, color: str | None) -> str:
  872. """Normalize color to #RRGGBB format."""
  873. if not color:
  874. return "#808080"
  875. hex_color = color.replace("#", "")[:6]
  876. return f"#{hex_color}"
  877. def _normalize_color_for_compare(self, color: str | None) -> str:
  878. """Normalize color for comparison (lowercase, no hash)."""
  879. if not color:
  880. return ""
  881. return color.replace("#", "").lower()[:6]
  882. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  883. """Check if two colors are visually similar within a threshold."""
  884. hex1 = self._normalize_color_for_compare(color1)
  885. hex2 = self._normalize_color_for_compare(color2)
  886. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  887. return False
  888. try:
  889. r1 = int(hex1[0:2], 16)
  890. g1 = int(hex1[2:4], 16)
  891. b1 = int(hex1[4:6], 16)
  892. r2 = int(hex2[0:2], 16)
  893. g2 = int(hex2[2:4], 16)
  894. b2 = int(hex2[4:6], 16)
  895. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  896. except ValueError:
  897. return False
  898. def _match_filaments_to_slots(
  899. self, required: list[dict], loaded: list[dict], prefer_lowest: bool = False
  900. ) -> list[int] | None:
  901. """Match required filaments to loaded filaments and build AMS mapping.
  902. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  903. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  904. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  905. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  906. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  907. matching among those trays.
  908. Args:
  909. required: List of required filaments with slot_id, type, color, tray_info_idx
  910. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  911. Returns:
  912. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  913. """
  914. if not required:
  915. return None
  916. # Track used trays to avoid duplicate assignment
  917. used_tray_ids: set[int] = set()
  918. comparisons = []
  919. for req in required:
  920. req_type = (req.get("type") or "").upper()
  921. req_color = req.get("color", "")
  922. req_tray_info_idx = req.get("tray_info_idx", "")
  923. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  924. idx_match = None
  925. exact_match = None
  926. similar_match = None
  927. type_only_match = None
  928. # Get available trays (not already used)
  929. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  930. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  931. # Hard filter — cross-nozzle assignment causes print failures
  932. # ("position of left hotend is abnormal"), so never fall back.
  933. req_nozzle_id = req.get("nozzle_id")
  934. if req_nozzle_id is not None:
  935. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  936. # Sort by remaining filament (ascending) so lowest-remain spool wins .find()
  937. if prefer_lowest:
  938. available.sort(key=lambda f: f.get("remain", -1) if f.get("remain", -1) >= 0 else 101)
  939. # Check if tray_info_idx is unique among available trays
  940. if req_tray_info_idx:
  941. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  942. if len(idx_matches) == 1:
  943. # Unique tray_info_idx - use it as definitive match
  944. idx_match = idx_matches[0]
  945. logger.debug(
  946. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  947. f"-> tray {idx_match['global_tray_id']}"
  948. )
  949. elif len(idx_matches) > 1:
  950. # Multiple trays with same tray_info_idx - use color matching among them
  951. logger.debug(
  952. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  953. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  954. )
  955. if prefer_lowest:
  956. idx_matches.sort(key=lambda f: f.get("remain", -1) if f.get("remain", -1) >= 0 else 101)
  957. # Use color matching within this subset
  958. for f in idx_matches:
  959. f_color = f.get("color", "")
  960. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  961. if not exact_match:
  962. exact_match = f
  963. elif self._colors_are_similar(f_color, req_color):
  964. if not similar_match:
  965. similar_match = f
  966. elif not type_only_match:
  967. type_only_match = f
  968. # If no idx_match yet, do standard type/color matching on all available trays
  969. if not idx_match and not exact_match and not similar_match and not type_only_match:
  970. for f in available:
  971. f_type = (f.get("type") or "").upper()
  972. if _canonical_filament_type(f_type) != _canonical_filament_type(req_type):
  973. continue
  974. # Type matches - check color
  975. f_color = f.get("color", "")
  976. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  977. if not exact_match:
  978. exact_match = f
  979. elif self._colors_are_similar(f_color, req_color):
  980. if not similar_match:
  981. similar_match = f
  982. elif not type_only_match:
  983. type_only_match = f
  984. match = idx_match or exact_match or similar_match or type_only_match
  985. if match:
  986. used_tray_ids.add(match["global_tray_id"])
  987. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  988. else:
  989. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  990. # Build mapping array
  991. if not comparisons:
  992. return None
  993. max_slot_id = max(c["slot_id"] for c in comparisons)
  994. if max_slot_id <= 0:
  995. return None
  996. mapping = [-1] * max_slot_id
  997. for c in comparisons:
  998. slot_id = c["slot_id"]
  999. if slot_id and slot_id > 0:
  1000. mapping[slot_id - 1] = c["global_tray_id"]
  1001. return mapping
  1002. def _mark_printer_dispatched(
  1003. self,
  1004. printer_id: int,
  1005. pre_state: str | None,
  1006. pre_subtask_id: str | None,
  1007. ) -> None:
  1008. """Record that a print command was just sent to ``printer_id``.
  1009. Held until either the watchdog observes a state/subtask transition
  1010. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  1011. """
  1012. if not pre_state:
  1013. # No pre_state means we can't detect a transition — fall back to a
  1014. # pure time-based hold using empty string as a sentinel that won't
  1015. # match any real printer state.
  1016. pre_state = ""
  1017. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  1018. def _release_dispatch_hold(self, printer_id: int) -> None:
  1019. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  1020. self._dispatch_holds.pop(printer_id, None)
  1021. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  1022. """True if ``printer_id`` is still inside its post-dispatch hold window.
  1023. Returns False (and clears the hold) once any of these are true:
  1024. - hard timeout (``_dispatch_max_hold``) has elapsed
  1025. - the printer has transitioned out of pre_state and we're past the
  1026. minimum cooldown
  1027. - the printer's subtask_id has advanced past pre_subtask_id and we're
  1028. past the minimum cooldown
  1029. Otherwise the printer is held — caller should treat it as busy.
  1030. """
  1031. entry = self._dispatch_holds.get(printer_id)
  1032. if not entry:
  1033. return False
  1034. started_at, pre_state, pre_subtask_id = entry
  1035. elapsed = time.monotonic() - started_at
  1036. if elapsed >= self._dispatch_max_hold:
  1037. self._dispatch_holds.pop(printer_id, None)
  1038. return False
  1039. # Without a pre_state we can't detect a transition — fall back to the
  1040. # min cooldown alone, then drop the hold.
  1041. if not pre_state:
  1042. if elapsed >= self._dispatch_min_cooldown:
  1043. self._dispatch_holds.pop(printer_id, None)
  1044. return False
  1045. return True
  1046. status = printer_manager.get_status(printer_id)
  1047. current_state = getattr(status, "state", None) if status else None
  1048. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  1049. transitioned = (current_state is not None and current_state != pre_state) or (
  1050. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  1051. )
  1052. if transitioned and elapsed >= self._dispatch_min_cooldown:
  1053. self._dispatch_holds.pop(printer_id, None)
  1054. return False
  1055. return True
  1056. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  1057. """Check if a printer is connected and idle."""
  1058. if not printer_manager.is_connected(printer_id):
  1059. logger.debug("Printer %d: not connected", printer_id)
  1060. return False
  1061. state = printer_manager.get_status(printer_id)
  1062. if not state:
  1063. logger.debug("Printer %d: no status available", printer_id)
  1064. return False
  1065. # Plate-clear gate: if the printer finished/failed a previous print and the user
  1066. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  1067. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  1068. # printer, it boots back into IDLE with no memory of the previous finish; without
  1069. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  1070. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  1071. logger.debug(
  1072. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  1073. printer_id,
  1074. state.state,
  1075. )
  1076. return False
  1077. idle = state.state in ("IDLE", "FINISH", "FAILED")
  1078. if not idle:
  1079. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  1080. return idle
  1081. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  1082. """Read a setting value from the database."""
  1083. result = await db.execute(select(Settings).where(Settings.key == key))
  1084. setting = result.scalar_one_or_none()
  1085. return setting.value if setting else None
  1086. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  1087. """Read a boolean setting from the database."""
  1088. result = await db.execute(select(Settings).where(Settings.key == key))
  1089. setting = result.scalar_one_or_none()
  1090. if setting:
  1091. return setting.value.lower() == "true"
  1092. return default
  1093. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  1094. """Get drying presets (user-configured or built-in defaults)."""
  1095. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  1096. setting = result.scalar_one_or_none()
  1097. if setting and setting.value:
  1098. try:
  1099. presets = json.loads(setting.value)
  1100. if isinstance(presets, dict) and presets:
  1101. return presets
  1102. except json.JSONDecodeError:
  1103. pass
  1104. return self.DEFAULT_DRYING_PRESETS
  1105. def _get_conservative_drying_params(
  1106. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  1107. ) -> tuple[int, int, str] | None:
  1108. """Get the most conservative drying params for mixed filament types in an AMS unit.
  1109. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  1110. """
  1111. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  1112. hours_key = f"{temp_key}_hours"
  1113. min_temp = None
  1114. max_hours = None
  1115. filament_type = ""
  1116. for tray in trays:
  1117. tray_type = tray.get("tray_type", "")
  1118. if not tray_type:
  1119. continue
  1120. # Normalize filament type for preset lookup (e.g., "PLA Basic" -> "PLA")
  1121. base_type = tray_type.split()[0].upper()
  1122. preset = presets.get(base_type)
  1123. if not preset:
  1124. continue
  1125. temp = preset.get(temp_key, 55)
  1126. hours = preset.get(hours_key, 12)
  1127. # Conservative: lowest temp, longest duration
  1128. if min_temp is None or temp < min_temp:
  1129. min_temp = temp
  1130. if max_hours is None or hours > max_hours:
  1131. max_hours = hours
  1132. if not filament_type:
  1133. filament_type = base_type
  1134. if min_temp is None:
  1135. return None
  1136. return (min_temp, max_hours or 12, filament_type)
  1137. async def _check_auto_drying(
  1138. self,
  1139. db: AsyncSession,
  1140. queue_items: list[PrintQueueItem],
  1141. busy_printers: set[int],
  1142. *,
  1143. require_plate_clear: bool = True,
  1144. ):
  1145. """Start drying on idle printers based on humidity.
  1146. Two modes (can both be enabled):
  1147. - queue_drying_enabled: Dry between scheduled queue prints
  1148. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  1149. """
  1150. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  1151. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  1152. if not queue_drying_enabled and not ambient_drying_enabled:
  1153. # Stop active drying on all printers if both features disabled
  1154. if self._drying_in_progress:
  1155. for pid in list(self._drying_in_progress):
  1156. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  1157. await self._stop_drying(pid)
  1158. return
  1159. # Update drying state from printer status (handles backend restart)
  1160. self._sync_drying_state()
  1161. # Find printers with scheduled items (for queue drying mode)
  1162. printers_with_scheduled: set[int] = set()
  1163. printers_with_items: set[int] = set()
  1164. for item in queue_items:
  1165. if item.printer_id:
  1166. printers_with_items.add(item.printer_id)
  1167. if item.scheduled_time and not item.manual_start:
  1168. printers_with_scheduled.add(item.printer_id)
  1169. # If only queue mode is on and no printers have scheduled items, stop drying
  1170. if not ambient_drying_enabled and not printers_with_scheduled:
  1171. for pid in list(self._drying_in_progress):
  1172. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  1173. await self._stop_drying(pid)
  1174. return
  1175. # Get humidity threshold
  1176. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  1177. setting = result.scalar_one_or_none()
  1178. humidity_threshold = int(setting.value) if setting else 60
  1179. # Get drying presets
  1180. presets = await self._get_drying_presets(db)
  1181. # Determine if drying should be skipped for printers with pending items
  1182. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  1183. # Get all active printers
  1184. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1185. for printer in all_printers.scalars():
  1186. pid = printer.id
  1187. if pid in busy_printers:
  1188. logger.debug("Auto-drying: printer %d skipped — busy", pid)
  1189. continue
  1190. # In queue-only mode, only dry printers that have scheduled prints
  1191. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  1192. if self._drying_in_progress.get(pid):
  1193. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  1194. await self._stop_drying(pid)
  1195. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  1196. continue
  1197. # When block mode is on, don't START new drying on printers with pending items.
  1198. # But allow already-drying printers through so humidity auto-stop logic still runs.
  1199. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  1200. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  1201. continue
  1202. if not printer_manager.is_connected(pid):
  1203. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  1204. continue
  1205. if not self._is_printer_idle(pid, require_plate_clear):
  1206. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  1207. continue
  1208. # Check if this printer supports drying
  1209. state = printer_manager.get_status(pid)
  1210. if not state:
  1211. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  1212. continue
  1213. model = printer_manager.get_model(pid)
  1214. firmware = state.firmware_version
  1215. if not supports_drying(model, firmware):
  1216. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  1217. continue
  1218. # Check each AMS unit from raw_data
  1219. ams_list = state.raw_data.get("ams", [])
  1220. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  1221. for ams_data in ams_list:
  1222. module_type = str(ams_data.get("module_type") or "")
  1223. ams_id = int(ams_data.get("id", 0))
  1224. # Only n3f/n3s support drying
  1225. if module_type not in ("n3f", "n3s"):
  1226. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  1227. continue
  1228. dry_time = int(ams_data.get("dry_time") or 0)
  1229. # Read humidity — prefer humidity_raw (actual %) over humidity (index 1-5)
  1230. humidity = None
  1231. h_raw = ams_data.get("humidity_raw")
  1232. if h_raw is not None:
  1233. try:
  1234. humidity = int(h_raw)
  1235. except (ValueError, TypeError):
  1236. pass
  1237. if humidity is None:
  1238. h_idx = ams_data.get("humidity")
  1239. if h_idx is not None:
  1240. try:
  1241. humidity = int(h_idx)
  1242. except (ValueError, TypeError):
  1243. pass
  1244. # Already drying — check if humidity dropped below threshold (with minimum drying time)
  1245. if dry_time > 0:
  1246. if pid not in self._drying_in_progress:
  1247. # Drying we didn't start (manual or from before restart) — track but don't stop
  1248. self._drying_in_progress[pid] = time.monotonic()
  1249. started_at = self._drying_in_progress[pid]
  1250. elapsed = time.monotonic() - started_at
  1251. if humidity is not None and humidity <= humidity_threshold and elapsed >= self._min_drying_seconds:
  1252. logger.info(
  1253. "Auto-drying: printer %d AMS %d — humidity %d%% <= threshold %d%% after %dm, stopping drying",
  1254. pid,
  1255. ams_id,
  1256. humidity,
  1257. humidity_threshold,
  1258. int(elapsed / 60),
  1259. )
  1260. printer_manager.send_drying_command(pid, ams_id, temp=0, duration=0, mode=0)
  1261. else:
  1262. logger.debug(
  1263. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%, elapsed %dm/%dm min)",
  1264. pid,
  1265. ams_id,
  1266. dry_time,
  1267. humidity,
  1268. int(elapsed / 60),
  1269. self._min_drying_seconds // 60,
  1270. )
  1271. continue
  1272. # Humidity below threshold — no need to start drying
  1273. if humidity is None or humidity <= humidity_threshold:
  1274. logger.debug(
  1275. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  1276. pid,
  1277. ams_id,
  1278. humidity,
  1279. humidity_threshold,
  1280. )
  1281. continue
  1282. # Check cannot-dry reasons (power constraints etc.)
  1283. sf_reasons = ams_data.get("dry_sf_reason", [])
  1284. if sf_reasons:
  1285. logger.debug(
  1286. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  1287. pid,
  1288. ams_id,
  1289. sf_reasons,
  1290. )
  1291. continue
  1292. # Get conservative drying params for mixed filaments
  1293. trays = ams_data.get("tray", [])
  1294. params = self._get_conservative_drying_params(trays, module_type, presets)
  1295. if not params:
  1296. logger.debug(
  1297. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  1298. )
  1299. continue
  1300. temp, duration_hours, filament_type = params
  1301. # Start drying
  1302. logger.info(
  1303. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  1304. "starting %s drying at %d°C for %dh",
  1305. pid,
  1306. ams_id,
  1307. humidity,
  1308. humidity_threshold,
  1309. filament_type,
  1310. temp,
  1311. duration_hours,
  1312. )
  1313. success = printer_manager.send_drying_command(
  1314. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  1315. )
  1316. if success:
  1317. self._drying_in_progress[pid] = time.monotonic()
  1318. def _sync_drying_state(self):
  1319. """Sync in-memory drying state with actual printer status.
  1320. Handles backend restart — if a printer is drying but we don't know about it,
  1321. update our state. If we think it's drying but it's not, clear it.
  1322. """
  1323. to_remove = []
  1324. for pid in self._drying_in_progress:
  1325. state = printer_manager.get_status(pid)
  1326. if not state:
  1327. to_remove.append(pid)
  1328. continue
  1329. # Check if any AMS unit is still drying
  1330. ams_list = state.raw_data.get("ams", [])
  1331. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  1332. if not any_drying:
  1333. to_remove.append(pid)
  1334. for pid in to_remove:
  1335. self._drying_in_progress.pop(pid, None)
  1336. async def _stop_drying(self, printer_id: int):
  1337. """Stop all active drying on a printer (print takes priority)."""
  1338. state = printer_manager.get_status(printer_id)
  1339. if not state:
  1340. self._drying_in_progress.pop(printer_id, None)
  1341. return
  1342. ams_list = state.raw_data.get("ams", [])
  1343. for ams_data in ams_list:
  1344. dry_time = int(ams_data.get("dry_time") or 0)
  1345. if dry_time > 0:
  1346. ams_id = int(ams_data.get("id", 0))
  1347. logger.info(
  1348. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  1349. printer_id,
  1350. ams_id,
  1351. )
  1352. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  1353. self._drying_in_progress.pop(printer_id, None)
  1354. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  1355. """Get all smart plugs associated with a printer."""
  1356. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1357. return list(result.scalars().all())
  1358. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  1359. """Turn on smart plug and wait for printer to connect.
  1360. Returns True if printer connected successfully within timeout.
  1361. """
  1362. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  1363. service = await smart_plug_manager.get_service_for_plug(plug, db)
  1364. # Check current plug state
  1365. status = await service.get_status(plug)
  1366. if not status.get("reachable"):
  1367. logger.warning("Smart plug '%s' is not reachable", plug.name)
  1368. return False
  1369. # Turn on if not already on
  1370. if status.get("state") != "ON":
  1371. success = await service.turn_on(plug)
  1372. if not success:
  1373. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  1374. return False
  1375. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  1376. # Get printer from database for connection
  1377. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1378. printer = result.scalar_one_or_none()
  1379. if not printer:
  1380. logger.error("Printer %s not found in database", printer_id)
  1381. return False
  1382. # Wait for printer to boot (give it some time before trying to connect)
  1383. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  1384. await asyncio.sleep(30)
  1385. # Try to connect to the printer periodically
  1386. elapsed = 30 # Already waited 30s
  1387. while elapsed < self._power_on_wait_time:
  1388. # Try to connect
  1389. logger.info("Attempting to connect to printer %s...", printer_id)
  1390. try:
  1391. connected = await printer_manager.connect_printer(printer)
  1392. if connected:
  1393. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  1394. # Give it a moment to stabilize and get status
  1395. await asyncio.sleep(5)
  1396. return True
  1397. except Exception as e:
  1398. logger.debug("Connection attempt failed: %s", e)
  1399. await asyncio.sleep(self._power_on_check_interval)
  1400. elapsed += self._power_on_check_interval
  1401. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  1402. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  1403. return False
  1404. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  1405. """Check if the previous print on this printer succeeded."""
  1406. # Find the most recent completed queue item for this printer
  1407. result = await db.execute(
  1408. select(PrintQueueItem)
  1409. .where(PrintQueueItem.printer_id == item.printer_id)
  1410. .where(PrintQueueItem.id != item.id)
  1411. .where(PrintQueueItem.status.in_(["completed", "failed", "skipped", "aborted"]))
  1412. .order_by(PrintQueueItem.completed_at.desc())
  1413. .limit(1)
  1414. )
  1415. prev_item = result.scalar_one_or_none()
  1416. # If no previous item, assume success (first in queue)
  1417. if not prev_item:
  1418. return True
  1419. return prev_item.status == "completed"
  1420. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  1421. """Power off printer if auto_off_after is enabled (waits for cooldown)."""
  1422. if not item.auto_off_after:
  1423. return
  1424. plugs = await self._get_smart_plugs(db, item.printer_id)
  1425. plug_ids = [p.id for p in plugs if p.enabled]
  1426. if plug_ids:
  1427. logger.info("Auto-off: Waiting for printer %s to cool down before power off...", item.printer_id)
  1428. # Wait for cooldown (up to 10 minutes)
  1429. await printer_manager.wait_for_cooldown(item.printer_id, target_temp=50.0, timeout=600)
  1430. # Re-fetch plugs in a fresh session after the long cooldown wait
  1431. async with async_session() as new_db:
  1432. for plug_id in plug_ids:
  1433. try:
  1434. result = await new_db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  1435. plug = result.scalar_one_or_none()
  1436. if plug and plug.enabled:
  1437. logger.info("Auto-off: Powering off plug '%s' for printer %s", plug.name, item.printer_id)
  1438. service = await smart_plug_manager.get_service_for_plug(plug, new_db)
  1439. await service.turn_off(plug)
  1440. except Exception as e:
  1441. logger.warning(
  1442. "Auto-off: Failed to power off plug %s for printer %s: %s", plug_id, item.printer_id, e
  1443. )
  1444. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  1445. """Get a human-readable name for a queue item."""
  1446. if item.archive_id:
  1447. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1448. archive = result.scalar_one_or_none()
  1449. if archive:
  1450. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  1451. if item.library_file_id:
  1452. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  1453. library_file = result.scalar_one_or_none()
  1454. if library_file:
  1455. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  1456. return f"Job #{item.id}"
  1457. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  1458. """Get printer by ID."""
  1459. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1460. return result.scalar_one_or_none()
  1461. async def _block_on_filament_deficit(
  1462. self,
  1463. db: AsyncSession,
  1464. item: PrintQueueItem,
  1465. ) -> bool:
  1466. """Promote the item to manual_start when the assigned spool is short (#1496).
  1467. Returns True when this dispatch attempt was blocked, False when the
  1468. item is clear to start. A previously-flagged item whose spool has
  1469. since been swapped to one with enough material clears the flag here
  1470. so the next scheduler tick dispatches it.
  1471. """
  1472. try:
  1473. deficit = await compute_deficit_for_queue_item(db, item)
  1474. except Exception as e:
  1475. # Never let a flaky deficit check wedge the queue — log and let
  1476. # dispatch proceed. The PrintModal-side check still runs on the
  1477. # manual paths.
  1478. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  1479. return False
  1480. if deficit:
  1481. item.filament_short = True
  1482. item.manual_start = True
  1483. await db.commit()
  1484. job_name = await self._get_job_name(db, item)
  1485. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  1486. logger.info(
  1487. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  1488. item.id,
  1489. len(deficit),
  1490. )
  1491. try:
  1492. await notification_service.on_queue_job_waiting(
  1493. job_name=job_name,
  1494. target_model=(printer.model if printer else "") or "",
  1495. waiting_reason="filament_short",
  1496. db=db,
  1497. )
  1498. except Exception as e:
  1499. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  1500. return True
  1501. # No deficit — clear any stale flag from a previous tick.
  1502. if item.filament_short:
  1503. item.filament_short = False
  1504. await db.commit()
  1505. return False
  1506. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  1507. """Upload file and start print for a queue item.
  1508. Supports two sources:
  1509. - archive_id: Print from an existing archive
  1510. - library_file_id: Print from a library file (file manager)
  1511. """
  1512. logger.info("Starting queue item %s", item.id)
  1513. # Get printer first (needed for both paths)
  1514. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  1515. printer = result.scalar_one_or_none()
  1516. if not printer:
  1517. item.status = "failed"
  1518. item.error_message = "Printer not found"
  1519. item.completed_at = datetime.now(timezone.utc)
  1520. await db.commit()
  1521. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  1522. await self._power_off_if_needed(db, item)
  1523. return
  1524. # Check printer is connected
  1525. if not printer_manager.is_connected(item.printer_id):
  1526. item.status = "failed"
  1527. item.error_message = "Printer not connected"
  1528. item.completed_at = datetime.now(timezone.utc)
  1529. await db.commit()
  1530. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  1531. await self._power_off_if_needed(db, item)
  1532. return
  1533. # Determine source: archive or library file
  1534. archive = None
  1535. library_file = None
  1536. file_path = None
  1537. filename = None
  1538. if item.archive_id:
  1539. # Print from archive
  1540. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1541. archive = result.scalar_one_or_none()
  1542. if not archive:
  1543. item.status = "failed"
  1544. item.error_message = "Archive not found"
  1545. item.completed_at = datetime.now(timezone.utc)
  1546. await db.commit()
  1547. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  1548. await self._power_off_if_needed(db, item)
  1549. return
  1550. file_path = settings.base_dir / archive.file_path
  1551. filename = archive.filename
  1552. elif item.library_file_id:
  1553. # Print from library file (file manager)
  1554. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  1555. library_file = result.scalar_one_or_none()
  1556. if not library_file:
  1557. item.status = "failed"
  1558. item.error_message = "Library file not found"
  1559. item.completed_at = datetime.now(timezone.utc)
  1560. await db.commit()
  1561. logger.error("Queue item %s: Library file %s not found", item.id, item.library_file_id)
  1562. await self._power_off_if_needed(db, item)
  1563. return
  1564. # Library files store absolute paths
  1565. lib_path = Path(library_file.file_path)
  1566. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  1567. filename = library_file.filename
  1568. # Create archive from library file so usage tracking has access to the 3MF
  1569. try:
  1570. from backend.app.services.archive import ArchiveService
  1571. archive_service = ArchiveService(db)
  1572. archive = await archive_service.archive_print(
  1573. printer_id=item.printer_id,
  1574. source_file=file_path,
  1575. original_filename=filename,
  1576. created_by_id=item.created_by_id,
  1577. project_id=item.project_id,
  1578. )
  1579. if archive:
  1580. item.archive_id = archive.id
  1581. await db.flush()
  1582. logger.info(
  1583. "Queue item %s: Created archive %s from library file %s",
  1584. item.id,
  1585. archive.id,
  1586. item.library_file_id,
  1587. )
  1588. except Exception as e:
  1589. logger.warning("Queue item %s: Failed to create archive from library file: %s", item.id, e)
  1590. else:
  1591. # Neither archive nor library file specified
  1592. item.status = "failed"
  1593. item.error_message = "No source file specified"
  1594. item.completed_at = datetime.now(timezone.utc)
  1595. await db.commit()
  1596. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  1597. await self._power_off_if_needed(db, item)
  1598. return
  1599. # Check file exists on disk
  1600. if not file_path.exists():
  1601. item.status = "failed"
  1602. item.error_message = "Source file not found on disk"
  1603. item.completed_at = datetime.now(timezone.utc)
  1604. await db.commit()
  1605. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  1606. await self._power_off_if_needed(db, item)
  1607. return
  1608. # G-code injection for auto-print systems (#422)
  1609. injected_path = None
  1610. if item.gcode_injection:
  1611. try:
  1612. snippets_raw = await self._get_setting(db, "gcode_snippets")
  1613. if snippets_raw:
  1614. snippets = json.loads(snippets_raw)
  1615. model_snippets = snippets.get(printer.model, {})
  1616. start_gc = (model_snippets.get("start_gcode") or "").strip()
  1617. end_gc = (model_snippets.get("end_gcode") or "").strip()
  1618. if start_gc or end_gc:
  1619. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  1620. injected_path = inject_gcode_into_3mf(
  1621. file_path, item.plate_id or 1, start_gc or None, end_gc or None
  1622. )
  1623. if injected_path:
  1624. file_path = injected_path
  1625. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  1626. else:
  1627. logger.warning(
  1628. "Queue item %s: G-code injection returned no result, using original", item.id
  1629. )
  1630. except Exception as e:
  1631. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  1632. # Upload file to printer via FTP
  1633. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  1634. base_name = filename
  1635. if base_name.endswith(".gcode.3mf"):
  1636. base_name = base_name[:-10] # Remove .gcode.3mf
  1637. elif base_name.endswith(".3mf"):
  1638. base_name = base_name[:-4] # Remove .3mf
  1639. remote_filename = f"{base_name}.3mf"
  1640. # Sanitize: firmware parses ftp://{filename} as a URL, spaces break it
  1641. remote_filename = remote_filename.replace(" ", "_")
  1642. # Upload to root directory (not /cache/) - the start_print command references
  1643. # files by name only (ftp://{filename}), so they must be in the root
  1644. remote_path = f"/{remote_filename}"
  1645. # Get FTP retry settings
  1646. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1647. logger.info(
  1648. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  1649. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  1650. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  1651. )
  1652. # Delete existing file if present (avoids 553 error on overwrite)
  1653. try:
  1654. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  1655. delete_result = await delete_file_async(
  1656. printer.ip_address,
  1657. printer.access_code,
  1658. remote_path,
  1659. socket_timeout=ftp_timeout,
  1660. printer_model=printer.model,
  1661. )
  1662. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  1663. except Exception as e:
  1664. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  1665. try:
  1666. if ftp_retry_enabled:
  1667. uploaded = await with_ftp_retry(
  1668. upload_file_async,
  1669. printer.ip_address,
  1670. printer.access_code,
  1671. file_path,
  1672. remote_path,
  1673. socket_timeout=ftp_timeout,
  1674. printer_model=printer.model,
  1675. max_retries=ftp_retry_count,
  1676. retry_delay=ftp_retry_delay,
  1677. operation_name=f"Upload print to {printer.name}",
  1678. )
  1679. else:
  1680. uploaded = await upload_file_async(
  1681. printer.ip_address,
  1682. printer.access_code,
  1683. file_path,
  1684. remote_path,
  1685. socket_timeout=ftp_timeout,
  1686. printer_model=printer.model,
  1687. )
  1688. except Exception as e:
  1689. uploaded = False
  1690. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  1691. # Clean up injected temp file after upload attempt
  1692. if injected_path and injected_path.exists():
  1693. injected_path.unlink(missing_ok=True)
  1694. if not uploaded:
  1695. error_msg = (
  1696. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  1697. "See server logs for detailed diagnostics."
  1698. )
  1699. item.status = "failed"
  1700. item.error_message = error_msg
  1701. item.completed_at = datetime.now(timezone.utc)
  1702. await db.commit()
  1703. logger.error(
  1704. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  1705. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  1706. )
  1707. # Send failure notification
  1708. await notification_service.on_queue_job_failed(
  1709. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1710. printer_id=printer.id,
  1711. printer_name=printer.name,
  1712. reason="Failed to upload file to printer",
  1713. db=db,
  1714. )
  1715. await self._power_off_if_needed(db, item)
  1716. return
  1717. # Parse AMS mapping if stored
  1718. ams_mapping = None
  1719. if item.ams_mapping:
  1720. try:
  1721. ams_mapping = json.loads(item.ams_mapping)
  1722. except json.JSONDecodeError:
  1723. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  1724. # Register as expected print so we don't create a duplicate archive
  1725. # Only applicable for archive-based prints
  1726. if archive:
  1727. from backend.app.main import register_expected_print
  1728. register_expected_print(
  1729. item.printer_id,
  1730. remote_filename,
  1731. archive.id,
  1732. ams_mapping=ams_mapping,
  1733. created_by_id=item.created_by_id,
  1734. )
  1735. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  1736. # This prevents phantom reprints if the backend crashes/restarts after the
  1737. # print command is sent but before the status update is committed.
  1738. # If we crash after this commit but before start_print(), the item will be
  1739. # in "printing" status without actually printing - but that's safer than
  1740. # accidentally reprinting the same file hours later.
  1741. item.status = "printing"
  1742. item.started_at = datetime.now(timezone.utc)
  1743. await db.commit()
  1744. # Clear the awaiting-plate-clear flag now that we're starting a new print
  1745. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  1746. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  1747. # Capture state before dispatch so the watchdog can detect whether the
  1748. # printer actually transitioned (#967). Also capture subtask_id so the
  1749. # watchdog can recognise "command landed but state hasn't flipped yet"
  1750. # on slow H2D transitions (#1078).
  1751. pre_status = printer_manager.get_status(item.printer_id)
  1752. pre_state = getattr(pre_status, "state", None) if pre_status else None
  1753. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  1754. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  1755. # Start the print with AMS mapping, plate_id and print options
  1756. started = printer_manager.start_print(
  1757. item.printer_id,
  1758. remote_filename,
  1759. plate_id=item.plate_id or 1,
  1760. ams_mapping=ams_mapping,
  1761. bed_levelling=item.bed_levelling,
  1762. flow_cali=item.flow_cali,
  1763. vibration_cali=item.vibration_cali,
  1764. layer_inspect=item.layer_inspect,
  1765. timelapse=item.timelapse,
  1766. use_ams=item.use_ams,
  1767. )
  1768. if started:
  1769. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  1770. # Register the local 3MF in the cover-cache so /cover skips FTP
  1771. # (#1166 follow-up). file_path was resolved earlier from either the
  1772. # archive or the library file row.
  1773. if file_path is not None:
  1774. cache_3mf_download(item.printer_id, remote_filename, file_path)
  1775. # Hold the printer against further dispatches until the watchdog
  1776. # confirms the printer transitioned (or until the hard timeout).
  1777. # Prevents multi-plate batches from triple-dispatching onto the
  1778. # same H2D Pro while it digests the first project_file (#1157).
  1779. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  1780. # Watchdog: if the printer never transitions out of pre_state AND
  1781. # never advances subtask_id, the MQTT publish was accepted locally but
  1782. # didn't reach the printer (half-broken session — same shape as
  1783. # #887/#936). Revert the queue item so the next dispatch can pick it
  1784. # up instead of leaving it stuck in "printing" (#967). subtask_id
  1785. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  1786. # that would otherwise cause the item to re-dispatch as a reprint
  1787. # of the just-finished job (#1078).
  1788. if pre_state:
  1789. asyncio.create_task(
  1790. self._watchdog_print_start(
  1791. item.id,
  1792. item.printer_id,
  1793. pre_state,
  1794. pre_subtask_id,
  1795. pre_gcode_file,
  1796. )
  1797. )
  1798. # Get estimated time for notification
  1799. estimated_time = None
  1800. if archive and archive.print_time_seconds:
  1801. estimated_time = archive.print_time_seconds
  1802. elif library_file and library_file.print_time_seconds:
  1803. estimated_time = library_file.print_time_seconds
  1804. # Send job started notification
  1805. await notification_service.on_queue_job_started(
  1806. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1807. printer_id=printer.id,
  1808. printer_name=printer.name,
  1809. db=db,
  1810. estimated_time=estimated_time,
  1811. )
  1812. # MQTT relay - publish queue job started
  1813. try:
  1814. from backend.app.services.mqtt_relay import mqtt_relay
  1815. await mqtt_relay.on_queue_job_started(
  1816. job_id=item.id,
  1817. filename=filename,
  1818. printer_id=printer.id,
  1819. printer_name=printer.name,
  1820. printer_serial=printer.serial_number,
  1821. )
  1822. except Exception:
  1823. pass # Don't fail if MQTT fails
  1824. else:
  1825. # Clean up uploaded file from SD card to prevent phantom prints
  1826. try:
  1827. await delete_file_async(
  1828. printer.ip_address,
  1829. printer.access_code,
  1830. remote_path,
  1831. printer_model=printer.model,
  1832. )
  1833. except Exception:
  1834. pass # Best-effort — don't fail the error handler
  1835. # Print command failed - revert status
  1836. item.status = "failed"
  1837. item.error_message = "Failed to send print command to printer"
  1838. item.completed_at = datetime.now(timezone.utc)
  1839. await db.commit()
  1840. logger.error(
  1841. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  1842. f"printer_manager.start_print() returned False. "
  1843. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  1844. f"Check printer status and backend logs for details."
  1845. )
  1846. # Send failure notification
  1847. await notification_service.on_queue_job_failed(
  1848. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1849. printer_id=printer.id,
  1850. printer_name=printer.name,
  1851. reason="Failed to send print command to printer - check printer connection and status",
  1852. db=db,
  1853. )
  1854. await self._power_off_if_needed(db, item)
  1855. @staticmethod
  1856. async def _watchdog_print_start(
  1857. queue_item_id: int,
  1858. printer_id: int,
  1859. pre_state: str,
  1860. pre_subtask_id: str | None = None,
  1861. pre_gcode_file: str | None = None,
  1862. timeout: float = 90.0,
  1863. poll_interval: float = 3.0,
  1864. ) -> None:
  1865. """Revert a queue item if the printer never acknowledges the start command.
  1866. Bambuddy optimistically marks the queue item as "printing" right after the
  1867. MQTT project_file publish succeeds locally. If the printer drops/ignores the
  1868. command (half-broken MQTT session — #887/#936), the state never transitions
  1869. and the item would otherwise stay stuck in "printing" forever (#967).
  1870. Exit paths (printer picked up the job — no revert):
  1871. - gcode_state changed from pre_state, OR
  1872. - subtask_id advanced past pre_subtask_id — the printer echoes our
  1873. per-dispatch identity back on push_status, so a subtask_id change is
  1874. a definitive "command landed" signal even while state is still FINISH.
  1875. H2D can sit at FINISH for ~50 s after accepting project_file before
  1876. transitioning to PREPARE, which used to trip the state-only watchdog
  1877. and caused the scheduler to revert + re-dispatch the item; the next
  1878. successful dispatch then looked like a reprint of the just-finished
  1879. job (#1078).
  1880. Timeout raised from 45 s → 90 s as belt-and-braces for slow transitions
  1881. that also don't emit an early subtask_id tick.
  1882. """
  1883. deadline = time.monotonic() + timeout
  1884. last_status = None
  1885. while time.monotonic() < deadline:
  1886. await asyncio.sleep(poll_interval)
  1887. status = printer_manager.get_status(printer_id)
  1888. if not status:
  1889. # Printer disconnected — don't mess with the DB. Drop the
  1890. # in-memory dispatch hold too so a fresh dispatch can retry
  1891. # once the printer comes back; the hard timeout would
  1892. # otherwise hold the printer unnecessarily.
  1893. scheduler._release_dispatch_hold(printer_id)
  1894. return
  1895. last_status = status
  1896. if status.state in _ACTIVE_PRINT_STATES:
  1897. # Printer is actively processing the job — release the
  1898. # post-dispatch hold so the next pending item for this printer
  1899. # can be evaluated normally. We do NOT accept arbitrary state
  1900. # transitions: a printer going FINISH -> IDLE (user dismissed
  1901. # the post-print prompt without accepting our project_file)
  1902. # would otherwise look like "command landed" and leave the
  1903. # queue item stuck in 'printing' forever (#1370).
  1904. scheduler._release_dispatch_hold(printer_id)
  1905. return
  1906. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  1907. # Printer picked up the job (subtask_id advanced). H2D can
  1908. # sit at FINISH for ~50 s after accepting project_file
  1909. # before transitioning to PREPARE, but the subtask_id flips
  1910. # to our submission_id almost immediately (#1078).
  1911. scheduler._release_dispatch_hold(printer_id)
  1912. return
  1913. # No transition. Revert the item so the scheduler can retry.
  1914. # Drop the in-memory hold so the retry isn't blocked by it.
  1915. scheduler._release_dispatch_hold(printer_id)
  1916. # Three outcomes from the revert attempt, each routed differently:
  1917. # "reverted": row flipped from printing -> pending, run recovery
  1918. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  1919. # on_print_complete or user). Skip recovery entirely
  1920. # — the print clearly landed somewhere even if the
  1921. # watchdog didn't see the active-state transition.
  1922. # "revert_failed": SQLite contention exhausted retries. Still run
  1923. # recovery so the MQTT session gets a fresh client_id
  1924. # on the half-broken-session path.
  1925. async def _do_revert(db):
  1926. item = await db.get(PrintQueueItem, queue_item_id)
  1927. if not item or item.status != "printing":
  1928. return "already_moved_on"
  1929. item.status = "pending"
  1930. item.started_at = None
  1931. await db.commit()
  1932. return "reverted"
  1933. try:
  1934. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  1935. except Exception as e:
  1936. logger.warning(
  1937. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  1938. "scheduler may keep treating this item as in-flight",
  1939. queue_item_id,
  1940. printer_id,
  1941. e,
  1942. )
  1943. revert_outcome = "revert_failed"
  1944. if revert_outcome == "already_moved_on":
  1945. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  1946. # other path) already moved the item past 'printing', don't run the
  1947. # MQTT session-recovery logic below — a forced reconnect on a healthy
  1948. # session breaks ongoing prints on the same printer.
  1949. return
  1950. if revert_outcome == "reverted":
  1951. logger.warning(
  1952. "Queue item %s: printer %d did not respond to print command within "
  1953. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  1954. "for retry (#967)",
  1955. queue_item_id,
  1956. printer_id,
  1957. timeout,
  1958. pre_state,
  1959. pre_subtask_id,
  1960. )
  1961. # Same #1150 / #887/#936 discriminator as background_dispatch: if the
  1962. # printer's gcode_file changed since pre-dispatch, the project_file
  1963. # command landed and the printer is parsing — a forced reconnect
  1964. # mid-parse triggers 0500_4003. If gcode_file is unchanged, the
  1965. # publish was silently swallowed (#887/#936) and the original
  1966. # force_reconnect recovery is what we want.
  1967. client = printer_manager.get_client(printer_id)
  1968. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  1969. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  1970. if publish_landed:
  1971. logger.warning(
  1972. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  1973. "received the command and is parsing slowly. Skipping forced "
  1974. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  1975. queue_item_id,
  1976. current_gcode_file,
  1977. pre_gcode_file,
  1978. )
  1979. elif client and hasattr(client, "force_reconnect_stale_session"):
  1980. client.force_reconnect_stale_session(
  1981. f"queue print command unacknowledged after {timeout:.0f}s "
  1982. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  1983. )
  1984. # Global scheduler instance
  1985. scheduler = PrintScheduler()