print_scheduler.py 131 KB

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