print_scheduler.py 178 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. from datetime import datetime, timezone
  7. from pathlib import Path
  8. from sqlalchemy import func, select, update
  9. from sqlalchemy.ext.asyncio import AsyncSession
  10. from sqlalchemy.orm import selectinload
  11. from backend.app.core.config import settings
  12. from backend.app.core.database import async_session, run_with_retry
  13. from backend.app.core.tasks import spawn_background_task
  14. from backend.app.core.websocket import ws_manager
  15. from backend.app.models.archive import PrintArchive
  16. from backend.app.models.library import LibraryFile
  17. from backend.app.models.print_queue import PrintQueueItem
  18. from backend.app.models.printer import Printer
  19. from backend.app.models.settings import Settings
  20. from backend.app.models.smart_plug import SmartPlug
  21. from backend.app.models.spool_assignment import SpoolAssignment
  22. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  23. from backend.app.services.bambu_ftp import (
  24. UploadCancelled,
  25. cache_3mf_download,
  26. delete_file_async,
  27. get_ftp_retry_settings,
  28. upload_file_async,
  29. with_ftp_retry,
  30. )
  31. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  32. from backend.app.services.notification_service import notification_service
  33. from backend.app.services.printer_manager import (
  34. printer_manager,
  35. supports_airduct,
  36. supports_chamber_heater,
  37. supports_chamber_temp,
  38. supports_drying,
  39. supports_drying_while_printing,
  40. )
  41. from backend.app.services.smart_plug_manager import smart_plug_manager
  42. from backend.app.utils.filename import derive_remote_filename
  43. from backend.app.utils.printer_models import is_gcode_compatible, normalize_printer_model
  44. logger = logging.getLogger(__name__)
  45. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  46. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  47. # byte gate) from before the scheduler unification. Time gate keeps small
  48. # files from going silent (a single 8 KB chunk fires once and that's it);
  49. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  50. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  51. # sub-200 ms files.
  52. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  53. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  54. class _UploadProgressBridge:
  55. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  56. ``upload_file_async`` runs the FTP transfer in an executor thread and
  57. invokes its ``progress_callback`` from that thread, so the callback
  58. body cannot ``await`` directly. This bridge captures the asyncio loop
  59. at construction (on the scheduler thread) and uses
  60. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  61. matches the legacy background_dispatch.py path 1:1 so the toast feels
  62. identical to the pre-#1625 experience.
  63. Failures inside the emit are swallowed — progress is a UX nicety, the
  64. upload itself must not fail because of a WS hiccup.
  65. """
  66. def __init__(self, user_id: int | None, queue_item_id: int):
  67. self._user_id = user_id
  68. self._queue_item_id = queue_item_id
  69. try:
  70. self._loop = asyncio.get_running_loop()
  71. except RuntimeError:
  72. self._loop = None
  73. self._last_emit_bytes = 0
  74. self._last_emit_monotonic = 0.0
  75. self._has_emitted = False
  76. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  77. if self._loop is None or total_bytes <= 0:
  78. return
  79. now = time.monotonic()
  80. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  81. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  82. # the four matter most: first-call so the user sees something even
  83. # for sub-chunk-size files; uploaded >= total so the bar locks at
  84. # 100% even when the throttle would otherwise eat it.
  85. should_emit = (
  86. not self._has_emitted
  87. or bytes_transferred >= total_bytes
  88. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  89. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  90. )
  91. if not should_emit:
  92. return
  93. self._has_emitted = True
  94. self._last_emit_bytes = bytes_transferred
  95. self._last_emit_monotonic = now
  96. try:
  97. asyncio.run_coroutine_threadsafe(
  98. ws_manager.send_queue_item_upload_progress(
  99. user_id=self._user_id,
  100. queue_item_id=self._queue_item_id,
  101. bytes_transferred=bytes_transferred,
  102. total_bytes=total_bytes,
  103. ),
  104. self._loop,
  105. )
  106. except Exception:
  107. pass # progress is best-effort, never block the upload
  108. # Bambu firmware states that mean the project_file has actually been accepted
  109. # and the printer is now processing / running / paused mid-print. Used by the
  110. # dispatch watchdog (#1370): a transition into one of these states means the
  111. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  112. # a post-print prompt) is NOT a valid "command landed" signal even though the
  113. # state value did change. SLICING is included because some firmwares park
  114. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  115. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  116. # How many times the start-watchdog may revert an item to 'pending' before it
  117. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  118. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  119. # both never recovers and starves the other printers of dispatch slots. Three
  120. # is chosen to clear the transient causes the watchdog already recovers from —
  121. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  122. # force-reconnect on the very next attempt — while still bounding the loop.
  123. DISPATCH_MAX_ATTEMPTS = 3
  124. # Filament type equivalence groups — types within the same group are
  125. # interchangeable on the printer side (Bambu Lab firmware treats them as compatible).
  126. _FILAMENT_TYPE_GROUPS: list[list[str]] = [
  127. ["PA-CF", "PA12-CF", "PAHT-CF"],
  128. ]
  129. _FILAMENT_EQUIV_MAP: dict[str, str] = {}
  130. for _group in _FILAMENT_TYPE_GROUPS:
  131. _canonical = _group[0].upper()
  132. for _t in _group:
  133. _FILAMENT_EQUIV_MAP[_t.upper()] = _canonical
  134. def _canonical_filament_type(ftype: str) -> str:
  135. """Return canonical type for equivalence matching."""
  136. upper = ftype.upper()
  137. return _FILAMENT_EQUIV_MAP.get(upper, upper)
  138. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  139. """True if ``mapping`` is a non-empty list whose every entry is the
  140. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  141. Such a mapping is a bug artifact: a frontend status-load race can serialize
  142. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  143. recomputed from live status at dispatch rather than trusted, otherwise it
  144. reaches the print command and is silently downgraded to external-spool mode.
  145. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  146. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  147. explicit external selection (``>= 254``) is NOT unresolved either — those
  148. keep their meaning.
  149. """
  150. if not isinstance(mapping, list) or not mapping:
  151. return False
  152. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  153. def _installed_nozzle_diameters(status) -> list[float]:
  154. """Parse the installed nozzle diameters from a PrinterState (#1899).
  155. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  156. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  157. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  158. told us its nozzle hardware" — callers must treat that as unknown, not as a
  159. mismatch, so we never block a print on missing data.
  160. """
  161. diameters: list[float] = []
  162. for nozzle in getattr(status, "nozzles", None) or []:
  163. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  164. try:
  165. value = float(raw)
  166. except (TypeError, ValueError):
  167. continue
  168. if value > 0:
  169. diameters.append(value)
  170. return diameters
  171. def _nozzle_mismatch_message(sliced_nozzle: float | None, installed: list[float]) -> str | None:
  172. """Return an actionable error message when the sliced nozzle can't be
  173. printed on any installed nozzle, else None (#1899).
  174. Fail-safe: returns None whenever we lack the data to judge — no sliced
  175. diameter, or the printer reported no nozzles — so a print is only ever
  176. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  177. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  178. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  179. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  180. """
  181. if not sliced_nozzle or not installed:
  182. return None
  183. if any(abs(d - sliced_nozzle) < 0.05 for d in installed):
  184. return None
  185. installed_str = " / ".join(f"{d:g}mm" for d in installed)
  186. return (
  187. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  188. f"{installed_str} installed. Re-slice for the installed nozzle, or "
  189. f"install the matching nozzle before printing."
  190. )
  191. class PrintScheduler:
  192. """Background scheduler that processes the print queue."""
  193. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  194. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  195. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  196. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  197. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  198. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  199. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  200. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  201. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  202. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  203. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  204. }
  205. def __init__(self):
  206. self._running = False
  207. self._check_interval = 30 # seconds
  208. # After a pass that actually dispatched something, loop again almost
  209. # immediately instead of sleeping the full interval (#2555). A dispatch
  210. # changes printer state — a batch launch fans out over several passes as
  211. # printers free up, a wedged head-of-line job reverts to pending, an
  212. # upload slot opens — and the next batch of ready work should not have to
  213. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  214. # pending items are behind printers that are genuinely busy printing),
  215. # there is nothing to react to, so we fall back to the normal interval;
  216. # that also means this can never tight-loop, since fast ticks only
  217. # continue while dispatches keep happening and the queue is draining.
  218. self._fast_check_interval = 3 # seconds
  219. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  220. self._power_on_check_interval = 10 # seconds between connection checks
  221. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  222. self._drying_in_progress: dict[int, float] = {}
  223. # Defensive in-memory dispatch hold (#1157): a printer that just received
  224. # a project_file command must not get a second dispatch until either it
  225. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  226. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  227. # during that window the DB busy_printers seed is empirically unreliable
  228. # (multi-plate batches double-/triple-dispatched onto the same printer
  229. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  230. # or revert.
  231. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  232. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  233. # Minimum cooldown between dispatches to the same printer (covers the
  234. # H2D's project_file digestion window).
  235. self._dispatch_min_cooldown = 60.0
  236. # Hard timeout — drop the hold even if we never observed a transition,
  237. # so a lost MQTT session can't lock a printer out of the queue forever.
  238. # Matches the watchdog timeout (90 s) plus a safety margin so the
  239. # watchdog runs first on the unhappy path.
  240. self._dispatch_max_hold = 180.0
  241. async def run(self):
  242. """Main loop - check queue every interval."""
  243. self._running = True
  244. logger.info("Print scheduler started")
  245. while self._running:
  246. dispatched = False
  247. try:
  248. dispatched = await self.check_queue()
  249. except Exception as e:
  250. logger.error("Scheduler error: %s", e)
  251. # Re-check quickly after a productive pass so a draining batch does
  252. # not stall behind the idle interval; otherwise sleep normally (#2555).
  253. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  254. def stop(self):
  255. """Stop the scheduler."""
  256. self._running = False
  257. logger.info("Print scheduler stopped")
  258. async def check_queue(self) -> bool:
  259. """Check for prints ready to start.
  260. Returns True if this pass dispatched at least one item, so the caller
  261. can loop again quickly instead of sleeping the full interval (#2555).
  262. """
  263. async with async_session() as db:
  264. # Check if shortest-job-first scheduling is enabled
  265. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  266. # Get all pending items, ordered by printer and position (or SJF order)
  267. if sjf_enabled:
  268. # SJF: group by printer (and target_model for model-based jobs),
  269. # then items already jumped get top priority (starvation guard),
  270. # then sort by print_time ascending. Items with no print time go last.
  271. result = await db.execute(
  272. select(PrintQueueItem)
  273. .where(PrintQueueItem.status == "pending")
  274. # archive/library_file are read by the cross-model gate
  275. # (#2578); eager-load once per pass instead of a lazy-load
  276. # (which would raise in async) per item.
  277. .options(
  278. selectinload(PrintQueueItem.archive),
  279. selectinload(PrintQueueItem.library_file),
  280. )
  281. .order_by(
  282. PrintQueueItem.printer_id,
  283. PrintQueueItem.target_model,
  284. PrintQueueItem.been_jumped.desc(),
  285. PrintQueueItem.print_time_seconds.asc().nullslast(),
  286. PrintQueueItem.position,
  287. )
  288. )
  289. else:
  290. result = await db.execute(
  291. select(PrintQueueItem)
  292. .where(PrintQueueItem.status == "pending")
  293. .options(
  294. selectinload(PrintQueueItem.archive),
  295. selectinload(PrintQueueItem.library_file),
  296. )
  297. .order_by(PrintQueueItem.printer_id, PrintQueueItem.position)
  298. )
  299. items = list(result.scalars().all())
  300. # Read plate-clear setting once per queue check. Default MUST be
  301. # False to match the schema (SettingsSchema.require_plate_clear
  302. # defaults False) and the frontend (toggle + card badge both treat a
  303. # missing value as off). When no settings row exists, a True default
  304. # here re-enabled the plate-clear gate the UI showed as disabled,
  305. # blocking dispatch to FINISH-state printers forever with no UI path
  306. # to clear it (#1865).
  307. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  308. if not items:
  309. # No pending items — still check auto-drying on idle printers
  310. await self._check_auto_drying(db, [], set(), require_plate_clear=require_plate_clear)
  311. return False
  312. logger.info(
  313. "Queue check: found %d pending items: %s",
  314. len(items),
  315. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  316. )
  317. # Seed busy_printers with printers that already have an item in 'printing'
  318. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  319. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  320. # lag several seconds behind the print command, so the next check_queue
  321. # tick still sees IDLE and would double-dispatch onto the same printer.
  322. # Without this guard, two pending items targeting the same printer
  323. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  324. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  325. busy_result = await db.execute(
  326. select(PrintQueueItem.printer_id)
  327. .where(PrintQueueItem.status == "printing")
  328. .where(PrintQueueItem.printer_id.is_not(None))
  329. )
  330. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  331. # Defense-in-depth (#1157): augment busy_printers with any printer
  332. # still in its post-dispatch hold window. Empirically, the DB seed
  333. # above can miss in-flight items in a multi-plate batch — same-file
  334. # plates were being dispatched 30 s apart while the H2D was still
  335. # digesting the first project_file. The hold is keyed in-memory and
  336. # released by the watchdog on the success path, so it adds a layer
  337. # that doesn't depend on DB row visibility or completion-callback
  338. # timing.
  339. for held_printer_id in list(self._dispatch_holds.keys()):
  340. if self._printer_in_dispatch_hold(held_printer_id):
  341. busy_printers.add(held_printer_id)
  342. # Log skip reasons once per queue check (not per item)
  343. skip_reasons: dict[str, int] = {}
  344. # Items selected for dispatch in this pass, one per printer. The
  345. # loop below only *decides* — the uploads happen afterwards, in
  346. # parallel (#2555). See _dispatch_selected().
  347. dispatch_ids: list[int] = []
  348. # Library rows queued with `cleanup_library_after_dispatch` (the
  349. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  350. # that prints them: the row is deleted and the 3MF is unlinked from
  351. # disk. That was safe only because dispatch was serial. Run two of
  352. # them against the same row at once and the second DELETE matches no
  353. # row (StaleDataError), and the winner's unlink can pull the file out
  354. # from under the loser's in-flight upload.
  355. #
  356. # Only the cleanup flag mutates the row. An ordinary library print
  357. # just reads it, so the common fan-out — one file, many printers,
  358. # which is exactly the reporter's workload — still goes out fully in
  359. # parallel. Narrow the guard to the mutating case; do not serialise
  360. # the case the whole fix exists for.
  361. dispatch_libs: set[int] = set()
  362. consumed_libs: set[int] = set()
  363. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  364. """True if dispatching `candidate` now would race another item's cleanup."""
  365. lib_id = candidate.library_file_id
  366. if lib_id is None:
  367. return False
  368. if candidate.cleanup_library_after_dispatch:
  369. # We would delete a row someone else in this pass is reading.
  370. return lib_id in dispatch_libs
  371. # Someone else in this pass will delete the row out from under us.
  372. return lib_id in consumed_libs
  373. def _claim_library_row(candidate: PrintQueueItem) -> None:
  374. lib_id = candidate.library_file_id
  375. if lib_id is None:
  376. return
  377. dispatch_libs.add(lib_id)
  378. if candidate.cleanup_library_after_dispatch:
  379. consumed_libs.add(lib_id)
  380. for item in items:
  381. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  382. if item.scheduled_time:
  383. sched = item.scheduled_time
  384. if sched.tzinfo is None:
  385. sched = sched.replace(tzinfo=timezone.utc)
  386. if sched > datetime.now(timezone.utc):
  387. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  388. continue
  389. # Skip items that require manual start
  390. if item.manual_start:
  391. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  392. continue
  393. if item.printer_id:
  394. # Specific printer assignment (existing behavior)
  395. if item.printer_id in busy_printers:
  396. continue
  397. # Check if printer is idle
  398. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  399. printer_connected = printer_manager.is_connected(item.printer_id)
  400. # If printer not connected, try to power on via smart plug
  401. if not printer_connected:
  402. plugs = await self._get_smart_plugs(db, item.printer_id)
  403. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  404. if auto_on_plugs:
  405. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  406. # Power on using the first auto_on plug (the printer power plug)
  407. powered_on = await self._power_on_and_wait(auto_on_plugs[0], item.printer_id, db)
  408. if powered_on:
  409. # Also turn on any remaining auto_on plugs (e.g., filter)
  410. for extra_plug in auto_on_plugs[1:]:
  411. try:
  412. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  413. await service.turn_on(extra_plug)
  414. logger.info(
  415. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  416. )
  417. except Exception as e:
  418. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  419. printer_connected = True
  420. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  421. else:
  422. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  423. busy_printers.add(item.printer_id)
  424. continue
  425. else:
  426. # No plug or auto_on disabled
  427. busy_printers.add(item.printer_id)
  428. continue
  429. # Check if printer is idle (busy with another print)
  430. if not printer_idle:
  431. # If printer is drying (not truly busy), handle based on queue_drying_block
  432. if self._drying_in_progress.get(item.printer_id):
  433. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  434. if block_for_drying:
  435. # Drying blocks queue — skip this printer
  436. busy_printers.add(item.printer_id)
  437. continue
  438. else:
  439. # Print takes priority — stop drying
  440. await self._stop_drying(item.printer_id)
  441. # Re-check idle after stopping drying
  442. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  443. if not printer_idle:
  444. busy_printers.add(item.printer_id)
  445. continue
  446. else:
  447. busy_printers.add(item.printer_id)
  448. continue
  449. # Check condition (previous print success)
  450. if item.require_previous_success:
  451. if not await self._check_previous_success(db, item):
  452. item.status = "skipped"
  453. item.error_message = "Previous print failed or was aborted"
  454. item.completed_at = datetime.now(timezone.utc)
  455. await db.commit()
  456. logger.info("Skipped queue item %s - previous print failed", item.id)
  457. # Send notification
  458. job_name = await self._get_job_name(db, item)
  459. printer = await self._get_printer(db, item.printer_id)
  460. await notification_service.on_queue_job_skipped(
  461. job_name=job_name,
  462. printer_id=item.printer_id,
  463. printer_name=printer.name if printer else "Unknown",
  464. reason="Previous print failed or was aborted",
  465. db=db,
  466. )
  467. continue
  468. # Resolve the AMS mapping when it's missing OR unresolved
  469. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  470. # frontend status-load race can persist [-1] (#2589) — and
  471. # must be recomputed from live trays rather than trusted.
  472. await self._ensure_ams_mapping(db, item.printer_id, item)
  473. # Filament-deficit pre-dispatch check (#1496). If the
  474. # assigned spool can't satisfy any required slot grams,
  475. # promote the item to manual_start so the user must
  476. # acknowledge via the ▶ button (which re-checks live).
  477. if await self._block_on_filament_deficit(db, item):
  478. continue
  479. # Hold this item back for the next pass rather than racing
  480. # another dispatch over the same transient library row. The
  481. # printer is still marked busy so a later item does not jump
  482. # its place in this printer's queue.
  483. if _library_row_conflict(item):
  484. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  485. busy_printers.add(item.printer_id)
  486. continue
  487. # Queue the dispatch instead of running it here — see
  488. # _dispatch_selected(). busy_printers still gets the printer
  489. # immediately, so nothing else in this pass can target it.
  490. _claim_library_row(item)
  491. dispatch_ids.append(item.id)
  492. busy_printers.add(item.printer_id)
  493. # SJF starvation guard: mark items that were jumped
  494. if sjf_enabled and item.print_time_seconds is not None:
  495. for other in items:
  496. if (
  497. other.id != item.id
  498. and other.status == "pending"
  499. and other.printer_id == item.printer_id
  500. and not other.been_jumped
  501. and other.position < item.position
  502. and (
  503. other.print_time_seconds is None
  504. or other.print_time_seconds > item.print_time_seconds
  505. )
  506. ):
  507. other.been_jumped = True
  508. await db.commit()
  509. elif item.target_model:
  510. # Model-based assignment - find any idle printer of matching model
  511. # Parse required filament types if present
  512. required_types = None
  513. if item.required_filament_types:
  514. try:
  515. required_types = json.loads(item.required_filament_types)
  516. except json.JSONDecodeError:
  517. pass # Ignore malformed filament types; treat as no constraint
  518. # Parse filament overrides if present
  519. filament_overrides = None
  520. if item.filament_overrides:
  521. try:
  522. filament_overrides = json.loads(item.filament_overrides)
  523. except json.JSONDecodeError:
  524. pass
  525. # If overrides exist, use override types for validation instead
  526. effective_types = required_types
  527. if filament_overrides:
  528. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  529. if override_types:
  530. # Merge: keep original types for non-overridden slots, add override types
  531. effective_types = sorted(set(required_types or []) | set(override_types))
  532. # Cross-model safety gate (#2578): never hand a 3MF sliced
  533. # for an incompatible model to a printer, no matter how the
  534. # row got into the DB (old rows, direct API writes). Held
  535. # as pending with an actionable waiting_reason — the user
  536. # fixes it by editing the item's target model.
  537. sliced_for = None
  538. if item.archive:
  539. sliced_for = item.archive.sliced_for_model
  540. elif item.library_file and item.library_file.file_metadata:
  541. sliced_for = item.library_file.file_metadata.get("sliced_for_model")
  542. if not is_gcode_compatible(sliced_for, item.target_model):
  543. printer_id = None
  544. waiting_reason = (
  545. f"File was sliced for {sliced_for}, which is not compatible with "
  546. f"{item.target_model} — edit the item and fix its target model"
  547. )
  548. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  549. else:
  550. printer_id, waiting_reason = await self._find_idle_printer_for_model(
  551. db,
  552. item.target_model,
  553. busy_printers,
  554. effective_types,
  555. item.target_location,
  556. filament_overrides=filament_overrides,
  557. require_plate_clear=require_plate_clear,
  558. )
  559. # Update waiting_reason if changed and send notification when first waiting
  560. if item.waiting_reason != waiting_reason:
  561. was_waiting = item.waiting_reason is not None
  562. item.waiting_reason = waiting_reason
  563. await db.commit()
  564. # Send waiting notification only when transitioning to waiting state
  565. # and the reason requires user action (not just "all printers busy")
  566. if waiting_reason and not was_waiting and not self._is_busy_only(waiting_reason):
  567. job_name = await self._get_job_name(db, item)
  568. await notification_service.on_queue_job_waiting(
  569. job_name=job_name,
  570. target_model=item.target_model,
  571. waiting_reason=waiting_reason,
  572. db=db,
  573. )
  574. if printer_id:
  575. # Before claiming the printer: hold back rather than race
  576. # another dispatch over the same transient library row.
  577. # Checked here so a held item does not get a printer
  578. # assigned and then sit on it. See _library_row_conflict().
  579. #
  580. # No busy_printers.add() here, unlike the fixed-printer
  581. # branch above: that one protects its printer's own queue
  582. # ordering, but this item was never assigned to `printer_id`
  583. # — the matcher merely offered it. Marking it busy would
  584. # strand an idle printer for the rest of the pass.
  585. if _library_row_conflict(item):
  586. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  587. continue
  588. # Check condition (previous print success) before assigning
  589. if item.require_previous_success:
  590. if not await self._check_previous_success(db, item):
  591. item.status = "skipped"
  592. item.error_message = "Previous print failed or was aborted"
  593. item.completed_at = datetime.now(timezone.utc)
  594. await db.commit()
  595. logger.info("Skipped queue item %s - previous print failed", item.id)
  596. # Send notification
  597. job_name = await self._get_job_name(db, item)
  598. printer = await self._get_printer(db, printer_id)
  599. await notification_service.on_queue_job_skipped(
  600. job_name=job_name,
  601. printer_id=printer_id,
  602. printer_name=printer.name if printer else "Unknown",
  603. reason="Previous print failed or was aborted",
  604. db=db,
  605. )
  606. continue
  607. # Assign printer and start - clear waiting reason
  608. item.printer_id = printer_id
  609. item.waiting_reason = None
  610. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  611. # Send assignment notification
  612. job_name = await self._get_job_name(db, item)
  613. printer = await self._get_printer(db, printer_id)
  614. await notification_service.on_queue_job_assigned(
  615. job_name=job_name,
  616. printer_id=printer_id,
  617. printer_name=printer.name if printer else "Unknown",
  618. target_model=item.target_model,
  619. db=db,
  620. )
  621. # Resolve the AMS mapping for the assigned printer when it's
  622. # missing OR unresolved (all -1). Critical for model-based
  623. # jobs where mapping wasn't computed upfront, and it also
  624. # self-heals a bogus stored [-1] (#2589).
  625. await self._ensure_ams_mapping(db, printer_id, item)
  626. # Filament-deficit pre-dispatch check (#1496).
  627. if await self._block_on_filament_deficit(db, item):
  628. continue
  629. _claim_library_row(item)
  630. dispatch_ids.append(item.id)
  631. busy_printers.add(printer_id)
  632. # SJF starvation guard: mark model-based items that were jumped
  633. if sjf_enabled and item.print_time_seconds is not None:
  634. for other in items:
  635. if (
  636. other.id != item.id
  637. and other.status == "pending"
  638. and other.printer_id is None
  639. and other.target_model
  640. and other.target_model.upper() == item.target_model.upper()
  641. and not other.been_jumped
  642. and other.position < item.position
  643. and (
  644. other.print_time_seconds is None
  645. or other.print_time_seconds > item.print_time_seconds
  646. )
  647. ):
  648. other.been_jumped = True
  649. await db.commit()
  650. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  651. # as long as the slowest upload takes (minutes on a big 3MF), and a
  652. # skip summary that only lands after the transfers have finished is
  653. # useless for working out why an item did not go out.
  654. if skip_reasons:
  655. logger.info("Queue skip summary: %s", skip_reasons)
  656. if busy_printers:
  657. # Log why each printer was busy (first time it was checked)
  658. for pid in busy_printers:
  659. state = printer_manager.get_status(pid)
  660. connected = printer_manager.is_connected(pid)
  661. awaiting = printer_manager.is_awaiting_plate_clear(pid)
  662. state_name = state.state if state else "NO_STATUS"
  663. logger.info(
  664. "Queue: printer %d not available — connected=%s, state=%s, awaiting_plate_clear=%s",
  665. pid,
  666. connected,
  667. state_name,
  668. awaiting,
  669. )
  670. # Read the concurrency limit BEFORE the commit below, not inside
  671. # _dispatch_selected(). A SELECT on this session after the commit
  672. # implicitly opens a fresh transaction that nothing then closes, and
  673. # it would stay open for the whole dispatch — minutes of "idle in
  674. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  675. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  676. # checkpointed while every dispatch is writing to it.
  677. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  678. # Selection is done; every decision above is recorded on `db`
  679. # (model-based printer assignment, computed ams_mapping). Flush it
  680. # before the dispatch tasks open their own sessions, or they will
  681. # read a row that still says printer_id=None. This also releases the
  682. # connection back to the pool for the duration of the dispatch.
  683. await db.commit()
  684. if dispatch_ids:
  685. await self._dispatch_selected(dispatch_ids, upload_limit)
  686. # Auto-drying: start drying on idle printers that have no pending queue items
  687. await self._check_auto_drying(db, items, busy_printers, require_plate_clear=require_plate_clear)
  688. return bool(dispatch_ids)
  689. async def _dispatch_selected(self, item_ids: list[int], limit: int) -> None:
  690. """Upload and start every item selected by this queue pass, in parallel.
  691. Dispatch used to happen inline in the selection loop: ``await
  692. _start_print(db, item)`` for each item in turn. Since ``_start_print``
  693. performs the FTP upload, that serialized every printer behind every
  694. other printer's transfer — even though the printers are entirely
  695. independent machines. A Bambu printer's FTP server sustains ~150 KB/s
  696. (its own SD write is the bottleneck, not the network), so a 41 MB 3MF
  697. takes ~4 minutes. The reporter's 19-printer farm therefore needed ~80
  698. minutes before the last printer received its file, and the queue looked
  699. like it was starting prints "one by one, very slowly" (#2555).
  700. Uploads to *different* printers contend for nothing, so they run
  701. concurrently here, bounded by ``queue_max_concurrent_uploads``. The
  702. bound exists because the printers are independent but the host is not:
  703. each in-flight upload holds a thread in the FTP pool, a TLS session and
  704. a file handle.
  705. This is awaited before ``check_queue`` returns, which preserves the
  706. invariant the rest of the scheduler is built on: a pass never overlaps
  707. with the next one. It matters more than it looks — ``_start_print``
  708. flips the row pending -> printing only *after* the upload finishes, so
  709. a pass that returned early while uploads were still in flight would let
  710. the next pass re-dispatch the very same still-pending rows.
  711. ``limit`` is read by the caller, on the caller's session, before it
  712. commits — reading it here would leave that session idle-in-transaction
  713. for the whole dispatch. This function deliberately takes no session.
  714. """
  715. sem = asyncio.Semaphore(limit)
  716. async def _one(item_id: int) -> None:
  717. # Its own session: these run concurrently, and an AsyncSession is not
  718. # safe to share across tasks. It also keeps a slow upload from pinning
  719. # the caller's session (and, on SQLite, its transaction) open for the
  720. # duration.
  721. async with sem, async_session() as item_db:
  722. item = await item_db.get(PrintQueueItem, item_id)
  723. if not item:
  724. logger.info("Queue item %s vanished before dispatch — skipping", item_id)
  725. return
  726. await self._start_print(item_db, item)
  727. logger.info(
  728. "Dispatching %d queue item(s) with up to %d concurrent upload(s): %s",
  729. len(item_ids),
  730. limit,
  731. item_ids,
  732. )
  733. results = await asyncio.gather(*(_one(i) for i in item_ids), return_exceptions=True)
  734. # gather() with return_exceptions keeps one printer's failure from
  735. # cancelling its siblings' in-flight uploads. _start_print already
  736. # handles its own failure modes and marks the item failed; anything
  737. # arriving here is unexpected, so log it loudly rather than letting
  738. # gather swallow it.
  739. for item_id, result in zip(item_ids, results, strict=True):
  740. if isinstance(result, BaseException):
  741. logger.error("Queue item %s: dispatch raised %s: %s", item_id, type(result).__name__, result)
  742. async def _find_idle_printer_for_model(
  743. self,
  744. db: AsyncSession,
  745. model: str,
  746. exclude_ids: set[int],
  747. required_filament_types: list[str] | None = None,
  748. target_location: str | None = None,
  749. filament_overrides: list[dict] | None = None,
  750. require_plate_clear: bool = True,
  751. ) -> tuple[int | None, str | None]:
  752. """Find an idle, connected printer matching the model with compatible filaments.
  753. Args:
  754. db: Database session
  755. model: Printer model to match (e.g., "X1C", "P1S")
  756. exclude_ids: Printer IDs to exclude (already busy)
  757. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  758. If provided, only printers with all required types loaded will match.
  759. target_location: Optional location filter. If provided, only printers in this location are considered.
  760. filament_overrides: Optional list of override dicts. Each entry may include
  761. ``force_color_match: true`` to require an exact type+color match
  762. on the printer for that slot. Without the flag the existing
  763. colour-preference logic applies.
  764. Returns:
  765. Tuple of (printer_id, waiting_reason):
  766. - (printer_id, None) if a matching printer was found
  767. - (None, reason) if no printer is available, with explanation
  768. """
  769. # Normalize model name and use case-insensitive matching
  770. normalized_model = normalize_printer_model(model) or model
  771. query = (
  772. select(Printer)
  773. .where(func.lower(Printer.model) == normalized_model.lower())
  774. .where(Printer.is_active == True) # noqa: E712
  775. )
  776. # Add location filter if specified
  777. if target_location:
  778. query = query.where(Printer.location == target_location)
  779. result = await db.execute(query)
  780. printers = list(result.scalars().all())
  781. location_suffix = f" in {target_location}" if target_location else ""
  782. if not printers:
  783. return None, f"No active {normalized_model} printers{location_suffix} configured"
  784. # Separate force-matched overrides from preference-only overrides
  785. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  786. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  787. # Track reasons for skipping printers
  788. printers_busy = []
  789. printers_offline = []
  790. printers_missing_filament: list[tuple[str, list[str]]] = []
  791. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  792. for printer in printers:
  793. if printer.id in exclude_ids:
  794. # Printer is already claimed by another job in this scheduling run.
  795. # For force-color jobs, still check if the color would match — if not,
  796. # report it as a color mismatch rather than plain "Busy" so the user
  797. # knows the job needs a filament change, not just to wait for availability.
  798. if force_overrides and not pref_overrides:
  799. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  800. if missing_colors:
  801. printers_missing_filament.append((printer.name, missing_colors))
  802. continue
  803. printers_busy.append(printer.name)
  804. continue
  805. is_connected = printer_manager.is_connected(printer.id)
  806. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  807. if not is_connected:
  808. printers_offline.append(printer.name)
  809. continue
  810. if not is_idle:
  811. # Printer is currently printing. For force-color jobs, check whether the
  812. # loaded color would satisfy the requirement — if not, surface it as a
  813. # color-mismatch reason rather than plain "Busy" so the user understands
  814. # that the job is waiting for a filament change, not just printer availability.
  815. if force_overrides and not pref_overrides:
  816. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  817. if missing_colors:
  818. printers_missing_filament.append((printer.name, missing_colors))
  819. logger.debug(
  820. "Printer %s (%s) is busy but also has wrong force-color: %s",
  821. printer.id,
  822. printer.name,
  823. missing_colors,
  824. )
  825. continue
  826. printers_busy.append(printer.name)
  827. continue
  828. # Validate filament compatibility if required types are specified
  829. if required_filament_types:
  830. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  831. if missing:
  832. # When force_overrides are present, enrich missing entries with color info
  833. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  834. if force_overrides:
  835. force_color_map = {
  836. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  837. for o in force_overrides
  838. }
  839. missing_enriched = [
  840. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  841. for t in missing
  842. ]
  843. printers_missing_filament.append((printer.name, missing_enriched))
  844. else:
  845. printers_missing_filament.append((printer.name, missing))
  846. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  847. continue
  848. # Force color match: ALL flagged slots must have an exact type+color match
  849. if force_overrides:
  850. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  851. if missing_colors:
  852. printers_missing_filament.append((printer.name, missing_colors))
  853. logger.debug(
  854. "Skipping printer %s (%s) - missing force-matched colors: %s",
  855. printer.id,
  856. printer.name,
  857. missing_colors,
  858. )
  859. continue
  860. # If preference-only overrides exist, rank by color matches (existing behaviour)
  861. if pref_overrides:
  862. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  863. if color_matches > 0:
  864. candidates.append((printer.id, color_matches))
  865. else:
  866. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  867. printers_missing_filament.append((printer.name, override_colors))
  868. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  869. continue
  870. elif force_overrides:
  871. # Passed all force checks — immediately eligible (no preference ordering needed)
  872. return printer.id, None
  873. else:
  874. # No overrides at all - take first available (existing behavior)
  875. return printer.id, None
  876. # If we have candidates from preference override matching, pick the one with most color matches
  877. if candidates:
  878. candidates.sort(key=lambda c: c[1], reverse=True)
  879. return candidates[0][0], None
  880. # Build waiting reason from what we found
  881. reasons = []
  882. if printers_missing_filament:
  883. # Filament/color mismatch is most actionable - show first
  884. if force_overrides and not pref_overrides:
  885. # All mismatches are force-color failures — use descriptive message only;
  886. # but only if there are no busy printers that DO have the matching color.
  887. # If a printer has the right color but is busy, surface "Busy" instead so
  888. # the user knows the job will start automatically once that printer is free.
  889. if not printers_busy:
  890. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  891. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  892. # else: fall through — printers_busy will be appended below
  893. else:
  894. names_and_missing = [
  895. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  896. ]
  897. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  898. if printers_busy:
  899. reasons.append(f"Busy: {', '.join(printers_busy)}")
  900. if printers_offline:
  901. reasons.append(f"Offline: {', '.join(printers_offline)}")
  902. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  903. @staticmethod
  904. def _is_busy_only(waiting_reason: str) -> bool:
  905. """Check if the waiting reason only contains 'Busy' entries.
  906. When all matching printers are simply busy printing, the queued job
  907. will start automatically once a printer finishes — no user action
  908. is required, so we skip the notification.
  909. """
  910. parts = [p.strip() for p in waiting_reason.split(" | ")]
  911. return all(p.startswith("Busy:") for p in parts)
  912. def _get_missing_force_color_slots(self, printer_id: int, force_overrides: list[dict]) -> list[str]:
  913. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  914. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  915. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  916. with an exact type+color match.
  917. Returns:
  918. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  919. """
  920. status = printer_manager.get_status(printer_id)
  921. if not status:
  922. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  923. # Build set of loaded type+colour pairs from AMS and external spool
  924. loaded: set[tuple[str, str]] = set()
  925. for ams_unit in status.raw_data.get("ams", []):
  926. for tray in ams_unit.get("tray", []):
  927. tray_type = tray.get("tray_type")
  928. tray_color = tray.get("tray_color", "")
  929. if tray_type:
  930. color_norm = tray_color.replace("#", "").lower()[:6]
  931. loaded.add((_canonical_filament_type(tray_type), color_norm))
  932. for vt in status.raw_data.get("vt_tray") or []:
  933. vt_type = vt.get("tray_type")
  934. if vt_type:
  935. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  936. loaded.add((_canonical_filament_type(vt_type), color_norm))
  937. missing = []
  938. for o in force_overrides:
  939. o_type = _canonical_filament_type(o.get("type") or "")
  940. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  941. if (o_type, o_color) not in loaded:
  942. color_label = o.get("color_name") or o.get("color", "?")
  943. missing.append(f"{o_type} ({color_label})")
  944. return missing
  945. def _get_missing_filament_types(self, printer_id: int, required_types: list[str]) -> list[str]:
  946. """Get the list of required filament types that are not loaded on the printer.
  947. Args:
  948. printer_id: The printer ID
  949. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  950. Returns:
  951. List of missing filament types (empty if all are loaded)
  952. """
  953. status = printer_manager.get_status(printer_id)
  954. if not status:
  955. return required_types # Can't determine, assume all missing
  956. # Collect all filament types loaded on this printer (AMS units + external spool)
  957. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  958. loaded_types: set[str] = set()
  959. # Check AMS units (stored in raw_data["ams"])
  960. ams_data = status.raw_data.get("ams", [])
  961. if ams_data:
  962. for ams_unit in ams_data:
  963. for tray in ams_unit.get("tray", []):
  964. tray_type = tray.get("tray_type")
  965. if tray_type:
  966. loaded_types.add(_canonical_filament_type(tray_type))
  967. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  968. for vt in status.raw_data.get("vt_tray") or []:
  969. vt_type = vt.get("tray_type")
  970. if vt_type:
  971. loaded_types.add(_canonical_filament_type(vt_type))
  972. # Find which required types are missing (using canonical type for equivalence)
  973. missing = []
  974. for req_type in required_types:
  975. if _canonical_filament_type(req_type) not in loaded_types:
  976. missing.append(req_type)
  977. return missing
  978. def _count_override_color_matches(self, printer_id: int, overrides: list[dict]) -> int:
  979. """Count how many filament overrides have an exact color match on the printer.
  980. Used to prefer printers that already have the desired override colors loaded.
  981. """
  982. status = printer_manager.get_status(printer_id)
  983. if not status:
  984. return 0
  985. # Collect loaded filaments' type+color pairs
  986. loaded: set[tuple[str, str]] = set()
  987. for ams_unit in status.raw_data.get("ams", []):
  988. for tray in ams_unit.get("tray", []):
  989. tray_type = tray.get("tray_type")
  990. tray_color = tray.get("tray_color", "")
  991. if tray_type:
  992. color_norm = tray_color.replace("#", "").lower()[:6]
  993. loaded.add((tray_type.upper(), color_norm))
  994. for vt in status.raw_data.get("vt_tray") or []:
  995. vt_type = vt.get("tray_type")
  996. if vt_type:
  997. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  998. loaded.add((vt_type.upper(), color_norm))
  999. matches = 0
  1000. for o in overrides:
  1001. o_type = (o.get("type") or "").upper()
  1002. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  1003. if (o_type, o_color) in loaded:
  1004. matches += 1
  1005. return matches
  1006. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> None:
  1007. """Ensure the queue item carries a usable AMS mapping before dispatch.
  1008. Recomputes from live printer status when the stored mapping is missing OR
  1009. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  1010. frontend status-load race can serialize [-1] before the printer's AMS
  1011. trays are known (#2589) — and must not be trusted: downstream it would be
  1012. silently downgraded to external-spool mode and print against an empty
  1013. feed. A resolved mapping (including manual overrides, or a partially
  1014. padded one) is left untouched.
  1015. When recompute cannot resolve it either (no compatible tray loaded), the
  1016. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  1017. external selection; the print command then keeps use_ams=True and the
  1018. firmware surfaces a clear AMS-mapping error instead of silently printing
  1019. to the empty external feed.
  1020. """
  1021. stored_mapping: list | None = None
  1022. if item.ams_mapping:
  1023. try:
  1024. stored_mapping = json.loads(item.ams_mapping)
  1025. except (json.JSONDecodeError, TypeError):
  1026. stored_mapping = None
  1027. # Already resolved (present and not all-unresolved) — keep as-is so a
  1028. # user's manual mapping is never overwritten.
  1029. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  1030. return
  1031. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  1032. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  1033. item.ams_mapping = json.dumps(computed_mapping)
  1034. logger.info(
  1035. "Queue item %s: Computed AMS mapping for printer %s: %s",
  1036. item.id,
  1037. printer_id,
  1038. computed_mapping,
  1039. )
  1040. await db.commit()
  1041. elif _mapping_is_all_unresolved(stored_mapping):
  1042. logger.warning(
  1043. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  1044. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  1045. item.id,
  1046. stored_mapping,
  1047. printer_id,
  1048. )
  1049. item.ams_mapping = None
  1050. await db.commit()
  1051. async def _compute_ams_mapping_for_printer(
  1052. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  1053. ) -> list[int] | None:
  1054. """Compute AMS mapping for a printer based on filament requirements.
  1055. Called when a queue item has no ams_mapping set — either for model-based
  1056. items after printer assignment, or printer-specific items (e.g. from VP).
  1057. Args:
  1058. db: Database session
  1059. printer_id: The assigned printer ID
  1060. item: The queue item (contains archive_id or library_file_id)
  1061. Returns:
  1062. AMS mapping array or None if no mapping needed/possible
  1063. """
  1064. # Get printer status
  1065. status = printer_manager.get_status(printer_id)
  1066. if not status:
  1067. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  1068. return None
  1069. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  1070. # either extruder, so the per-nozzle hard filter below must NOT apply.
  1071. # Otherwise a print on one nozzle can't use a spool physically loaded in
  1072. # an AMS on the *other* nozzle, and the matcher falls through to a
  1073. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  1074. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  1075. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  1076. # Get filament requirements from source file
  1077. filament_reqs = await self._get_filament_requirements(db, item)
  1078. if not filament_reqs:
  1079. # When the 3MF can't be read but force-color overrides are present, build a
  1080. # direct mapping from the overrides so the printer uses the correct AMS slot.
  1081. if item.filament_overrides:
  1082. try:
  1083. overrides = json.loads(item.filament_overrides)
  1084. force_overrides = [o for o in overrides if o.get("force_color_match")]
  1085. if force_overrides:
  1086. logger.info(
  1087. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  1088. "force-color override(s)",
  1089. item.id,
  1090. len(force_overrides),
  1091. )
  1092. return self._build_override_direct_mapping(force_overrides, status)
  1093. except (json.JSONDecodeError, KeyError, TypeError) as e:
  1094. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  1095. logger.debug("No filament requirements found for queue item %s", item.id)
  1096. return None
  1097. # Apply filament overrides if present
  1098. if item.filament_overrides:
  1099. try:
  1100. overrides = json.loads(item.filament_overrides)
  1101. override_map = {o["slot_id"]: o for o in overrides}
  1102. for req in filament_reqs:
  1103. if req["slot_id"] in override_map:
  1104. override = override_map[req["slot_id"]]
  1105. req["type"] = override["type"]
  1106. req["color"] = override["color"]
  1107. # Clear tray_info_idx so matching uses type+color instead of
  1108. # the original 3MF's tray_info_idx (which would match the old filament)
  1109. req["tray_info_idx"] = ""
  1110. logger.debug(
  1111. "Queue item %s: Override slot %d -> %s %s",
  1112. item.id,
  1113. req["slot_id"],
  1114. override["type"],
  1115. override["color"],
  1116. )
  1117. except (json.JSONDecodeError, KeyError, TypeError) as e:
  1118. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  1119. # Build loaded filaments from printer status
  1120. loaded_filaments = self._build_loaded_filaments(status)
  1121. if not loaded_filaments:
  1122. logger.debug("No filaments loaded on printer %s", printer_id)
  1123. return None
  1124. # Check if user prefers lowest remaining filament when multiple spools match
  1125. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  1126. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  1127. # Without backup, the printer will not switch to a second spool when the
  1128. # picked one runs out — so sorting toward the lowest leaves the print
  1129. # at risk of running dry mid-job. None (unknown / A1 family) preserves
  1130. # today's behaviour intentionally.
  1131. if prefer_lowest and status.ams_filament_backup is False:
  1132. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  1133. prefer_lowest = False
  1134. # When the preference is on, surface Bambuddy's inventory-side
  1135. # remaining for each slot that's bound to a tracked spool, so the
  1136. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  1137. # entirely when the preference is off — no behaviour change for
  1138. # users who haven't opted in.
  1139. inventory_remain_overrides: dict[int, float] | None = None
  1140. if prefer_lowest:
  1141. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  1142. # Compute mapping: match required filaments to available slots
  1143. return self._match_filaments_to_slots(
  1144. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  1145. )
  1146. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  1147. """Build an AMS mapping directly from force-color overrides without a 3MF.
  1148. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  1149. slice_info is missing or unreadable) but ``force_color_match`` overrides
  1150. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  1151. treated as the filament requirement for that slot and matched against the
  1152. current AMS state of the printer.
  1153. Returns the same format as ``_match_filaments_to_slots``, or None when
  1154. the AMS has no loaded filaments.
  1155. """
  1156. loaded = self._build_loaded_filaments(status)
  1157. if not loaded:
  1158. return None
  1159. reqs = [
  1160. {
  1161. "slot_id": o["slot_id"],
  1162. "type": o.get("type", ""),
  1163. "color": o.get("color", ""),
  1164. "tray_info_idx": "",
  1165. }
  1166. for o in force_overrides
  1167. ]
  1168. return self._match_filaments_to_slots(reqs, loaded)
  1169. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  1170. """Resolve the queue item's source 3MF and parse the per-slot
  1171. filament requirements out of it. Thin DB-resolver wrapper around
  1172. ``filament_requirements.extract_filament_requirements`` so the VP
  1173. queue-mode write path (#1188) can reuse the same parser at upload
  1174. time.
  1175. """
  1176. from backend.app.services.filament_requirements import extract_filament_requirements
  1177. file_path: Path | None = None
  1178. if item.archive_id:
  1179. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1180. archive = result.scalar_one_or_none()
  1181. if archive:
  1182. file_path = settings.base_dir / archive.file_path
  1183. elif item.library_file_id:
  1184. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  1185. library_file = result.scalar_one_or_none()
  1186. if library_file:
  1187. lib_path = Path(library_file.file_path)
  1188. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  1189. if not file_path or not file_path.exists():
  1190. return None
  1191. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  1192. return filaments if filaments else None
  1193. def _build_loaded_filaments(self, status) -> list[dict]:
  1194. """Build list of loaded filaments from printer status.
  1195. Args:
  1196. status: PrinterState from printer_manager
  1197. Returns:
  1198. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  1199. """
  1200. filaments = []
  1201. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  1202. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  1203. # Parse AMS units from raw_data
  1204. ams_data = status.raw_data.get("ams", [])
  1205. for ams_unit in ams_data:
  1206. ams_id = int(ams_unit.get("id", 0))
  1207. trays = ams_unit.get("tray", [])
  1208. is_ht = len(trays) == 1 # AMS-HT has single tray
  1209. for tray in trays:
  1210. tray_type = tray.get("tray_type")
  1211. if tray_type:
  1212. tray_id = int(tray.get("id", 0))
  1213. tray_color = tray.get("tray_color", "")
  1214. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  1215. tray_info_idx = tray.get("tray_info_idx", "")
  1216. # Normalize color: remove alpha, add hash
  1217. color = self._normalize_color(tray_color)
  1218. # Calculate global tray ID
  1219. # AMS-HT units have IDs starting at 128 with a single tray
  1220. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  1221. filaments.append(
  1222. {
  1223. "type": tray_type,
  1224. "color": color,
  1225. "tray_info_idx": tray_info_idx,
  1226. "ams_id": ams_id,
  1227. "tray_id": tray_id,
  1228. "is_ht": is_ht,
  1229. "is_external": False,
  1230. "global_tray_id": global_tray_id,
  1231. "extruder_id": ams_extruder_map.get(str(ams_id)),
  1232. "remain": tray.get("remain", -1),
  1233. }
  1234. )
  1235. # Check external spool(s) (vt_tray is a list)
  1236. for idx, vt in enumerate(status.raw_data.get("vt_tray") or []):
  1237. if vt.get("tray_type"):
  1238. color = self._normalize_color(vt.get("tray_color", ""))
  1239. tray_id = int(vt.get("id", 254))
  1240. filaments.append(
  1241. {
  1242. "type": vt["tray_type"],
  1243. "color": color,
  1244. "tray_info_idx": vt.get("tray_info_idx", ""),
  1245. "ams_id": -1,
  1246. "tray_id": idx,
  1247. "is_ht": False,
  1248. "is_external": True,
  1249. "global_tray_id": tray_id,
  1250. "extruder_id": (255 - tray_id) if ams_extruder_map else None,
  1251. "remain": vt.get("remain", -1),
  1252. }
  1253. )
  1254. return filaments
  1255. def _normalize_color(self, color: str | None) -> str:
  1256. """Normalize color to #RRGGBB format."""
  1257. if not color:
  1258. return "#808080"
  1259. hex_color = color.replace("#", "")[:6]
  1260. return f"#{hex_color}"
  1261. def _normalize_color_for_compare(self, color: str | None) -> str:
  1262. """Normalize color for comparison (lowercase, no hash)."""
  1263. if not color:
  1264. return ""
  1265. return color.replace("#", "").lower()[:6]
  1266. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  1267. """Check if two colors are visually similar within a threshold."""
  1268. hex1 = self._normalize_color_for_compare(color1)
  1269. hex2 = self._normalize_color_for_compare(color2)
  1270. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  1271. return False
  1272. try:
  1273. r1 = int(hex1[0:2], 16)
  1274. g1 = int(hex1[2:4], 16)
  1275. b1 = int(hex1[4:6], 16)
  1276. r2 = int(hex2[0:2], 16)
  1277. g2 = int(hex2[2:4], 16)
  1278. b2 = int(hex2[4:6], 16)
  1279. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  1280. except ValueError:
  1281. return False
  1282. async def _build_inventory_remain_overrides(
  1283. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  1284. ) -> dict[int, float]:
  1285. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  1286. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  1287. The MQTT ``remain`` field on a tray is the printer firmware's
  1288. RFID-decremented value, which has two limitations the "Prefer Lowest
  1289. Remaining Filament" feature has been ignoring (#1508):
  1290. - it's only meaningful for Bambu RFID spools; everything else reports
  1291. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  1292. compare equal and the sort collapses to AMS-slot order — the user
  1293. who's curating inventory weights gets the lower-slot pick instead
  1294. of the lower-remaining pick;
  1295. - even when set, it's the *printer's* counter, not Bambuddy's
  1296. ``label_weight - weight_used`` (internal mode) or Spoolman's
  1297. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  1298. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  1299. When the user has bound a spool to a slot, their own inventory
  1300. tracking is authoritative; this helper surfaces that value so the
  1301. sort can prefer it. Slots without a binding are absent from the
  1302. returned map — the caller then falls back to MQTT ``remain`` for
  1303. those, preserving the pre-#1508 behaviour for un-tracked spools.
  1304. Returns an empty map on any failure (no inventory bindings, DB
  1305. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  1306. is a preference, not a guarantee.
  1307. """
  1308. if not loaded:
  1309. return {}
  1310. # External / virtual-tray slots are tracked separately from AMS — skip
  1311. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  1312. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  1313. # match is fiddly and out of scope for this fix).
  1314. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  1315. if not tracked_slots:
  1316. return {}
  1317. is_spoolman = await self._is_spoolman_mode(db)
  1318. overrides: dict[int, float] = {}
  1319. if is_spoolman:
  1320. result = await db.execute(
  1321. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  1322. )
  1323. assignments = list(result.scalars().all())
  1324. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  1325. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  1326. for ams_id, tray_id, gtid in tracked_slots:
  1327. spoolman_id = by_slot.get((ams_id, tray_id))
  1328. if spoolman_id is None:
  1329. continue
  1330. grams = await _spoolman_remaining_grams(spoolman_id)
  1331. if grams is not None:
  1332. overrides[gtid] = grams
  1333. return overrides
  1334. # Internal inventory mode (default). selectinload matches the pattern
  1335. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  1336. # plus an eager-loaded relationship rather than an explicit join, so
  1337. # the row-attribute shape is exactly what those routes already rely on.
  1338. result = await db.execute(
  1339. select(SpoolAssignment)
  1340. .options(selectinload(SpoolAssignment.spool))
  1341. .where(SpoolAssignment.printer_id == printer_id)
  1342. )
  1343. assignments = list(result.scalars().all())
  1344. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  1345. for ams_id, tray_id, gtid in tracked_slots:
  1346. spool = by_slot.get((ams_id, tray_id))
  1347. if spool is None:
  1348. continue
  1349. label = float(spool.label_weight or 0)
  1350. used = float(spool.weight_used or 0)
  1351. overrides[gtid] = max(0.0, label - used)
  1352. return overrides
  1353. @staticmethod
  1354. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  1355. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  1356. here to avoid making this module import-dependent on that private
  1357. helper's signature."""
  1358. try:
  1359. from backend.app.api.routes.settings import get_setting
  1360. v = await get_setting(db, "spoolman_enabled")
  1361. return bool(v) and v.lower() == "true"
  1362. except Exception:
  1363. return False
  1364. @staticmethod
  1365. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  1366. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  1367. Three bands, matched to the emission order in ``_build_loaded_filaments``
  1368. so a tied sort produces the same physical-position order the pre-#1508
  1369. stable sort did (preserves the regression-free baseline):
  1370. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  1371. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  1372. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  1373. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  1374. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  1375. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  1376. """
  1377. if ams_id is None or ams_id < 0:
  1378. return 10_000
  1379. if ams_id >= 128:
  1380. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  1381. return ams_id * 4 + (tray_id or 0)
  1382. @staticmethod
  1383. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  1384. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  1385. Two-tier ordering: inventory-tracked spools always sort BEFORE
  1386. non-tracked spools (the user has told us they care about these
  1387. specifically), then ascending by remaining within each tier, then
  1388. ascending by AMS slot position as the deterministic tie-breaker.
  1389. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  1390. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  1391. because the tier flag dominates — which is what lets us mix grams
  1392. (inventory) and percent (MQTT) without a unit conversion.
  1393. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  1394. spools the printer DOES know something about sort ahead of those
  1395. it knows nothing about — preserves pre-#1508 behaviour for the
  1396. no-inventory-binding case.
  1397. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  1398. external on ties, matching the legacy emission-order stable sort.
  1399. """
  1400. gtid = f.get("global_tray_id")
  1401. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  1402. if overrides and gtid in overrides:
  1403. return (0, overrides[gtid], slot_order)
  1404. remain = f.get("remain", -1)
  1405. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  1406. def _match_filaments_to_slots(
  1407. self,
  1408. required: list[dict],
  1409. loaded: list[dict],
  1410. prefer_lowest: bool = False,
  1411. inventory_remain_overrides: dict[int, float] | None = None,
  1412. fts_installed: bool = False,
  1413. ) -> list[int] | None:
  1414. """Match required filaments to loaded filaments and build AMS mapping.
  1415. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  1416. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  1417. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  1418. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  1419. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  1420. matching among those trays.
  1421. Args:
  1422. required: List of required filaments with slot_id, type, color, tray_info_idx
  1423. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  1424. Returns:
  1425. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  1426. """
  1427. if not required:
  1428. return None
  1429. # Track used trays to avoid duplicate assignment
  1430. used_tray_ids: set[int] = set()
  1431. comparisons = []
  1432. for req in required:
  1433. req_type = (req.get("type") or "").upper()
  1434. req_color = req.get("color", "")
  1435. req_tray_info_idx = req.get("tray_info_idx", "")
  1436. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  1437. idx_match = None
  1438. exact_match = None
  1439. similar_match = None
  1440. type_only_match = None
  1441. # Get available trays (not already used)
  1442. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  1443. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  1444. # Hard filter — cross-nozzle assignment causes print failures
  1445. # ("position of left hotend is abnormal"), so never fall back.
  1446. # Skipped when an FTS is installed: it routes any AMS slot to either
  1447. # extruder, so restricting to one nozzle would wrongly exclude the
  1448. # correct spool sitting in the other nozzle's AMS (#2186).
  1449. req_nozzle_id = req.get("nozzle_id")
  1450. if req_nozzle_id is not None and not fts_installed:
  1451. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  1452. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  1453. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  1454. # _prefer_lowest_sort_key for the full rationale.
  1455. if prefer_lowest:
  1456. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  1457. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  1458. # One line per filament req so a bug report can be diagnosed
  1459. # without enabling debug logging: shows what the matcher saw
  1460. # (req shape + sorted candidate trays with their remain values
  1461. # and any inventory override that was applied). Mirrored by
  1462. # the picked-match log at the bottom of the loop.
  1463. logger.info(
  1464. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  1465. req.get("slot_id"),
  1466. req_type,
  1467. req_color,
  1468. req_tray_info_idx,
  1469. req_nozzle_id,
  1470. [
  1471. {
  1472. "gtid": f.get("global_tray_id"),
  1473. "type": f.get("type"),
  1474. "color": f.get("color"),
  1475. "tii": f.get("tray_info_idx"),
  1476. "remain": f.get("remain"),
  1477. "inv_g": (
  1478. inventory_remain_overrides.get(f.get("global_tray_id"))
  1479. if inventory_remain_overrides
  1480. else None
  1481. ),
  1482. }
  1483. for f in available
  1484. ],
  1485. )
  1486. # Check if tray_info_idx is unique among available trays
  1487. if req_tray_info_idx:
  1488. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  1489. if len(idx_matches) == 1:
  1490. # Unique tray_info_idx - use it as definitive match
  1491. idx_match = idx_matches[0]
  1492. logger.debug(
  1493. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  1494. f"-> tray {idx_match['global_tray_id']}"
  1495. )
  1496. elif len(idx_matches) > 1:
  1497. # Multiple trays with same tray_info_idx - use color matching among them
  1498. logger.debug(
  1499. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  1500. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  1501. )
  1502. if prefer_lowest:
  1503. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  1504. # Use color matching within this subset
  1505. for f in idx_matches:
  1506. f_color = f.get("color", "")
  1507. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  1508. if not exact_match:
  1509. exact_match = f
  1510. elif self._colors_are_similar(f_color, req_color):
  1511. if not similar_match:
  1512. similar_match = f
  1513. elif not type_only_match:
  1514. type_only_match = f
  1515. # If no idx_match yet, do standard type/color matching on all available trays
  1516. if not idx_match and not exact_match and not similar_match and not type_only_match:
  1517. for f in available:
  1518. f_type = (f.get("type") or "").upper()
  1519. if _canonical_filament_type(f_type) != _canonical_filament_type(req_type):
  1520. continue
  1521. # Type matches - check color
  1522. f_color = f.get("color", "")
  1523. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  1524. if not exact_match:
  1525. exact_match = f
  1526. elif self._colors_are_similar(f_color, req_color):
  1527. if not similar_match:
  1528. similar_match = f
  1529. elif not type_only_match:
  1530. type_only_match = f
  1531. match = idx_match or exact_match or similar_match or type_only_match
  1532. if match:
  1533. used_tray_ids.add(match["global_tray_id"])
  1534. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  1535. else:
  1536. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  1537. if prefer_lowest:
  1538. # Pair with the "available (sorted)" log above so the reporter
  1539. # bundle shows BOTH what the matcher saw AND which match bucket
  1540. # won — fast triage when "Prefer Lowest Filament" picks the
  1541. # wrong slot (#1766).
  1542. if match:
  1543. bucket = (
  1544. "idx"
  1545. if idx_match is not None
  1546. else "exact_color"
  1547. if exact_match is not None
  1548. else "similar_color"
  1549. if similar_match is not None
  1550. else "type_only"
  1551. )
  1552. logger.info(
  1553. "[prefer-lowest] picked gtid=%s via %s for req slot=%s",
  1554. match["global_tray_id"],
  1555. bucket,
  1556. req.get("slot_id"),
  1557. )
  1558. else:
  1559. logger.info(
  1560. "[prefer-lowest] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  1561. req.get("slot_id"),
  1562. req_type,
  1563. req_color,
  1564. req_tray_info_idx,
  1565. )
  1566. # Build mapping array
  1567. if not comparisons:
  1568. return None
  1569. max_slot_id = max(c["slot_id"] for c in comparisons)
  1570. if max_slot_id <= 0:
  1571. return None
  1572. mapping = [-1] * max_slot_id
  1573. for c in comparisons:
  1574. slot_id = c["slot_id"]
  1575. if slot_id and slot_id > 0:
  1576. mapping[slot_id - 1] = c["global_tray_id"]
  1577. return mapping
  1578. def _mark_printer_dispatched(
  1579. self,
  1580. printer_id: int,
  1581. pre_state: str | None,
  1582. pre_subtask_id: str | None,
  1583. ) -> None:
  1584. """Record that a print command was just sent to ``printer_id``.
  1585. Held until either the watchdog observes a state/subtask transition
  1586. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  1587. """
  1588. if not pre_state:
  1589. # No pre_state means we can't detect a transition — fall back to a
  1590. # pure time-based hold using empty string as a sentinel that won't
  1591. # match any real printer state.
  1592. pre_state = ""
  1593. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  1594. def _release_dispatch_hold(self, printer_id: int) -> None:
  1595. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  1596. self._dispatch_holds.pop(printer_id, None)
  1597. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  1598. """True if ``printer_id`` is still inside its post-dispatch hold window.
  1599. Returns False (and clears the hold) once any of these are true:
  1600. - hard timeout (``_dispatch_max_hold``) has elapsed
  1601. - the printer has transitioned out of pre_state and we're past the
  1602. minimum cooldown
  1603. - the printer's subtask_id has advanced past pre_subtask_id and we're
  1604. past the minimum cooldown
  1605. Otherwise the printer is held — caller should treat it as busy.
  1606. """
  1607. entry = self._dispatch_holds.get(printer_id)
  1608. if not entry:
  1609. return False
  1610. started_at, pre_state, pre_subtask_id = entry
  1611. elapsed = time.monotonic() - started_at
  1612. if elapsed >= self._dispatch_max_hold:
  1613. self._dispatch_holds.pop(printer_id, None)
  1614. return False
  1615. # Without a pre_state we can't detect a transition — fall back to the
  1616. # min cooldown alone, then drop the hold.
  1617. if not pre_state:
  1618. if elapsed >= self._dispatch_min_cooldown:
  1619. self._dispatch_holds.pop(printer_id, None)
  1620. return False
  1621. return True
  1622. status = printer_manager.get_status(printer_id)
  1623. current_state = getattr(status, "state", None) if status else None
  1624. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  1625. transitioned = (current_state is not None and current_state != pre_state) or (
  1626. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  1627. )
  1628. if transitioned and elapsed >= self._dispatch_min_cooldown:
  1629. self._dispatch_holds.pop(printer_id, None)
  1630. return False
  1631. return True
  1632. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  1633. """Check if a printer is connected and idle."""
  1634. if not printer_manager.is_connected(printer_id):
  1635. logger.debug("Printer %d: not connected", printer_id)
  1636. return False
  1637. state = printer_manager.get_status(printer_id)
  1638. if not state:
  1639. logger.debug("Printer %d: no status available", printer_id)
  1640. return False
  1641. # Plate-clear gate: if the printer finished/failed a previous print and the user
  1642. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  1643. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  1644. # printer, it boots back into IDLE with no memory of the previous finish; without
  1645. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  1646. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  1647. logger.debug(
  1648. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  1649. printer_id,
  1650. state.state,
  1651. )
  1652. return False
  1653. idle = state.state in ("IDLE", "FINISH", "FAILED")
  1654. if not idle:
  1655. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  1656. return idle
  1657. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  1658. """Read a setting value from the database."""
  1659. result = await db.execute(select(Settings).where(Settings.key == key))
  1660. setting = result.scalar_one_or_none()
  1661. return setting.value if setting else None
  1662. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  1663. """Read a boolean setting from the database."""
  1664. result = await db.execute(select(Settings).where(Settings.key == key))
  1665. setting = result.scalar_one_or_none()
  1666. if setting:
  1667. return setting.value.lower() == "true"
  1668. return default
  1669. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  1670. """Read an int setting; falls back to default on missing/unparseable rows."""
  1671. result = await db.execute(select(Settings).where(Settings.key == key))
  1672. setting = result.scalar_one_or_none()
  1673. if setting and setting.value:
  1674. try:
  1675. return int(setting.value)
  1676. except ValueError:
  1677. pass
  1678. return default
  1679. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  1680. """Get drying presets (user-configured or built-in defaults)."""
  1681. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  1682. setting = result.scalar_one_or_none()
  1683. if setting and setting.value:
  1684. try:
  1685. presets = json.loads(setting.value)
  1686. if isinstance(presets, dict) and presets:
  1687. return presets
  1688. except json.JSONDecodeError:
  1689. pass
  1690. return self.DEFAULT_DRYING_PRESETS
  1691. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  1692. """Per-filament humidity thresholds (#1605).
  1693. Returns the user-configured overrides map keyed by normalized filament
  1694. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  1695. unknown / unmapped types. Empty / unset → empty dict, in which case
  1696. callers fall back to ``ams_humidity_fair``.
  1697. """
  1698. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  1699. setting = result.scalar_one_or_none()
  1700. if not setting or not setting.value:
  1701. return {}
  1702. try:
  1703. data = json.loads(setting.value)
  1704. except json.JSONDecodeError:
  1705. return {}
  1706. if not isinstance(data, dict):
  1707. return {}
  1708. out: dict[str, int] = {}
  1709. for key, value in data.items():
  1710. try:
  1711. out[str(key).upper() if key != "default" else "default"] = int(value)
  1712. except (TypeError, ValueError):
  1713. continue
  1714. return out
  1715. @staticmethod
  1716. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  1717. """Resolve the effective humidity threshold for an AMS unit (#1605).
  1718. For mixed filament types loaded into one AMS, returns the most
  1719. restrictive (lowest) threshold across all loaded tray types — matches
  1720. the conservative-params strategy already used for drying temp/hours.
  1721. Empty / unloaded trays contribute no constraint. Unknown types use the
  1722. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  1723. when no per-type map is configured at all.
  1724. """
  1725. default = thresholds.get("default", fallback)
  1726. if not thresholds:
  1727. return fallback
  1728. candidates: list[int] = []
  1729. for tray in trays:
  1730. tray_type = str(tray.get("tray_type") or "").strip()
  1731. if not tray_type:
  1732. continue
  1733. base_type = tray_type.split()[0].upper()
  1734. candidates.append(thresholds.get(base_type, default))
  1735. if not candidates:
  1736. return default
  1737. return min(candidates)
  1738. def _get_conservative_drying_params(
  1739. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  1740. ) -> tuple[int, int, str] | None:
  1741. """Get the most conservative drying params for mixed filament types in an AMS unit.
  1742. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  1743. """
  1744. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  1745. hours_key = f"{temp_key}_hours"
  1746. min_temp = None
  1747. max_hours = None
  1748. filament_type = ""
  1749. for tray in trays:
  1750. tray_type = tray.get("tray_type", "")
  1751. if not tray_type:
  1752. continue
  1753. # Normalize filament type for preset lookup (e.g., "PLA Basic" -> "PLA")
  1754. base_type = tray_type.split()[0].upper()
  1755. preset = presets.get(base_type)
  1756. if not preset:
  1757. continue
  1758. temp = preset.get(temp_key, 55)
  1759. hours = preset.get(hours_key, 12)
  1760. # Conservative: lowest temp, longest duration
  1761. if min_temp is None or temp < min_temp:
  1762. min_temp = temp
  1763. if max_hours is None or hours > max_hours:
  1764. max_hours = hours
  1765. if not filament_type:
  1766. filament_type = base_type
  1767. if min_temp is None:
  1768. return None
  1769. return (min_temp, max_hours or 12, filament_type)
  1770. async def _check_auto_drying(
  1771. self,
  1772. db: AsyncSession,
  1773. queue_items: list[PrintQueueItem],
  1774. busy_printers: set[int],
  1775. *,
  1776. require_plate_clear: bool = True,
  1777. ):
  1778. """Start drying on idle printers based on humidity.
  1779. Three modes (can all be enabled independently):
  1780. - queue_drying_enabled: Dry between scheduled queue prints
  1781. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  1782. - print_drying_enabled: Also evaluate printers that are currently printing,
  1783. when model+firmware supports "Print While Drying" (gated by
  1784. supports_drying_while_printing). Drying temperature is capped at
  1785. max(40, preset_temp - 5) to protect spools mid-print.
  1786. """
  1787. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  1788. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  1789. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  1790. if not queue_drying_enabled and not ambient_drying_enabled:
  1791. # Stop active drying on all printers if both features disabled
  1792. if self._drying_in_progress:
  1793. for pid in list(self._drying_in_progress):
  1794. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  1795. await self._stop_drying(pid)
  1796. return
  1797. # Update drying state from printer status (handles backend restart)
  1798. self._sync_drying_state()
  1799. # Find printers with scheduled items (for queue drying mode)
  1800. printers_with_scheduled: set[int] = set()
  1801. printers_with_items: set[int] = set()
  1802. for item in queue_items:
  1803. if item.printer_id:
  1804. printers_with_items.add(item.printer_id)
  1805. if item.scheduled_time and not item.manual_start:
  1806. printers_with_scheduled.add(item.printer_id)
  1807. # If only queue mode is on and no printers have scheduled items, stop drying
  1808. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  1809. # may still be eligible for mid-print drying regardless of queue state).
  1810. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  1811. for pid in list(self._drying_in_progress):
  1812. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  1813. await self._stop_drying(pid)
  1814. return
  1815. # Get humidity threshold (global fallback)
  1816. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  1817. setting = result.scalar_one_or_none()
  1818. global_humidity_threshold = int(setting.value) if setting else 60
  1819. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  1820. # to the global threshold for every AMS unit.
  1821. per_type_thresholds = await self._get_humidity_thresholds(db)
  1822. # Get drying presets
  1823. presets = await self._get_drying_presets(db)
  1824. # Determine if drying should be skipped for printers with pending items
  1825. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  1826. # Get all active printers
  1827. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1828. for printer in all_printers.scalars():
  1829. pid = printer.id
  1830. # Resolve model+firmware up front — needed to decide whether this printer
  1831. # qualifies for mid-print drying (busy printer on capable hardware).
  1832. state = printer_manager.get_status(pid)
  1833. if not state:
  1834. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  1835. continue
  1836. model = printer_manager.get_model(pid)
  1837. firmware = state.firmware_version
  1838. mid_print = (
  1839. pid in busy_printers and print_drying_enabled and supports_drying_while_printing(model, firmware)
  1840. )
  1841. if pid in busy_printers and not mid_print:
  1842. logger.debug("Auto-drying: printer %d skipped — busy", pid)
  1843. continue
  1844. if not mid_print:
  1845. # In queue-only mode, only dry printers that have scheduled prints
  1846. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  1847. if self._drying_in_progress.get(pid):
  1848. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  1849. await self._stop_drying(pid)
  1850. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  1851. continue
  1852. # When block mode is on, don't START new drying on printers with pending items.
  1853. # But allow already-drying printers through so humidity auto-stop logic still runs.
  1854. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  1855. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  1856. continue
  1857. if not printer_manager.is_connected(pid):
  1858. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  1859. continue
  1860. if not mid_print and not self._is_printer_idle(pid, require_plate_clear):
  1861. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  1862. continue
  1863. # Check drying capability. For mid-print path, supports_drying_while_printing
  1864. # was already verified when computing mid_print above.
  1865. if not mid_print and not supports_drying(model, firmware):
  1866. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  1867. continue
  1868. # Check each AMS unit from raw_data
  1869. ams_list = state.raw_data.get("ams", [])
  1870. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  1871. for ams_data in ams_list:
  1872. module_type = str(ams_data.get("module_type") or "")
  1873. ams_id = int(ams_data.get("id", 0))
  1874. # Only n3f/n3s support drying
  1875. if module_type not in ("n3f", "n3s"):
  1876. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  1877. continue
  1878. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  1879. # Most-restrictive of all loaded tray types; falls back to the
  1880. # global threshold when no overrides are configured.
  1881. trays = ams_data.get("tray", []) or []
  1882. humidity_threshold = self.resolve_humidity_threshold(
  1883. trays, per_type_thresholds, global_humidity_threshold
  1884. )
  1885. dry_time = int(ams_data.get("dry_time") or 0)
  1886. # Read humidity — prefer humidity_raw (actual %) over humidity (index 1-5)
  1887. humidity = None
  1888. h_raw = ams_data.get("humidity_raw")
  1889. if h_raw is not None:
  1890. try:
  1891. humidity = int(h_raw)
  1892. except (ValueError, TypeError):
  1893. pass
  1894. if humidity is None:
  1895. h_idx = ams_data.get("humidity")
  1896. if h_idx is not None:
  1897. try:
  1898. humidity = int(h_idx)
  1899. except (ValueError, TypeError):
  1900. pass
  1901. # Already drying — let it run to its configured duration (#1892).
  1902. #
  1903. # We deliberately do NOT stop drying from a humidity re-check here.
  1904. # Relative humidity drops steeply in heated air, so the AMS sensor
  1905. # reads ~15-20% within minutes of the dryer starting even while the
  1906. # filament is still saturated. A humidity-based early-stop therefore
  1907. # always fires at the minimum-time floor, truncating both user-started
  1908. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  1909. # The firmware stops when the configured duration elapses; scheduling
  1910. # stops (print takes priority, queue no longer needs drying) are
  1911. # handled separately via _stop_drying().
  1912. if dry_time > 0:
  1913. if pid not in self._drying_in_progress:
  1914. # Drying we didn't start (manual or from before restart) —
  1915. # track it so scheduling stops still apply; never auto-stop it.
  1916. self._drying_in_progress[pid] = time.monotonic()
  1917. logger.debug(
  1918. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  1919. pid,
  1920. ams_id,
  1921. dry_time,
  1922. humidity,
  1923. )
  1924. continue
  1925. # Humidity below threshold — no need to start drying
  1926. if humidity is None or humidity <= humidity_threshold:
  1927. logger.debug(
  1928. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  1929. pid,
  1930. ams_id,
  1931. humidity,
  1932. humidity_threshold,
  1933. )
  1934. continue
  1935. # Check cannot-dry reasons (power constraints etc.)
  1936. sf_reasons = ams_data.get("dry_sf_reason", [])
  1937. if sf_reasons:
  1938. logger.debug(
  1939. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  1940. pid,
  1941. ams_id,
  1942. sf_reasons,
  1943. )
  1944. continue
  1945. # Get conservative drying params for mixed filaments
  1946. params = self._get_conservative_drying_params(trays, module_type, presets)
  1947. if not params:
  1948. logger.debug(
  1949. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  1950. )
  1951. continue
  1952. temp, duration_hours, filament_type = params
  1953. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  1954. # "drying temperature must not exceed the filament's softening temperature"
  1955. # for Print While Drying). Floor at 40 degC — below that the dryer is
  1956. # ineffective and firmware will reject anyway.
  1957. if mid_print:
  1958. temp = max(40, temp - 5)
  1959. # Start drying
  1960. logger.info(
  1961. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  1962. "starting %s drying at %d°C for %dh%s",
  1963. pid,
  1964. ams_id,
  1965. humidity,
  1966. humidity_threshold,
  1967. filament_type,
  1968. temp,
  1969. duration_hours,
  1970. " (mid-print)" if mid_print else "",
  1971. )
  1972. success = printer_manager.send_drying_command(
  1973. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  1974. )
  1975. if success:
  1976. self._drying_in_progress[pid] = time.monotonic()
  1977. def _sync_drying_state(self):
  1978. """Sync in-memory drying state with actual printer status.
  1979. Handles backend restart — if a printer is drying but we don't know about it,
  1980. update our state. If we think it's drying but it's not, clear it.
  1981. """
  1982. to_remove = []
  1983. for pid in self._drying_in_progress:
  1984. state = printer_manager.get_status(pid)
  1985. if not state:
  1986. to_remove.append(pid)
  1987. continue
  1988. # Check if any AMS unit is still drying
  1989. ams_list = state.raw_data.get("ams", [])
  1990. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  1991. if not any_drying:
  1992. to_remove.append(pid)
  1993. for pid in to_remove:
  1994. self._drying_in_progress.pop(pid, None)
  1995. async def _stop_drying(self, printer_id: int):
  1996. """Stop all active drying on a printer (print takes priority)."""
  1997. state = printer_manager.get_status(printer_id)
  1998. if not state:
  1999. self._drying_in_progress.pop(printer_id, None)
  2000. return
  2001. ams_list = state.raw_data.get("ams", [])
  2002. for ams_data in ams_list:
  2003. dry_time = int(ams_data.get("dry_time") or 0)
  2004. if dry_time > 0:
  2005. ams_id = int(ams_data.get("id", 0))
  2006. logger.info(
  2007. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  2008. printer_id,
  2009. ams_id,
  2010. )
  2011. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  2012. self._drying_in_progress.pop(printer_id, None)
  2013. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  2014. """Get all smart plugs associated with a printer."""
  2015. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  2016. return list(result.scalars().all())
  2017. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  2018. # chamber-temperature recommendations BambuStudio ships for the matching
  2019. # filament profile; users can override via Settings → Workflow → Preheat
  2020. # card. "default" applies when a loaded tray's normalised type isn't in
  2021. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  2022. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  2023. "PLA": 0,
  2024. "PETG": 0,
  2025. "PETG-CF": 40,
  2026. "ABS": 45,
  2027. "ASA": 45,
  2028. "PA": 50,
  2029. "PA-CF": 55,
  2030. "PC": 50,
  2031. "PC-FR": 50,
  2032. "TPU": 0,
  2033. "PVA": 0,
  2034. "default": 0,
  2035. }
  2036. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  2037. """Parse the user-configured filament→chamber-target map, falling back
  2038. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  2039. are uppercased and the 'default' fallback is always present in the
  2040. returned dict so the resolution loop can index it unconditionally."""
  2041. raw = await self._get_setting(db, "preheat_filament_targets")
  2042. if not raw:
  2043. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  2044. try:
  2045. parsed = json.loads(raw)
  2046. if not isinstance(parsed, dict):
  2047. raise ValueError("not an object")
  2048. except (json.JSONDecodeError, ValueError) as exc:
  2049. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  2050. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  2051. # Coerce values to int; drop unparseable rows so a stray string
  2052. # doesn't crash the loop.
  2053. out: dict[str, int] = {}
  2054. for key, value in parsed.items():
  2055. try:
  2056. out[str(key).upper()] = int(value)
  2057. except (TypeError, ValueError):
  2058. continue
  2059. if "DEFAULT" not in out:
  2060. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  2061. return out
  2062. @staticmethod
  2063. def _normalize_filament_type(tray_type: str) -> str:
  2064. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  2065. existing drying-preset normalisation (split-at-space, upper-case) so
  2066. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  2067. "PA-CF" (no space to split on)."""
  2068. return tray_type.split()[0].upper() if tray_type else ""
  2069. def _derive_chamber_target(
  2070. self,
  2071. printer: Printer,
  2072. targets: dict[str, int],
  2073. ) -> int:
  2074. """Look up the chamber target for each loaded AMS tray and return the
  2075. max. Returns 0 when no AMS data is available (e.g. external-spool
  2076. prints) or when every loaded slot maps to 0 — the chamber phase then
  2077. short-circuits in the main loop.
  2078. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  2079. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  2080. less slots have empty `tray_type` and contribute nothing."""
  2081. state = printer_manager.get_status(printer.id)
  2082. if state is None:
  2083. return 0
  2084. ams_list = (state.raw_data or {}).get("ams") if state.raw_data else None
  2085. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  2086. if isinstance(ams_list, dict):
  2087. ams_list = ams_list.get("ams") or []
  2088. if not isinstance(ams_list, list):
  2089. return 0
  2090. best = 0
  2091. for ams in ams_list:
  2092. for tray in (ams.get("tray") or []) if isinstance(ams, dict) else []:
  2093. normalised = self._normalize_filament_type(tray.get("tray_type") or "")
  2094. if not normalised:
  2095. continue
  2096. target = targets.get(normalised, targets.get("DEFAULT", 0))
  2097. if target > best:
  2098. best = target
  2099. return best
  2100. async def _preheat_and_soak(
  2101. self,
  2102. db: AsyncSession,
  2103. item: PrintQueueItem,
  2104. printer: Printer,
  2105. archive: PrintArchive | None,
  2106. ) -> None:
  2107. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  2108. Resolution order:
  2109. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  2110. to the global `preheat_enabled` setting; 'on' forces the stage on
  2111. even if the global is off.
  2112. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  2113. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  2114. across loaded AMS slots; else 0 (skips chamber phase, keeps bed
  2115. phase + soak timer).
  2116. 3. Three hardware tiers branch the wait loop:
  2117. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  2118. send M141 to the resolved target, then wait for the chamber sensor
  2119. to reach it (or the max-wait timeout to elapse).
  2120. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  2121. no M141; the bed is the only heat source, so we wait for the chamber
  2122. sensor to rise via bed radiation OR fall through on timeout.
  2123. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  2124. temperature; the function just heats the bed and holds for the
  2125. configured soak duration.
  2126. The bed target comes from the archive's parsed metadata
  2127. (`bed_temperature`); if missing the preheat stage logs and returns
  2128. without dispatching anything, rather than guessing at a default that
  2129. might wreck filament setup.
  2130. Failures are logged but never re-raised — preheat is best-effort. A
  2131. printer that goes offline mid-soak, a refused gcode command, or a
  2132. missing temperature reading must not turn into a failed queue item; the
  2133. normal upload + start path runs immediately after this method returns.
  2134. """
  2135. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  2136. if override == "off":
  2137. return
  2138. if override == "inherit":
  2139. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  2140. if not enabled:
  2141. return
  2142. # override == "on" forces the stage on regardless of the global setting.
  2143. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  2144. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  2145. # Chamber target resolution:
  2146. # 1. Explicit per-item override beats everything (user knows best).
  2147. # 2. Otherwise derive from loaded AMS filament types via the per-
  2148. # filament target map. PLA-only print derives 0 → chamber phase
  2149. # auto-skips without the user touching anything.
  2150. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  2151. if explicit_target is not None and explicit_target > 0:
  2152. chamber_target = int(explicit_target)
  2153. chamber_source = "item-override"
  2154. elif explicit_target == 0:
  2155. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  2156. chamber_source = "item-override-zero"
  2157. else:
  2158. targets = await self._get_preheat_filament_targets(db)
  2159. chamber_target = self._derive_chamber_target(printer, targets)
  2160. chamber_source = "filament-map"
  2161. bed_target = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  2162. if bed_target <= 0:
  2163. logger.info(
  2164. "Queue item %s: preheat skipped — archive has no bed_temperature metadata",
  2165. item.id,
  2166. )
  2167. return
  2168. client = printer_manager.get_client(printer.id)
  2169. if client is None:
  2170. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  2171. return
  2172. model = printer.model or ""
  2173. has_heater = supports_chamber_heater(model)
  2174. has_sensor = supports_chamber_temp(model)
  2175. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  2176. logger.info(
  2177. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  2178. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  2179. item.id,
  2180. bed_target,
  2181. chamber_target if do_chamber else 0,
  2182. chamber_source,
  2183. override,
  2184. model,
  2185. has_heater,
  2186. has_sensor,
  2187. max_wait,
  2188. soak_seconds,
  2189. )
  2190. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  2191. # cache the target locally so the polling reads below see consistent
  2192. # state (firmware MQTT echoes lag by ~1s).
  2193. try:
  2194. client.set_bed_temperature(bed_target)
  2195. except Exception as exc:
  2196. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  2197. return
  2198. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  2199. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  2200. # left it on, regardless of M141. Default cooling actively vents the
  2201. # chamber, so a `chamber_target > 0` print with the flap stuck in
  2202. # cooling never converges — the heater fights the open exhaust. We
  2203. # flip the flap BEFORE M141 to "heating" when the preheat wants
  2204. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  2205. # on an H2D that was previously running ABS would otherwise stay in
  2206. # heating mode and overheat PLA). The current-state read keeps the
  2207. # command idempotent — no MQTT chatter when the flap is already where
  2208. # we want it.
  2209. if supports_airduct(model):
  2210. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  2211. desired_id = 1 if desired_airduct == "heating" else 0
  2212. current_state = printer_manager.get_status(printer.id)
  2213. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  2214. if current_airduct != desired_id:
  2215. try:
  2216. client.set_airduct_mode(desired_airduct)
  2217. except Exception as exc:
  2218. logger.warning(
  2219. "Queue item %s: preheat airduct %s mode failed: %s",
  2220. item.id,
  2221. desired_airduct,
  2222. exc,
  2223. )
  2224. if do_chamber and has_heater:
  2225. try:
  2226. client.set_chamber_temperature(chamber_target)
  2227. except Exception as exc:
  2228. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  2229. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  2230. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  2231. # Poll every 3s — frequent enough for responsive logging without
  2232. # spamming the MQTT state stream. The "converged" predicate is:
  2233. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  2234. # AND
  2235. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  2236. BED_TOLERANCE = 2.0
  2237. CHAMBER_TOLERANCE = 2.0
  2238. POLL_INTERVAL = 3.0
  2239. deadline = asyncio.get_event_loop().time() + max_wait
  2240. while True:
  2241. state = printer_manager.get_status(printer.id)
  2242. if state is None:
  2243. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  2244. break
  2245. temps = state.temperatures or {}
  2246. bed_now = float(temps.get("bed", 0) or 0)
  2247. chamber_now = float(temps.get("chamber", 0) or 0)
  2248. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  2249. if not do_chamber:
  2250. chamber_ok = True # phase disabled or model has neither sensor nor heater
  2251. elif not has_sensor:
  2252. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  2253. else:
  2254. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  2255. if bed_ok and chamber_ok:
  2256. logger.info(
  2257. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  2258. item.id,
  2259. bed_now,
  2260. chamber_now,
  2261. )
  2262. break
  2263. if asyncio.get_event_loop().time() >= deadline:
  2264. logger.info(
  2265. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  2266. item.id,
  2267. bed_now,
  2268. bed_target,
  2269. chamber_now,
  2270. chamber_target if do_chamber else 0,
  2271. )
  2272. break
  2273. await asyncio.sleep(POLL_INTERVAL)
  2274. if soak_seconds > 0:
  2275. logger.info("Queue item %s: preheat soak — holding for %ds", item.id, soak_seconds)
  2276. await asyncio.sleep(soak_seconds)
  2277. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  2278. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  2279. """Turn on smart plug and wait for printer to connect.
  2280. Returns True if printer connected successfully within timeout.
  2281. """
  2282. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  2283. service = await smart_plug_manager.get_service_for_plug(plug, db)
  2284. # Check current plug state
  2285. status = await service.get_status(plug)
  2286. if not status.get("reachable"):
  2287. logger.warning("Smart plug '%s' is not reachable", plug.name)
  2288. return False
  2289. # Turn on if not already on
  2290. if status.get("state") != "ON":
  2291. success = await service.turn_on(plug)
  2292. if not success:
  2293. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  2294. return False
  2295. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  2296. # Get printer from database for connection
  2297. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2298. printer = result.scalar_one_or_none()
  2299. if not printer:
  2300. logger.error("Printer %s not found in database", printer_id)
  2301. return False
  2302. # Wait for printer to boot (give it some time before trying to connect)
  2303. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  2304. await asyncio.sleep(30)
  2305. # Try to connect to the printer periodically
  2306. elapsed = 30 # Already waited 30s
  2307. while elapsed < self._power_on_wait_time:
  2308. # Try to connect
  2309. logger.info("Attempting to connect to printer %s...", printer_id)
  2310. try:
  2311. connected = await printer_manager.connect_printer(printer)
  2312. if connected:
  2313. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  2314. # Give it a moment to stabilize and get status
  2315. await asyncio.sleep(5)
  2316. return True
  2317. except Exception as e:
  2318. logger.debug("Connection attempt failed: %s", e)
  2319. await asyncio.sleep(self._power_on_check_interval)
  2320. elapsed += self._power_on_check_interval
  2321. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  2322. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  2323. return False
  2324. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  2325. """Check if the previous print on this printer succeeded.
  2326. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  2327. deliberate action, not a failure, so subsequent items should still
  2328. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  2329. a skip isn't an actual print attempt, so it must not gate downstream
  2330. items — counting it as a failed predecessor was the cascade bug that
  2331. let a single cancellation block 18 items over 3 days for the reporter.
  2332. Only `failed` and `aborted` — real print-attempt failures — block.
  2333. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  2334. action — #1818) are also excluded from the lookback so the user can
  2335. clear the gate after fixing the physical issue without having to
  2336. re-queue every downstream job.
  2337. """
  2338. result = await db.execute(
  2339. select(PrintQueueItem)
  2340. .where(PrintQueueItem.printer_id == item.printer_id)
  2341. .where(PrintQueueItem.id != item.id)
  2342. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  2343. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  2344. .order_by(PrintQueueItem.completed_at.desc())
  2345. .limit(1)
  2346. )
  2347. prev_item = result.scalar_one_or_none()
  2348. # If no previous item, assume success (first in queue)
  2349. if not prev_item:
  2350. return True
  2351. return prev_item.status in ("completed", "cancelled")
  2352. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  2353. """Schedule power-off if the queue item enabled auto_off_after.
  2354. Delegates to the smart-plug manager so the off honours each plug's
  2355. configured strategy (time delay or temperature threshold), is cancelled
  2356. if the printer starts printing again, and never cuts power on a loaded
  2357. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  2358. powered off on the timeout regardless of print state.
  2359. """
  2360. if not item.auto_off_after:
  2361. return
  2362. try:
  2363. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  2364. except Exception as e:
  2365. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  2366. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  2367. """Get a human-readable name for a queue item."""
  2368. if item.archive_id:
  2369. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  2370. archive = result.scalar_one_or_none()
  2371. if archive:
  2372. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  2373. if item.library_file_id:
  2374. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  2375. library_file = result.scalar_one_or_none()
  2376. if library_file:
  2377. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  2378. return f"Job #{item.id}"
  2379. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  2380. """Get printer by ID."""
  2381. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2382. return result.scalar_one_or_none()
  2383. async def _notify_dispatch_gave_up(
  2384. self,
  2385. queue_item_id: int,
  2386. printer_id: int,
  2387. created_by_id: int | None,
  2388. ) -> None:
  2389. """Tell the user the queue item was failed after exhausting its dispatch retries.
  2390. Called from the watchdog, which is a background task with no session of
  2391. its own — hence the fresh one here. Best-effort throughout: the row is
  2392. already marked failed and that is the load-bearing part; a notification
  2393. provider being down must not resurrect the retry loop we just stopped.
  2394. """
  2395. try:
  2396. async with async_session() as db:
  2397. item = await db.get(PrintQueueItem, queue_item_id)
  2398. if not item:
  2399. return
  2400. job_name = await self._get_job_name(db, item)
  2401. printer = await self._get_printer(db, printer_id)
  2402. await notification_service.on_queue_job_failed(
  2403. job_name=job_name,
  2404. printer_id=printer_id,
  2405. printer_name=printer.name if printer else "Unknown",
  2406. reason="Printer accepted the file but never started printing",
  2407. db=db,
  2408. )
  2409. except Exception as e:
  2410. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  2411. try:
  2412. await ws_manager.send_queue_item_failed(
  2413. user_id=created_by_id,
  2414. queue_item_id=queue_item_id,
  2415. printer_id=printer_id,
  2416. reason="never_started",
  2417. )
  2418. except Exception:
  2419. pass # toast is best-effort
  2420. async def _block_on_filament_deficit(
  2421. self,
  2422. db: AsyncSession,
  2423. item: PrintQueueItem,
  2424. ) -> bool:
  2425. """Promote the item to manual_start when the assigned spool is short (#1496).
  2426. Returns True when this dispatch attempt was blocked, False when the
  2427. item is clear to start. A previously-flagged item whose spool has
  2428. since been swapped to one with enough material clears the flag here
  2429. so the next scheduler tick dispatches it.
  2430. """
  2431. # User has explicitly acknowledged the deficit ("Print Anyway") —
  2432. # don't re-flag, don't even compute. Without this short-circuit the
  2433. # scheduler bounces between "user said anyway" (route clears
  2434. # manual_start) and "scheduler re-blocked" (this method re-flags it
  2435. # on identical spool state) (#1698-followup).
  2436. if item.skip_filament_check:
  2437. # #1762 diagnostic: surface the short-circuit at INFO so a
  2438. # future "Print Anyway didn't work" report (e.g. issue #1762
  2439. # comment 3) has actionable evidence in the support bundle
  2440. # without needing DEBUG enabled.
  2441. logger.info(
  2442. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  2443. item.id,
  2444. )
  2445. return False
  2446. try:
  2447. deficit = await compute_deficit_for_queue_item(db, item)
  2448. except Exception as e:
  2449. # Never let a flaky deficit check wedge the queue — log and let
  2450. # dispatch proceed. The PrintModal-side check still runs on the
  2451. # manual paths.
  2452. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  2453. return False
  2454. if deficit:
  2455. item.filament_short = True
  2456. item.manual_start = True
  2457. await db.commit()
  2458. job_name = await self._get_job_name(db, item)
  2459. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  2460. logger.info(
  2461. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  2462. item.id,
  2463. len(deficit),
  2464. )
  2465. try:
  2466. await notification_service.on_queue_job_waiting(
  2467. job_name=job_name,
  2468. target_model=(printer.model if printer else "") or "",
  2469. waiting_reason="filament_short",
  2470. db=db,
  2471. )
  2472. except Exception as e:
  2473. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  2474. return True
  2475. # No deficit — clear any stale flag from a previous tick.
  2476. if item.filament_short:
  2477. item.filament_short = False
  2478. await db.commit()
  2479. return False
  2480. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  2481. """Hand the queue item's owner to printer_manager so the
  2482. print-complete callback can credit the user in PrintLogEntry (#1670).
  2483. No-ops when the item has no `created_by_id` or the referenced user
  2484. row is missing (e.g. user deleted between queue-add and dispatch —
  2485. in that case the print log row falls back to the existing un-credited
  2486. behaviour rather than crashing the dispatch).
  2487. """
  2488. if not item.created_by_id:
  2489. return
  2490. from backend.app.models.user import User
  2491. owner = await db.get(User, item.created_by_id)
  2492. if owner:
  2493. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username)
  2494. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  2495. """Upload file and start print for a queue item.
  2496. Supports two sources:
  2497. - archive_id: Print from an existing archive
  2498. - library_file_id: Print from a library file (file manager)
  2499. """
  2500. logger.info("Starting queue item %s", item.id)
  2501. # Get printer first (needed for both paths)
  2502. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  2503. printer = result.scalar_one_or_none()
  2504. if not printer:
  2505. item.status = "failed"
  2506. item.error_message = "Printer not found"
  2507. item.completed_at = datetime.now(timezone.utc)
  2508. await db.commit()
  2509. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  2510. await self._power_off_if_needed(db, item)
  2511. return
  2512. # Check printer is connected
  2513. if not printer_manager.is_connected(item.printer_id):
  2514. item.status = "failed"
  2515. item.error_message = "Printer not connected"
  2516. item.completed_at = datetime.now(timezone.utc)
  2517. await db.commit()
  2518. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  2519. await self._power_off_if_needed(db, item)
  2520. return
  2521. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  2522. # `items` was taken at the top of check_queue, but the user can /cancel
  2523. # any pending row in the gap before we reach this point. Re-read the
  2524. # row and bail out cleanly instead of starting an FTP upload for a row
  2525. # that's already cancelled. The atomic CAS at the pending→printing
  2526. # transition (below, before start_print) is the load-bearing guard;
  2527. # this is the early-exit optimisation that avoids wasted FTP I/O.
  2528. await db.refresh(item)
  2529. if item.status != "pending":
  2530. logger.info(
  2531. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  2532. item.id,
  2533. item.status,
  2534. )
  2535. return
  2536. # Determine source: archive or library file
  2537. archive = None
  2538. library_file = None
  2539. file_path = None
  2540. filename = None
  2541. cleanup_disk_paths: list[Path] = []
  2542. if item.archive_id:
  2543. # Print from archive
  2544. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  2545. archive = result.scalar_one_or_none()
  2546. if not archive:
  2547. item.status = "failed"
  2548. item.error_message = "Archive not found"
  2549. item.completed_at = datetime.now(timezone.utc)
  2550. await db.commit()
  2551. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  2552. await self._power_off_if_needed(db, item)
  2553. return
  2554. file_path = settings.base_dir / archive.file_path
  2555. filename = archive.filename
  2556. elif item.library_file_id:
  2557. # Print from library file (file manager)
  2558. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  2559. library_file = result.scalar_one_or_none()
  2560. if not library_file:
  2561. item.status = "failed"
  2562. item.error_message = "Library file not found"
  2563. item.completed_at = datetime.now(timezone.utc)
  2564. await db.commit()
  2565. logger.error("Queue item %s: Library file %s not found", item.id, item.library_file_id)
  2566. await self._power_off_if_needed(db, item)
  2567. return
  2568. # Library files store absolute paths
  2569. lib_path = Path(library_file.file_path)
  2570. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  2571. filename = library_file.filename
  2572. # Create archive from library file so usage tracking has access to the 3MF
  2573. queue_item_id = item.id
  2574. try:
  2575. from backend.app.services.archive import ArchiveService
  2576. archive_service = ArchiveService(db)
  2577. archive = await archive_service.archive_print(
  2578. printer_id=item.printer_id,
  2579. source_file=file_path,
  2580. original_filename=filename,
  2581. created_by_id=item.created_by_id,
  2582. project_id=item.project_id,
  2583. )
  2584. if archive:
  2585. item.archive_id = archive.id
  2586. if item.cleanup_library_after_dispatch and not library_file.is_external:
  2587. item.library_file_id = None
  2588. cleanup_disk_paths.append(file_path)
  2589. if library_file.thumbnail_path:
  2590. thumb_path = Path(library_file.thumbnail_path)
  2591. if not thumb_path.is_absolute():
  2592. thumb_path = settings.base_dir / library_file.thumbnail_path
  2593. cleanup_disk_paths.append(thumb_path)
  2594. await db.delete(library_file)
  2595. file_path = settings.base_dir / archive.file_path
  2596. filename = archive.filename
  2597. # Commit, not flush — flush opens the SQLite write
  2598. # transaction (item.archive_id update + library_file
  2599. # delete) and would hold the WAL writer lock through the
  2600. # FTP upload below, causing "database is locked" cascades
  2601. # for sensor history + concurrent cancels (#1853).
  2602. await db.commit()
  2603. logger.info(
  2604. "Queue item %s: Created archive %s from library file %s",
  2605. item.id,
  2606. archive.id,
  2607. item.library_file_id,
  2608. )
  2609. except Exception as e:
  2610. logger.warning(
  2611. "Queue item %s: Failed to create archive from library file: %s",
  2612. queue_item_id,
  2613. e,
  2614. exc_info=True,
  2615. )
  2616. await db.rollback()
  2617. item = await db.get(PrintQueueItem, queue_item_id)
  2618. if item:
  2619. item.status = "failed"
  2620. item.error_message = "Failed to create archive from library file"
  2621. item.completed_at = datetime.now(timezone.utc)
  2622. await db.commit()
  2623. await self._power_off_if_needed(db, item)
  2624. return
  2625. if not archive:
  2626. item.status = "failed"
  2627. item.error_message = "Failed to create archive from library file"
  2628. item.completed_at = datetime.now(timezone.utc)
  2629. await db.commit()
  2630. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  2631. await self._power_off_if_needed(db, item)
  2632. return
  2633. else:
  2634. # Neither archive nor library file specified
  2635. item.status = "failed"
  2636. item.error_message = "No source file specified"
  2637. item.completed_at = datetime.now(timezone.utc)
  2638. await db.commit()
  2639. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  2640. await self._power_off_if_needed(db, item)
  2641. return
  2642. # Check file exists on disk
  2643. if not file_path.exists():
  2644. item.status = "failed"
  2645. item.error_message = "Source file not found on disk"
  2646. item.completed_at = datetime.now(timezone.utc)
  2647. await db.commit()
  2648. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  2649. await self._power_off_if_needed(db, item)
  2650. return
  2651. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  2652. # size dispatched to a printer with a different nozzle installed is
  2653. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  2654. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  2655. # gives the user no idea what went wrong. Catch it here, before we spend
  2656. # time preheating and uploading, and fail with an actionable message.
  2657. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  2658. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  2659. # the printer hasn't reported its nozzles yet, we fall through and let the
  2660. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  2661. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  2662. # as one of the two hotends is a 0.6.
  2663. sliced_nozzle = archive.nozzle_diameter if archive else None
  2664. if sliced_nozzle:
  2665. installed = _installed_nozzle_diameters(printer_manager.get_status(item.printer_id))
  2666. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed)
  2667. if mismatch_msg:
  2668. item.status = "failed"
  2669. item.error_message = mismatch_msg
  2670. item.completed_at = datetime.now(timezone.utc)
  2671. await db.commit()
  2672. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  2673. await notification_service.on_queue_job_failed(
  2674. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  2675. printer_id=printer.id,
  2676. printer_name=printer.name,
  2677. reason=mismatch_msg,
  2678. db=db,
  2679. )
  2680. try:
  2681. await ws_manager.send_queue_item_failed(
  2682. user_id=item.created_by_id,
  2683. queue_item_id=item.id,
  2684. printer_id=item.printer_id,
  2685. reason="nozzle_mismatch",
  2686. )
  2687. except Exception:
  2688. pass
  2689. await self._power_off_if_needed(db, item)
  2690. return
  2691. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  2692. # bed (and chamber, if applicable) is at temperature when the firmware
  2693. # starts the actual print routine. Best-effort: any failure logs and
  2694. # falls through to the normal upload+start path rather than turning a
  2695. # configuration issue into a failed queue item.
  2696. await self._preheat_and_soak(db, item, printer, archive)
  2697. # G-code injection for auto-print systems (#422)
  2698. injected_path = None
  2699. if item.gcode_injection:
  2700. try:
  2701. snippets_raw = await self._get_setting(db, "gcode_snippets")
  2702. if snippets_raw:
  2703. snippets = json.loads(snippets_raw)
  2704. model_snippets = snippets.get(printer.model, {})
  2705. start_gc = (model_snippets.get("start_gcode") or "").strip()
  2706. end_gc = (model_snippets.get("end_gcode") or "").strip()
  2707. if start_gc or end_gc:
  2708. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  2709. injected_path = inject_gcode_into_3mf(
  2710. file_path, item.plate_id or 1, start_gc or None, end_gc or None
  2711. )
  2712. if injected_path:
  2713. file_path = injected_path
  2714. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  2715. else:
  2716. logger.warning(
  2717. "Queue item %s: G-code injection returned no result, using original", item.id
  2718. )
  2719. except Exception as e:
  2720. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  2721. # Upload to root directory (not /cache/) - the start_print command references
  2722. # files by name only (ftp://{filename}), so they must be in the root
  2723. remote_filename = derive_remote_filename(filename)
  2724. remote_path = f"/{remote_filename}"
  2725. # Get FTP retry settings
  2726. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  2727. logger.info(
  2728. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  2729. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  2730. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  2731. )
  2732. # Delete existing file if present (avoids 553 error on overwrite)
  2733. try:
  2734. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  2735. delete_result = await delete_file_async(
  2736. printer.ip_address,
  2737. printer.access_code,
  2738. remote_path,
  2739. socket_timeout=ftp_timeout,
  2740. printer_model=printer.model,
  2741. )
  2742. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  2743. except Exception as e:
  2744. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  2745. # Dispatch toast — announce the upload start with the total byte
  2746. # count so the frontend can render an honest progress bar.
  2747. toast_uid = item.created_by_id
  2748. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  2749. try:
  2750. total_bytes = file_path.stat().st_size
  2751. except OSError:
  2752. total_bytes = 0
  2753. try:
  2754. await ws_manager.send_queue_item_uploading(
  2755. user_id=toast_uid,
  2756. queue_item_id=item.id,
  2757. printer_id=item.printer_id,
  2758. printer_name=printer.name,
  2759. file_name=toast_file_name,
  2760. total_bytes=total_bytes,
  2761. )
  2762. except Exception:
  2763. pass # toast is best-effort
  2764. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  2765. # A deadline expiry gets its own message: "check your SD card" is the
  2766. # wrong advice for a link that was simply too slow to finish (#2529).
  2767. upload_error: str | None = None
  2768. try:
  2769. if ftp_retry_enabled:
  2770. uploaded = await with_ftp_retry(
  2771. upload_file_async,
  2772. printer.ip_address,
  2773. printer.access_code,
  2774. file_path,
  2775. remote_path,
  2776. socket_timeout=ftp_timeout,
  2777. printer_model=printer.model,
  2778. progress_callback=progress_bridge,
  2779. max_retries=ftp_retry_count,
  2780. retry_delay=ftp_retry_delay,
  2781. operation_name=f"Upload print to {printer.name}",
  2782. )
  2783. else:
  2784. uploaded = await upload_file_async(
  2785. printer.ip_address,
  2786. printer.access_code,
  2787. file_path,
  2788. remote_path,
  2789. socket_timeout=ftp_timeout,
  2790. printer_model=printer.model,
  2791. progress_callback=progress_bridge,
  2792. )
  2793. except UploadCancelled as e:
  2794. uploaded = False
  2795. upload_error = (
  2796. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  2797. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  2798. )
  2799. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  2800. except Exception as e:
  2801. uploaded = False
  2802. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  2803. # Clean up injected temp file after upload attempt
  2804. if injected_path and injected_path.exists():
  2805. injected_path.unlink(missing_ok=True)
  2806. if not uploaded:
  2807. error_msg = upload_error or (
  2808. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  2809. "See server logs for detailed diagnostics."
  2810. )
  2811. item.status = "failed"
  2812. item.error_message = error_msg
  2813. item.completed_at = datetime.now(timezone.utc)
  2814. await db.commit()
  2815. logger.error(
  2816. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  2817. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  2818. )
  2819. # Send failure notification
  2820. await notification_service.on_queue_job_failed(
  2821. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  2822. printer_id=printer.id,
  2823. printer_name=printer.name,
  2824. reason="Failed to upload file to printer",
  2825. db=db,
  2826. )
  2827. try:
  2828. await ws_manager.send_queue_item_failed(
  2829. user_id=toast_uid,
  2830. queue_item_id=item.id,
  2831. printer_id=item.printer_id,
  2832. reason="upload_failed",
  2833. )
  2834. except Exception:
  2835. pass
  2836. await self._power_off_if_needed(db, item)
  2837. return
  2838. # Parse AMS mapping if stored
  2839. ams_mapping = None
  2840. if item.ams_mapping:
  2841. try:
  2842. ams_mapping = json.loads(item.ams_mapping)
  2843. except json.JSONDecodeError:
  2844. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  2845. # Register as expected print so we don't create a duplicate archive
  2846. # Only applicable for archive-based prints
  2847. if archive:
  2848. from backend.app.main import register_expected_print
  2849. register_expected_print(
  2850. item.printer_id,
  2851. remote_filename,
  2852. archive.id,
  2853. ams_mapping=ams_mapping,
  2854. created_by_id=item.created_by_id,
  2855. plate_id=item.plate_id,
  2856. )
  2857. # Propagate the queue item's owner into printer_manager so the
  2858. # print-complete callback can credit the user in the PrintLogEntry
  2859. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  2860. # items) or when the user clicks the manual-start button.
  2861. await self._propagate_owner_to_printer_manager(db, item)
  2862. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  2863. # This prevents phantom reprints if the backend crashes/restarts after the
  2864. # print command is sent but before the status update is committed.
  2865. # If we crash after this commit but before start_print(), the item will be
  2866. # in "printing" status without actually printing - but that's safer than
  2867. # accidentally reprinting the same file hours later.
  2868. #
  2869. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  2870. # initial pending read at the top of check_queue and this point) flips
  2871. # the row to "cancelled" in a separate session. Without the WHERE
  2872. # status='pending' clause, the unconditional update here would silently
  2873. # overwrite that cancellation and we'd ship the MQTT start_print below
  2874. # — printer obeys, user sees "I pressed cancel and the print started".
  2875. # rowcount==0 means the user won the race; bail out, best-effort delete
  2876. # the file we just uploaded, do NOT send start_print.
  2877. now_utc = datetime.now(timezone.utc)
  2878. cas = await db.execute(
  2879. update(PrintQueueItem)
  2880. .where(PrintQueueItem.id == item.id)
  2881. .where(PrintQueueItem.status == "pending")
  2882. .values(status="printing", started_at=now_utc)
  2883. )
  2884. await db.commit()
  2885. if cas.rowcount == 0:
  2886. logger.info(
  2887. "Queue item %s no longer pending at print-command time "
  2888. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  2889. item.id,
  2890. )
  2891. try:
  2892. await delete_file_async(
  2893. printer.ip_address,
  2894. printer.access_code,
  2895. remote_path,
  2896. socket_timeout=ftp_timeout,
  2897. printer_model=printer.model,
  2898. )
  2899. except Exception as cleanup_err:
  2900. logger.debug(
  2901. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  2902. item.id,
  2903. cleanup_err,
  2904. )
  2905. try:
  2906. await ws_manager.send_queue_item_failed(
  2907. user_id=toast_uid,
  2908. queue_item_id=item.id,
  2909. printer_id=item.printer_id,
  2910. reason="cancelled_mid_dispatch",
  2911. )
  2912. except Exception:
  2913. pass
  2914. return
  2915. # Sync the in-memory item so subsequent code that reads item.status /
  2916. # item.started_at sees the values we just persisted.
  2917. item.status = "printing"
  2918. item.started_at = now_utc
  2919. for cleanup_path in cleanup_disk_paths:
  2920. try:
  2921. if cleanup_path.exists():
  2922. cleanup_path.unlink()
  2923. except OSError as cleanup_err:
  2924. logger.warning(
  2925. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  2926. json.dumps(
  2927. {
  2928. "queue_item_id": item.id,
  2929. "path": str(cleanup_path),
  2930. "error": str(cleanup_err),
  2931. },
  2932. sort_keys=True,
  2933. ),
  2934. )
  2935. # Clear the awaiting-plate-clear flag now that we're starting a new print
  2936. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  2937. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  2938. # Capture state before dispatch so the watchdog can detect whether the
  2939. # printer actually transitioned (#967). Also capture subtask_id so the
  2940. # watchdog can recognise "command landed but state hasn't flipped yet"
  2941. # on slow H2D transitions (#1078).
  2942. pre_status = printer_manager.get_status(item.printer_id)
  2943. pre_state = getattr(pre_status, "state", None) if pre_status else None
  2944. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  2945. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  2946. # #1721: respect the user's explicit timelapse choice. The #1397
  2947. # force-on at dispatch was removed because it caused per-layer nozzle
  2948. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  2949. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  2950. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  2951. # FINISH-state fallback — no need to force a video.
  2952. effective_timelapse = bool(item.timelapse)
  2953. # Start the print with AMS mapping, plate_id and print options.
  2954. # nozzle_mapping rides through verbatim — JSON string captured from
  2955. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  2956. # parses + injects it only for dual-nozzle models so a null on every
  2957. # other model is a transparent pass-through.
  2958. started = printer_manager.start_print(
  2959. item.printer_id,
  2960. remote_filename,
  2961. plate_id=item.plate_id or 1,
  2962. ams_mapping=ams_mapping,
  2963. bed_levelling=item.bed_levelling,
  2964. flow_cali=item.flow_cali,
  2965. vibration_cali=item.vibration_cali,
  2966. layer_inspect=item.layer_inspect,
  2967. timelapse=effective_timelapse,
  2968. use_ams=item.use_ams,
  2969. nozzle_offset_cali=item.nozzle_offset_cali,
  2970. nozzle_mapping=item.nozzle_mapping,
  2971. )
  2972. if started:
  2973. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  2974. # No dispatch-toast event here: the legacy bg-dispatch path kept
  2975. # status='processing' from upload start until the printer acked
  2976. # (or timed out). The frontend derives "Awaiting printer…" purely
  2977. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  2978. # event would push the status chip out of 'PROCESSING' prematurely
  2979. # — which is exactly what the screenshot at #1625-followup
  2980. # complained about.
  2981. # Register the local 3MF in the cover-cache so /cover skips FTP
  2982. # (#1166 follow-up). file_path was resolved earlier from either the
  2983. # archive or the library file row.
  2984. if file_path is not None:
  2985. cache_3mf_download(item.printer_id, remote_filename, file_path)
  2986. # Hold the printer against further dispatches until the watchdog
  2987. # confirms the printer transitioned (or until the hard timeout).
  2988. # Prevents multi-plate batches from triple-dispatching onto the
  2989. # same H2D Pro while it digests the first project_file (#1157).
  2990. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  2991. # Watchdog: if the printer never transitions out of pre_state AND
  2992. # never advances subtask_id, the MQTT publish was accepted locally but
  2993. # didn't reach the printer (half-broken session — same shape as
  2994. # #887/#936). Revert the queue item so the next dispatch can pick it
  2995. # up instead of leaving it stuck in "printing" (#967). subtask_id
  2996. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  2997. # that would otherwise cause the item to re-dispatch as a reprint
  2998. # of the just-finished job (#1078).
  2999. if pre_state:
  3000. spawn_background_task(
  3001. self._watchdog_print_start(
  3002. item.id,
  3003. item.printer_id,
  3004. pre_state,
  3005. pre_subtask_id,
  3006. pre_gcode_file,
  3007. created_by_id=toast_uid,
  3008. ),
  3009. name=f"watchdog-print-start-{item.id}",
  3010. )
  3011. # Get estimated time for notification.
  3012. #
  3013. # This used to fall back to `library_file.print_time_seconds`, a column
  3014. # LibraryFile does not have — the print time it knows about lives in
  3015. # `file_metadata`. So a library print whose archive carried no parseable
  3016. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  3017. # AttributeError right here, *after* the printer had already been sent
  3018. # the job: the started-notification never fired, and the exception
  3019. # unwound the whole queue pass, so every other printer still waiting to
  3020. # be dispatched on that tick silently missed its turn.
  3021. #
  3022. # The queue item caches the print time at creation ("Cached from
  3023. # archive/library"), which is the value this was reaching for.
  3024. estimated_time = None
  3025. if archive and archive.print_time_seconds:
  3026. estimated_time = archive.print_time_seconds
  3027. elif item.print_time_seconds:
  3028. estimated_time = item.print_time_seconds
  3029. # Send job started notification
  3030. await notification_service.on_queue_job_started(
  3031. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  3032. printer_id=printer.id,
  3033. printer_name=printer.name,
  3034. db=db,
  3035. estimated_time=estimated_time,
  3036. )
  3037. # MQTT relay - publish queue job started
  3038. try:
  3039. from backend.app.services.mqtt_relay import mqtt_relay
  3040. await mqtt_relay.on_queue_job_started(
  3041. job_id=item.id,
  3042. filename=filename,
  3043. printer_id=printer.id,
  3044. printer_name=printer.name,
  3045. printer_serial=printer.serial_number,
  3046. )
  3047. except Exception:
  3048. pass # Don't fail if MQTT fails
  3049. else:
  3050. # Clean up uploaded file from SD card to prevent phantom prints
  3051. try:
  3052. await delete_file_async(
  3053. printer.ip_address,
  3054. printer.access_code,
  3055. remote_path,
  3056. printer_model=printer.model,
  3057. )
  3058. except Exception:
  3059. pass # Best-effort — don't fail the error handler
  3060. # Print command failed - revert status
  3061. item.status = "failed"
  3062. item.error_message = "Failed to send print command to printer"
  3063. item.completed_at = datetime.now(timezone.utc)
  3064. await db.commit()
  3065. logger.error(
  3066. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  3067. f"printer_manager.start_print() returned False. "
  3068. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  3069. f"Check printer status and backend logs for details."
  3070. )
  3071. # Send failure notification
  3072. await notification_service.on_queue_job_failed(
  3073. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  3074. printer_id=printer.id,
  3075. printer_name=printer.name,
  3076. reason="Failed to send print command to printer - check printer connection and status",
  3077. db=db,
  3078. )
  3079. try:
  3080. await ws_manager.send_queue_item_failed(
  3081. user_id=toast_uid,
  3082. queue_item_id=item.id,
  3083. printer_id=item.printer_id,
  3084. reason="start_command_failed",
  3085. )
  3086. except Exception:
  3087. pass
  3088. await self._power_off_if_needed(db, item)
  3089. @staticmethod
  3090. async def _watchdog_print_start(
  3091. queue_item_id: int,
  3092. printer_id: int,
  3093. pre_state: str,
  3094. pre_subtask_id: str | None = None,
  3095. pre_gcode_file: str | None = None,
  3096. timeout: float = 90.0,
  3097. phase_b_timeout: float = 180.0,
  3098. poll_interval: float = 3.0,
  3099. created_by_id: int | None = None,
  3100. ) -> None:
  3101. """Revert a queue item if the printer never acknowledges the start command.
  3102. Bambuddy optimistically marks the queue item as "printing" right after the
  3103. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  3104. Phase A (up to ``timeout``): wait for either an active-state transition
  3105. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  3106. primary signal; subtask_id advance handles the H2D case where state can
  3107. sit at FINISH for ~50 s after the printer accepted ``project_file``
  3108. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  3109. was lost on a half-broken session (#887/#936) — revert and force
  3110. reconnect (the #967 recovery path).
  3111. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  3112. alone): keep watching for the active-state transition. subtask_id alone
  3113. proves the file landed but not that the printer started — and a printer
  3114. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  3115. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  3116. used to leave the queue item stuck in 'printing' forever because the
  3117. old watchdog returned success as soon as subtask_id advanced. If Phase
  3118. B times out, revert the queue item so the user can retry without
  3119. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  3120. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  3121. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  3122. transitions that also don't emit an early subtask_id tick.
  3123. """
  3124. last_status = None
  3125. landed_on_subtask = False
  3126. deadline = time.monotonic() + timeout
  3127. while time.monotonic() < deadline:
  3128. await asyncio.sleep(poll_interval)
  3129. status = printer_manager.get_status(printer_id)
  3130. if not status:
  3131. # Printer disconnected — don't mess with the DB. Drop the
  3132. # in-memory dispatch hold too so a fresh dispatch can retry
  3133. # once the printer comes back; the hard timeout would
  3134. # otherwise hold the printer unnecessarily.
  3135. scheduler._release_dispatch_hold(printer_id)
  3136. return
  3137. last_status = status
  3138. if status.state in _ACTIVE_PRINT_STATES:
  3139. # Printer is actively processing the job — release the
  3140. # post-dispatch hold so the next pending item for this printer
  3141. # can be evaluated normally. We do NOT accept arbitrary state
  3142. # transitions: a printer going FINISH -> IDLE (user dismissed
  3143. # the post-print prompt without accepting our project_file)
  3144. # would otherwise look like "command landed" and leave the
  3145. # queue item stuck in 'printing' forever (#1370).
  3146. scheduler._release_dispatch_hold(printer_id)
  3147. try:
  3148. await ws_manager.send_queue_item_acked(
  3149. user_id=created_by_id,
  3150. queue_item_id=queue_item_id,
  3151. printer_id=printer_id,
  3152. )
  3153. except Exception:
  3154. pass
  3155. return
  3156. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  3157. # Phase A exit — printer accepted the file (subtask_id flipped
  3158. # to our submission id). Don't return yet: the printer may
  3159. # have accepted the command but never actually start (e.g.
  3160. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  3161. # B watches for the active-state transition.
  3162. landed_on_subtask = True
  3163. break
  3164. if landed_on_subtask:
  3165. phase_b_deadline = time.monotonic() + phase_b_timeout
  3166. while time.monotonic() < phase_b_deadline:
  3167. await asyncio.sleep(poll_interval)
  3168. status = printer_manager.get_status(printer_id)
  3169. if not status:
  3170. scheduler._release_dispatch_hold(printer_id)
  3171. return
  3172. last_status = status
  3173. if status.state in _ACTIVE_PRINT_STATES:
  3174. scheduler._release_dispatch_hold(printer_id)
  3175. try:
  3176. await ws_manager.send_queue_item_acked(
  3177. user_id=created_by_id,
  3178. queue_item_id=queue_item_id,
  3179. printer_id=printer_id,
  3180. )
  3181. except Exception:
  3182. pass
  3183. return
  3184. # No active-state transition. Revert the item so the scheduler can retry.
  3185. # Drop the in-memory hold so the retry isn't blocked by it.
  3186. scheduler._release_dispatch_hold(printer_id)
  3187. # Four outcomes from the revert attempt, each routed differently:
  3188. # "reverted": row flipped from printing -> pending, run recovery
  3189. # "gave_up": same, but the retry budget is spent — row failed
  3190. # rather than pending, so it stops going round again
  3191. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  3192. # on_print_complete or user). Skip recovery entirely
  3193. # — the print clearly landed somewhere even if the
  3194. # watchdog didn't see the active-state transition.
  3195. # "revert_failed": SQLite contention exhausted retries. Still run
  3196. # recovery so the MQTT session gets a fresh client_id
  3197. # on the half-broken-session path.
  3198. #
  3199. # The retry budget (#2555): reverting to 'pending' hands the item straight
  3200. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  3201. # the watchdog again. For a printer that is genuinely wedged that loop never
  3202. # ends — the reporter had one printer "since this morning still not launch"
  3203. # — and each lap also consumes an upload slot that the other printers in the
  3204. # farm are waiting on. Retrying is right; retrying forever is not.
  3205. async def _do_revert(db):
  3206. item = await db.get(PrintQueueItem, queue_item_id)
  3207. if not item or item.status != "printing":
  3208. return "already_moved_on"
  3209. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  3210. item.started_at = None
  3211. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  3212. item.status = "failed"
  3213. item.error_message = (
  3214. f"The printer accepted the file but never started printing, after "
  3215. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  3216. f"prompt or error, confirm its SD card is readable, and start the job again."
  3217. )
  3218. item.completed_at = datetime.now(timezone.utc)
  3219. await db.commit()
  3220. return "gave_up"
  3221. item.status = "pending"
  3222. await db.commit()
  3223. return "reverted"
  3224. try:
  3225. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  3226. except Exception as e:
  3227. logger.warning(
  3228. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  3229. "scheduler may keep treating this item as in-flight",
  3230. queue_item_id,
  3231. printer_id,
  3232. e,
  3233. )
  3234. revert_outcome = "revert_failed"
  3235. if revert_outcome == "already_moved_on":
  3236. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  3237. # other path) already moved the item past 'printing', don't run the
  3238. # MQTT session-recovery logic below — a forced reconnect on a healthy
  3239. # session breaks ongoing prints on the same printer.
  3240. return
  3241. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  3242. if revert_outcome == "gave_up":
  3243. logger.error(
  3244. "Queue item %s: printer %d never started the print after %d dispatch "
  3245. "attempts (last one waited %.0fs) — marking the item failed instead of "
  3246. "re-uploading it again (#2555)",
  3247. queue_item_id,
  3248. printer_id,
  3249. DISPATCH_MAX_ATTEMPTS,
  3250. total_timeout,
  3251. )
  3252. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  3253. elif revert_outcome == "reverted":
  3254. if landed_on_subtask:
  3255. logger.warning(
  3256. "Queue item %s: printer %d accepted project_file (subtask_id "
  3257. "advanced) but never transitioned to an active state within "
  3258. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  3259. "for retry (#1678)",
  3260. queue_item_id,
  3261. printer_id,
  3262. total_timeout,
  3263. )
  3264. else:
  3265. logger.warning(
  3266. "Queue item %s: printer %d did not respond to print command within "
  3267. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  3268. "for retry (#967)",
  3269. queue_item_id,
  3270. printer_id,
  3271. timeout,
  3272. pre_state,
  3273. pre_subtask_id,
  3274. )
  3275. # Phase B was entered iff subtask_id advanced, which means the
  3276. # project_file landed on the printer. A forced reconnect at this point
  3277. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  3278. # skip the recovery entirely.
  3279. if landed_on_subtask:
  3280. return
  3281. # Phase A timeout path: if the printer's gcode_file changed since
  3282. # pre-dispatch, the project_file command landed and the printer is
  3283. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  3284. # If gcode_file is unchanged, the publish was silently swallowed
  3285. # (#887/#936) and force_reconnect recovery is what we want.
  3286. client = printer_manager.get_client(printer_id)
  3287. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  3288. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  3289. if publish_landed:
  3290. logger.warning(
  3291. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  3292. "received the command and is parsing slowly. Skipping forced "
  3293. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  3294. queue_item_id,
  3295. current_gcode_file,
  3296. pre_gcode_file,
  3297. )
  3298. elif client and hasattr(client, "force_reconnect_stale_session"):
  3299. client.force_reconnect_stale_session(
  3300. f"queue print command unacknowledged after {timeout:.0f}s "
  3301. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  3302. )
  3303. # Global scheduler instance
  3304. scheduler = PrintScheduler()