print_scheduler.py 130 KB

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