print_scheduler.py 173 KB

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