print_scheduler.py 307 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. import uuid
  7. from collections import deque
  8. from dataclasses import dataclass
  9. from datetime import datetime, timezone
  10. from pathlib import Path
  11. from fastapi import HTTPException
  12. from sqlalchemy import func, select, update
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. from sqlalchemy.orm import selectinload
  15. from backend.app.core.config import settings
  16. from backend.app.core.database import async_session, run_with_retry
  17. from backend.app.core.tasks import spawn_background_task
  18. from backend.app.core.websocket import ws_manager
  19. from backend.app.models.archive import PrintArchive
  20. from backend.app.models.library import LibraryFile
  21. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  22. from backend.app.models.printer import Printer
  23. from backend.app.models.settings import Settings
  24. from backend.app.models.smart_plug import SmartPlug
  25. from backend.app.models.spool_assignment import SpoolAssignment
  26. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  27. from backend.app.services import print_dispatch_context
  28. from backend.app.services.bambu_ftp import (
  29. UploadCancelled,
  30. cache_3mf_download,
  31. delete_file_async,
  32. get_ftp_retry_settings,
  33. upload_file_async,
  34. with_ftp_retry,
  35. )
  36. from backend.app.services.bambu_mqtt import HMS_MQTT_VERIFY_FAILED
  37. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  38. from backend.app.services.finance_budget import (
  39. create_budget_reservation,
  40. release_budget_reservation,
  41. validate_print_budget,
  42. )
  43. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  44. from backend.app.services.notification_service import notification_service
  45. from backend.app.services.print_cost_estimate import estimate_queue_source_cost
  46. from backend.app.services.printer_manager import (
  47. printer_manager,
  48. supports_airduct,
  49. supports_chamber_heater,
  50. supports_chamber_temp,
  51. supports_drying,
  52. supports_drying_while_printing,
  53. )
  54. from backend.app.services.smart_plug_manager import smart_plug_manager
  55. from backend.app.utils.filename import derive_remote_filename
  56. from backend.app.utils.printer_models import (
  57. is_gcode_compatible,
  58. is_nozzle_rack_model,
  59. normalize_printer_model,
  60. )
  61. from backend.app.utils.threemf_tools import extract_slot_extruders_from_3mf
  62. logger = logging.getLogger(__name__)
  63. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  64. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  65. # byte gate) from before the scheduler unification. Time gate keeps small
  66. # files from going silent (a single 8 KB chunk fires once and that's it);
  67. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  68. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  69. # sub-200 ms files.
  70. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  71. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  72. # How far back chamber temperature samples are retained. 2h comfortably spans
  73. # any soak a user can configure (capped at 30 min) plus the plate-clearing gap
  74. # before the next print.
  75. _CHAMBER_HISTORY_TTL_SECONDS = 7200
  76. # Fallback for `queue_keep_warm_max_minutes` — how long the bed may be held
  77. # warm on a printer sitting in FINISH before the heaters are shut off. Users
  78. # who clear plates promptly will want far less than this; it is deliberately
  79. # the cautious end, since the cost of it being too short is only a re-soak.
  80. _KEEP_WARM_MAX_MINUTES_DEFAULT = 120
  81. # Max acceptable gap between two consecutive chamber samples before we treat
  82. # the older one as belonging to a separate observation run (printer went
  83. # offline and came back). Above ~30s cadence with a safety margin.
  84. _CHAMBER_SAMPLE_MAX_GAP_SECONDS = 60.0
  85. # How long the chamber must read below target before we accept that it really
  86. # cooled. An enclosed chamber's thermal mass cannot lose and regain several
  87. # degrees quickly: measured on an X1C, falling from ~55°C to below 48°C took
  88. # 23-73 minutes (~0.2 C/min), while the fastest drop ever recorded was
  89. # 27 C/min — impossible for that mass, i.e. a sensor artifact. Brief
  90. # sub-target readings are therefore a door opening or noise, not lost soak,
  91. # and a plate swap (exactly when keep-warm is running) produces one. Six
  92. # minutes clears the longest such artifact observed (~5 min once bracketed by
  93. # its neighbouring samples) and still sits far below the 23-minute floor for
  94. # real cooling.
  95. _CHAMBER_DIP_GRACE_SECONDS = 360.0
  96. # How often the preheat stage re-checks that the item it is heating for still
  97. # wants to be printed. Cancelling only writes `status` to the database — it
  98. # cannot interrupt a coroutine parked in `asyncio.sleep` — so without this the
  99. # heaters run for the rest of max_wait + soak (45 min at the default settings)
  100. # and the printer stays in `busy_printers`, blocking every other queued item
  101. # behind a print that is not happening.
  102. _PREHEAT_CANCEL_CHECK_SECONDS = 10.0
  103. # set_airduct_mode modeId values (bambu_mqtt.py:5937 — 0 cooling, 1 heating).
  104. _AIRDUCT_MODE_COOLING = 0
  105. _AIRDUCT_MODE_HEATING = 1
  106. @dataclass
  107. class _KeepWarmEntry:
  108. """Per-printer keep-warm state.
  109. - ``started``: monotonic time when keep-warm first fired for this printer.
  110. Used by the max-duration timeout.
  111. - ``held_target``: last bed target we successfully published. On release
  112. we only send bed-off when firmware still reports this value, so a user
  113. or subsequent print that changed the target isn't clobbered.
  114. - ``expired``: latched True when the max-duration timeout fires. Prevents
  115. re-engagement (and re-seeding of ``started``) on subsequent ticks. The
  116. release sweep drops the entry entirely once the printer leaves the
  117. candidate set.
  118. """
  119. started: float
  120. held_target: int
  121. expired: bool = False
  122. # Auto-drying re-arm guards (#2770).
  123. #
  124. # An AMS reports HIGHER relative humidity while it is warm than once it has
  125. # cooled: measured on an H2D/AMS 2 Pro at 10-13% cold against 15-20% throughout
  126. # every drying cycle, and the same unit read 16-20% across a full 12 h dry. A
  127. # threshold set inside that band therefore cannot be satisfied while the box is
  128. # hot, and the firmware is free to end a cycle whenever it decides the filament
  129. # is dry — so the next 30 s pass sees dry_time 0 with the reading still above
  130. # the threshold and arms another cycle. The reporter's log has five 12-hour
  131. # cycles armed inside four hours, one of them six seconds after the previous
  132. # ended.
  133. #
  134. # The cooldown stops the six-second re-arm; the unproductive-cycle cap stops the
  135. # loop. Neither ever stops a running cycle — both only gate STARTING one, so a
  136. # manual or firmware-run dry is untouched.
  137. AUTO_DRY_REARM_COOLDOWN_SECONDS = 30 * 60
  138. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES = 2
  139. class _UploadProgressBridge:
  140. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  141. ``upload_file_async`` runs the FTP transfer in an executor thread and
  142. invokes its ``progress_callback`` from that thread, so the callback
  143. body cannot ``await`` directly. This bridge captures the asyncio loop
  144. at construction (on the scheduler thread) and uses
  145. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  146. matches the legacy background_dispatch.py path 1:1 so the toast feels
  147. identical to the pre-#1625 experience.
  148. Failures inside the emit are swallowed — progress is a UX nicety, the
  149. upload itself must not fail because of a WS hiccup.
  150. """
  151. def __init__(self, user_id: int | None, queue_item_id: int):
  152. self._user_id = user_id
  153. self._queue_item_id = queue_item_id
  154. try:
  155. self._loop = asyncio.get_running_loop()
  156. except RuntimeError:
  157. self._loop = None
  158. self._last_emit_bytes = 0
  159. self._last_emit_monotonic = 0.0
  160. self._has_emitted = False
  161. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  162. if self._loop is None or total_bytes <= 0:
  163. return
  164. now = time.monotonic()
  165. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  166. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  167. # the four matter most: first-call so the user sees something even
  168. # for sub-chunk-size files; uploaded >= total so the bar locks at
  169. # 100% even when the throttle would otherwise eat it.
  170. should_emit = (
  171. not self._has_emitted
  172. or bytes_transferred >= total_bytes
  173. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  174. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  175. )
  176. if not should_emit:
  177. return
  178. self._has_emitted = True
  179. self._last_emit_bytes = bytes_transferred
  180. self._last_emit_monotonic = now
  181. try:
  182. asyncio.run_coroutine_threadsafe(
  183. ws_manager.send_queue_item_upload_progress(
  184. user_id=self._user_id,
  185. queue_item_id=self._queue_item_id,
  186. bytes_transferred=bytes_transferred,
  187. total_bytes=total_bytes,
  188. ),
  189. self._loop,
  190. )
  191. except Exception:
  192. pass # progress is best-effort, never block the upload
  193. # Bambu firmware states that mean the project_file has actually been accepted
  194. # and the printer is now processing / running / paused mid-print. Used by the
  195. # dispatch watchdog (#1370): a transition into one of these states means the
  196. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  197. # a post-print prompt) is NOT a valid "command landed" signal even though the
  198. # state value did change. SLICING is included because some firmwares park
  199. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  200. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  201. # How many times the start-watchdog may revert an item to 'pending' before it
  202. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  203. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  204. # both never recovers and starves the other printers of dispatch slots. Three
  205. # is chosen to clear the transient causes the watchdog already recovers from —
  206. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  207. # force-reconnect on the very next attempt — while still bounding the loop.
  208. DISPATCH_MAX_ATTEMPTS = 3
  209. # Filament type equivalence groups — types within the same group are
  210. # interchangeable on the printer side (Bambu Lab firmware treats them as compatible).
  211. _FILAMENT_TYPE_GROUPS: list[list[str]] = [
  212. ["PA-CF", "PA12-CF", "PAHT-CF"],
  213. ]
  214. _FILAMENT_EQUIV_MAP: dict[str, str] = {}
  215. for _group in _FILAMENT_TYPE_GROUPS:
  216. _canonical = _group[0].upper()
  217. for _t in _group:
  218. _FILAMENT_EQUIV_MAP[_t.upper()] = _canonical
  219. def _canonical_filament_type(ftype: str) -> str:
  220. """Return canonical type for equivalence matching."""
  221. upper = ftype.upper()
  222. return _FILAMENT_EQUIV_MAP.get(upper, upper)
  223. @dataclass(slots=True)
  224. class _ModelCandidate:
  225. """One (file, printer model) pair the model-based matcher may try.
  226. Model-based assignment used to have exactly one of these per item, held
  227. directly in the item's own columns. Cross-model queue items (#671) have
  228. several, held in ``print_queue_variants``. Both shapes are normalised into
  229. this so the matching, the cross-model gate and the waiting-reason handling
  230. are written once and an item without variants provably takes the same path
  231. it took before variants existed.
  232. ``variant`` is None for the item's own columns and set for a real variant
  233. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  234. item once that candidate wins.
  235. """
  236. target_model: str | None
  237. sliced_for: str | None
  238. required_filament_types: str | None
  239. filament_overrides: str | None
  240. variant: "PrintQueueVariant | None" = None
  241. def _sliced_for_model(archive, library_file) -> str | None:
  242. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  243. if archive is not None:
  244. return archive.sliced_for_model
  245. if library_file is not None and library_file.file_metadata:
  246. return library_file.file_metadata.get("sliced_for_model")
  247. return None
  248. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  249. """Candidate files for ``item``, best first.
  250. An item with no variant rows yields exactly one candidate built from its own
  251. columns — the pre-#671 behaviour, unchanged.
  252. Variants come back least-attempted first, ties broken by the user's
  253. ``position``. On the first pass every count is zero, so this is purely the
  254. user's priority order. After a start-watchdog bounce the printer that failed
  255. drops behind, so the next lap tries the other machine rather than spending the
  256. item's whole retry budget on the one that is wedged. Once every candidate has
  257. been tried equally often they cycle again, which keeps the item-level
  258. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  259. still gives up, it just does not give up without trying them.
  260. """
  261. if not item.variants:
  262. if not item.archive_id and not item.library_file_id:
  263. # Nothing to print at all. Dispatching would fail deep in the upload
  264. # on "No archive_id or library_file_id"; the caller holds the item
  265. # with an explanation instead.
  266. return []
  267. return [
  268. _ModelCandidate(
  269. target_model=item.target_model,
  270. sliced_for=_sliced_for_model(item.archive, item.library_file),
  271. required_filament_types=item.required_filament_types,
  272. filament_overrides=item.filament_overrides,
  273. )
  274. ]
  275. # Drop candidates whose file is gone or in the trash. Both are reachable and
  276. # neither is covered by the schema: library deletes are soft (the row lives
  277. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  278. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  279. # fires there and a hard delete leaves the variant row pointing at nothing.
  280. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  281. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  282. return [
  283. _ModelCandidate(
  284. target_model=v.target_model,
  285. sliced_for=_sliced_for_model(None, v.library_file),
  286. required_filament_types=v.required_filament_types,
  287. filament_overrides=v.filament_overrides,
  288. variant=v,
  289. )
  290. for v in ordered
  291. ]
  292. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  293. """Fold one waiting reason per candidate into a single line for the item.
  294. A cross-model item produces a reason per candidate, and pasting them
  295. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  296. — on which machine?). Each reason is prefixed with its model, except in the
  297. single-candidate case where the item already displays its target model and
  298. the prefix would be noise.
  299. Identical reasons collapse rather than repeat, so three idle-less models
  300. read as one clause.
  301. When *every* candidate is merely busy the parts are joined with the ``" | "``
  302. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  303. unprefixed. That case must keep testing busy-only: a fleet that is simply
  304. printing needs no user action, and labelling the clauses would turn each pass
  305. over a two-model item into a "job waiting" notification.
  306. """
  307. reasons = [(model, reason) for model, reason in per_model if reason]
  308. if not reasons:
  309. return None
  310. if len(reasons) == 1:
  311. return reasons[0][1]
  312. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  313. if len(distinct) == 1:
  314. return distinct[0]
  315. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  316. return " | ".join(distinct)
  317. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  318. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  319. """Human label for the models an item is waiting on ("H2S or H2C").
  320. Notifications take a single target model. For a cross-model item the item's
  321. own ``target_model`` is whichever variant happens to be first, which reads as
  322. a lie once it is the H2C that actually runs — so name all of them.
  323. """
  324. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  325. if not models:
  326. return None
  327. return " or ".join(models)
  328. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  329. """True if ``mapping`` is a non-empty list whose every entry is the
  330. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  331. Such a mapping is a bug artifact: a frontend status-load race can serialize
  332. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  333. recomputed from live status at dispatch rather than trusted, otherwise it
  334. reaches the print command and is silently downgraded to external-spool mode.
  335. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  336. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  337. explicit external selection (``>= 254``) is NOT unresolved either — those
  338. keep their meaning.
  339. """
  340. if not isinstance(mapping, list) or not mapping:
  341. return False
  342. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  343. def _mqtt_commands_rejected(status) -> bool:
  344. """True when the printer is currently reporting that it refused a command.
  345. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  346. a control command it could not verify. Queries still answer, so the printer
  347. looks connected and idle while project_file, gcode_line and
  348. ams_change_filament are all dropped — no amount of waiting or re-uploading
  349. changes that (#2732).
  350. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  351. ``print_error`` path builds HMSError differently), so this is safe to call on
  352. every watchdog poll.
  353. """
  354. for err in getattr(status, "hms_errors", None) or []:
  355. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  356. return True
  357. return False
  358. def _drying_ams_ids(status) -> list[int]:
  359. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  360. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  361. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  362. started (#2758) — it is a diagnostic, not a gate.
  363. Deliberately not used to block or stop drying before dispatch. This printer
  364. class supports drying concurrently with an active print
  365. (``supports_drying_while_printing``), so drying is not incompatible with
  366. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  367. while two AMS units were drying, one of them without its external PSU. Until
  368. it is known whether the blocker is drying itself or the power budget
  369. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  370. hardware is perfectly happy to continue.
  371. """
  372. ids: list[int] = []
  373. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  374. if not isinstance(unit, dict):
  375. continue
  376. try:
  377. if int(unit.get("dry_time") or 0) > 0:
  378. ids.append(int(unit.get("id", 0)))
  379. except (TypeError, ValueError):
  380. continue
  381. return ids
  382. def _installed_nozzle_diameters(status) -> list[float]:
  383. """Parse the installed nozzle diameters from a PrinterState (#1899).
  384. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  385. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  386. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  387. told us its nozzle hardware" — callers must treat that as unknown, not as a
  388. mismatch, so we never block a print on missing data.
  389. """
  390. diameters: list[float] = []
  391. for nozzle in getattr(status, "nozzles", None) or []:
  392. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  393. try:
  394. value = float(raw)
  395. except (TypeError, ValueError):
  396. continue
  397. if value > 0:
  398. diameters.append(value)
  399. return diameters
  400. def _nozzle_mismatch_message(sliced_nozzle: float | None, installed: list[float]) -> str | None:
  401. """Return an actionable error message when the sliced nozzle can't be
  402. printed on any installed nozzle, else None (#1899).
  403. Fail-safe: returns None whenever we lack the data to judge — no sliced
  404. diameter, or the printer reported no nozzles — so a print is only ever
  405. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  406. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  407. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  408. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  409. """
  410. if not sliced_nozzle or not installed:
  411. return None
  412. if any(abs(d - sliced_nozzle) < 0.05 for d in installed):
  413. return None
  414. installed_str = " / ".join(f"{d:g}mm" for d in installed)
  415. return (
  416. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  417. f"{installed_str} installed. Re-slice for the installed nozzle, or "
  418. f"install the matching nozzle before printing."
  419. )
  420. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  421. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  422. Shared by the required and loaded sides, which name their extruder
  423. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  424. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  425. 1 the left/deputy — and both are absent on single-nozzle printers, where
  426. naming a nozzle would be noise.
  427. """
  428. parts = [(entry.get("type") or "filament").upper()]
  429. if entry.get("color"):
  430. parts.append(str(entry["color"]))
  431. nozzle = entry.get(nozzle_key)
  432. if nozzle == 0:
  433. parts.append("(right nozzle)")
  434. elif nozzle == 1:
  435. parts.append("(left nozzle)")
  436. return " ".join(parts)
  437. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  438. """Explain that nothing loaded matches what the file needs (#2771).
  439. Only ever built for a printer with no AMS, where the loaded list is short
  440. enough to quote in full and there is no "load another spool and hit Resume"
  441. recovery — the external spool holder is all there is, so the user needs to
  442. be told which filament to put on it.
  443. """
  444. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  445. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  446. return (
  447. f"No filament loaded on this printer matches the file. It needs {want}; "
  448. f"the printer has {have} and no AMS. Load the required filament on the "
  449. f"external spool holder, or send this job to a printer that has it."
  450. )
  451. class PrintScheduler:
  452. """Background scheduler that processes the print queue."""
  453. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  454. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  455. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  456. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  457. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  458. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  459. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  460. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  461. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  462. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  463. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  464. }
  465. def __init__(self):
  466. self._running = False
  467. self._check_interval = 30 # seconds
  468. # After a pass that actually dispatched something, loop again almost
  469. # immediately instead of sleeping the full interval (#2555). A dispatch
  470. # changes printer state — a batch launch fans out over several passes as
  471. # printers free up, a wedged head-of-line job reverts to pending, an
  472. # upload slot opens — and the next batch of ready work should not have to
  473. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  474. # pending items are behind printers that are genuinely busy printing),
  475. # there is nothing to react to, so we fall back to the normal interval;
  476. # that also means this can never tight-loop, since fast ticks only
  477. # continue while dispatches keep happening and the queue is draining.
  478. self._fast_check_interval = 3 # seconds
  479. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  480. self._power_on_check_interval = 10 # seconds between connection checks
  481. # Printers whose class-target power-on failed, mapped to the monotonic
  482. # time their cool-off expires (#2786).
  483. #
  484. # Without this, one printer with an unreachable plug starves every
  485. # sibling of its model forever: the wake step walks candidates in id
  486. # order, spends the pass's single attempt on the same broken printer
  487. # every time, and the healthy one two slots down is never reached. It
  488. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  489. # which delays the whole queue, not just this job.
  490. #
  491. # Entries expire on read rather than being cleared on success: a printer
  492. # inside its cool-off is skipped before the power-on is reached, so a
  493. # live entry can never be overwritten by a success anyway. A printer
  494. # that comes back by any other route stops being a wake candidate the
  495. # moment it connects.
  496. self._wake_failures: dict[int, float] = {}
  497. self._wake_failure_cooloff = 600 # seconds
  498. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  499. self._drying_in_progress: dict[int, float] = {}
  500. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  501. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  502. # cycle and the humidity finally coming down, so the normal steady
  503. # state is an empty dict. Fields:
  504. # running — a cycle we armed is (or should be) on the firmware
  505. # ended_at — monotonic when we observed that cycle end
  506. # unproductive — consecutive armed cycles that ended with the reading
  507. # still above the threshold
  508. # suspended — we have stopped arming this unit and said so
  509. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  510. # Defensive in-memory dispatch hold (#1157): a printer that just received
  511. # a project_file command must not get a second dispatch until either it
  512. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  513. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  514. # during that window the DB busy_printers seed is empirically unreliable
  515. # (multi-plate batches double-/triple-dispatched onto the same printer
  516. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  517. # or revert.
  518. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  519. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  520. # Minimum cooldown between dispatches to the same printer (covers the
  521. # H2D's project_file digestion window).
  522. self._dispatch_min_cooldown = 60.0
  523. # Hard timeout — drop the hold even if we never observed a transition,
  524. # so a lost MQTT session can't lock a printer out of the queue forever.
  525. # Matches the watchdog timeout (90 s) plus a safety margin so the
  526. # watchdog runs first on the unhappy path.
  527. self._dispatch_max_hold = 180.0
  528. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  529. # an earlier pass and is still running. `_start_print` flips the row
  530. # pending -> printing only *after* the upload completes, so until then
  531. # the row stays `pending`: each tick, check_queue excludes these
  532. # item_ids from re-selection and their printers from new dispatch /
  533. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  534. # freed slots refill on the next fast tick. check_queue is the sole,
  535. # sequential caller and the prune done-callbacks run in the same
  536. # event-loop thread, so this dict needs no lock.
  537. # item_id -> (task, printer_id)
  538. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  539. # Expected prints registered by `_start_print` that have not yet had a
  540. # print command sent. Populated at registration, dropped once
  541. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  542. # other exit. Same threading argument as `_inflight` above: one
  543. # sequential caller, callbacks on the same loop, so no lock.
  544. # item_id -> (printer_id, remote_filename, archive_id)
  545. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  546. # Budget reservations created for a dispatch whose print command has
  547. # not been confirmed yet. `_dispatch_one` releases these on every
  548. # unsuccessful exit; a successful start removes the item id and leaves
  549. # the reservation for finance_billing to consume with the archive.
  550. self._unconfirmed_budget_reservations: set[int] = set()
  551. # Chamber temperature history for smart soak-time reduction.
  552. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  553. # Entries older than _chamber_history_ttl are pruned on write.
  554. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  555. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  556. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  557. # Populated on engagement in `_apply_keep_warm`, cleared by
  558. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  559. # when a gate setting toggles off mid-hold — the release publishes
  560. # bed → 0 first).
  561. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  562. # Preheat rollback registry: printer_id -> subset of
  563. # {"bed", "chamber", "airduct"} listing which preheat commands
  564. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  565. # every entry still present at exit unless the print successfully
  566. # started, so a failed upload / cancel / exception never leaves the
  567. # printer heating for a job that isn't happening.
  568. self._preheat_pin: dict[int, set[str]] = {}
  569. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  570. # rollback can tell its own target from one someone else has since
  571. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  572. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  573. self._preheat_pin_bed: dict[int, int] = {}
  574. # Item ids whose in-flight dispatch has been cancelled or deleted while
  575. # its preheat was still holding at temperature. Set by
  576. # `notify_dispatch_cancelled` from the queue routes, consumed by
  577. # `_preheat_sleep`, and cleared when the dispatch exits.
  578. self._cancelled_dispatches: set[int] = set()
  579. async def run(self):
  580. """Main loop - check queue every interval."""
  581. self._running = True
  582. logger.info("Print scheduler started")
  583. await self._clear_stale_dispatch_claims(at_startup=True)
  584. while self._running:
  585. dispatched = False
  586. try:
  587. self._sample_chamber_temps()
  588. # No-op while any upload is in flight; on a quiet tick it releases
  589. # a claim whose best-effort clear failed (e.g. the database was
  590. # briefly unreachable), instead of leaving the row wedged until
  591. # the next restart.
  592. await self._clear_stale_dispatch_claims()
  593. dispatched = await self.check_queue()
  594. except Exception as e:
  595. logger.error("Scheduler error: %s", e)
  596. # Re-check quickly after a productive pass so a draining batch does
  597. # not stall behind the idle interval; otherwise sleep normally (#2555).
  598. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  599. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  600. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  601. A claim is only ever held by a live dispatch coroutine, so when this
  602. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  603. is stale. At startup that is trivially true — no coroutine survives a
  604. restart. It is equally true on any later tick where no upload is running,
  605. which is what makes this safe to repeat rather than only run once.
  606. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  607. the database is briefly unreachable at exactly the moment dispatch ends,
  608. the claim survives and the row is wedged out of the selection query. That
  609. used to last until the next restart (#2702 follow-up, seen when
  610. PostgreSQL refused a connection mid-dispatch).
  611. ``_inflight`` is populated when the task is spawned, before the coroutine
  612. claims its row, and pruned by a done-callback that cannot run before the
  613. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  614. race window and needs no age threshold. A size-derived upload deadline
  615. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  616. """
  617. if self._inflight:
  618. return
  619. try:
  620. async with async_session() as db:
  621. res = await db.execute(
  622. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  623. )
  624. await db.commit()
  625. if res.rowcount:
  626. logger.info(
  627. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  628. res.rowcount,
  629. " at startup" if at_startup else "",
  630. )
  631. except Exception as exc:
  632. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  633. def stop(self):
  634. """Stop the scheduler."""
  635. self._running = False
  636. logger.info("Print scheduler stopped")
  637. async def check_queue(self) -> bool:
  638. """Check for prints ready to start.
  639. Returns True if this pass dispatched at least one item, so the caller
  640. can loop again quickly instead of sleeping the full interval (#2555).
  641. """
  642. async with async_session() as db:
  643. # Check if shortest-job-first scheduling is enabled
  644. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  645. # Get all pending items, ordered by printer and position (or SJF order)
  646. if sjf_enabled:
  647. # SJF: group by printer (and target_model for model-based jobs),
  648. # then items already jumped get top priority (starvation guard),
  649. # then sort by print_time ascending. Items with no print time go last.
  650. result = await db.execute(
  651. select(PrintQueueItem)
  652. .where(PrintQueueItem.status == "pending")
  653. # Never re-select a row a dispatch worker has already claimed
  654. # (#2615) — belt-and-suspenders with the _inflight exclusion
  655. # below, and the guard that lets an orphaned claim be ignored
  656. # until startup reconciliation clears it.
  657. .where(PrintQueueItem.dispatching_at.is_(None))
  658. # archive/library_file are read by the cross-model gate
  659. # (#2578); eager-load once per pass instead of a lazy-load
  660. # (which would raise in async) per item.
  661. .options(
  662. selectinload(PrintQueueItem.archive),
  663. selectinload(PrintQueueItem.library_file),
  664. # Cross-model candidates (#671), plus each candidate's file
  665. # for the same cross-model gate. Lazy-loading either would
  666. # raise in async.
  667. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  668. )
  669. .order_by(
  670. PrintQueueItem.printer_id,
  671. PrintQueueItem.target_model,
  672. PrintQueueItem.been_jumped.desc(),
  673. PrintQueueItem.print_time_seconds.asc().nullslast(),
  674. PrintQueueItem.position,
  675. )
  676. )
  677. else:
  678. result = await db.execute(
  679. select(PrintQueueItem)
  680. .where(PrintQueueItem.status == "pending")
  681. # Skip rows already claimed by a dispatch worker (#2615).
  682. .where(PrintQueueItem.dispatching_at.is_(None))
  683. .options(
  684. selectinload(PrintQueueItem.archive),
  685. selectinload(PrintQueueItem.library_file),
  686. # Cross-model candidates (#671), plus each candidate's file
  687. # for the same cross-model gate. Lazy-loading either would
  688. # raise in async.
  689. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  690. )
  691. .order_by(PrintQueueItem.printer_id, PrintQueueItem.position)
  692. )
  693. items = list(result.scalars().all())
  694. # Drop rows whose upload is still in flight from an earlier pass
  695. # (#2602). They stay `pending` until the upload finishes, so without
  696. # this a fast tick would re-select and re-dispatch the same row.
  697. # Belt-and-suspenders with the printer exclusion below.
  698. if self._inflight:
  699. inflight_ids = set(self._inflight)
  700. items = [it for it in items if it.id not in inflight_ids]
  701. # Read plate-clear setting once per queue check. Default MUST be
  702. # False to match the schema (SettingsSchema.require_plate_clear
  703. # defaults False) and the frontend (toggle + card badge both treat a
  704. # missing value as off). When no settings row exists, a True default
  705. # here re-enabled the plate-clear gate the UI showed as disabled,
  706. # blocking dispatch to FINISH-state printers forever with no UI path
  707. # to clear it (#1865).
  708. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  709. if not items:
  710. # No dispatchable pending items — still check auto-drying on idle
  711. # printers, but keep any printer with an upload still in flight
  712. # from an earlier pass out of it (#2602): its print is imminent,
  713. # so it must not be auto-dried in the gap before the row flips to
  714. # printing. Report the pass as productive while uploads run so the
  715. # loop stays on the fast interval.
  716. #
  717. # Also release any keep-warm holds that got orphaned by the queue
  718. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  719. # this early return, so call it directly with an empty candidate
  720. # set. Without this, a printer whose queued item was cancelled or
  721. # deleted would keep its bed at target until the max-duration
  722. # timeout expired.
  723. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  724. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  725. await self._check_auto_drying(db, [], inflight_printers)
  726. return bool(self._inflight)
  727. logger.info(
  728. "Queue check: found %d pending items: %s",
  729. len(items),
  730. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  731. )
  732. # Seed busy_printers with printers that already have an item in 'printing'
  733. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  734. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  735. # lag several seconds behind the print command, so the next check_queue
  736. # tick still sees IDLE and would double-dispatch onto the same printer.
  737. # Without this guard, two pending items targeting the same printer
  738. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  739. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  740. busy_result = await db.execute(
  741. select(PrintQueueItem.printer_id)
  742. .where(PrintQueueItem.status == "printing")
  743. .where(PrintQueueItem.printer_id.is_not(None))
  744. )
  745. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  746. # Defense-in-depth (#1157): augment busy_printers with any printer
  747. # still in its post-dispatch hold window. Empirically, the DB seed
  748. # above can miss in-flight items in a multi-plate batch — same-file
  749. # plates were being dispatched 30 s apart while the H2D was still
  750. # digesting the first project_file. The hold is keyed in-memory and
  751. # released by the watchdog on the success path, so it adds a layer
  752. # that doesn't depend on DB row visibility or completion-callback
  753. # timing.
  754. for held_printer_id in list(self._dispatch_holds.keys()):
  755. if self._printer_in_dispatch_hold(held_printer_id):
  756. busy_printers.add(held_printer_id)
  757. # Exclude printers whose upload is still in flight from an earlier
  758. # pass (#2602). The row is `pending` until the upload finishes and
  759. # the printing-state seed / dispatch hold above only arm once the
  760. # upload completes, so this is what holds the printer (and, via
  761. # busy_printers, its auto-drying) out of the pass during the upload.
  762. for _task, inflight_pid in self._inflight.values():
  763. if inflight_pid is not None:
  764. busy_printers.add(inflight_pid)
  765. # Snapshot taken here, before the item loop adds anything (#2801).
  766. #
  767. # The three sources above all mean the same thing: a print on this
  768. # printer is running or imminent. Everything the loop adds below
  769. # means only "the queue could not dispatch to it this pass", which
  770. # is a different statement -- a printer waiting on a plate-clear
  771. # acknowledgment, an offline printer, one with no matching file.
  772. #
  773. # Auto-drying must only see the first kind. Reading the whole set
  774. # as "is currently printing" is what put a plate-held printer down
  775. # the mid-print path: it capped the drying temperature, logged the
  776. # cycle as (mid-print), and skipped the very gate that was supposed
  777. # to hold it. The interlock block below already documents the same
  778. # hazard and works around it by staying out of busy_printers; this
  779. # generalises that workaround instead of repeating it per case.
  780. dispatching_printers: set[int] = set(busy_printers)
  781. # Printers held by a Home Assistant sensor interlock (#1148) — an
  782. # enclosure door left open, say. The fixed-printer branch turns
  783. # this into a waiting_reason the user can act on; the model-based
  784. # branch hides these printers from the matcher so an "Any <model>"
  785. # job runs on a sibling instead of queueing behind the held one.
  786. #
  787. # Deliberately NOT merged into busy_printers, even though that set
  788. # already means "unavailable this pass". _check_auto_drying reads
  789. # it as "is currently printing" and would put an idle-but-held
  790. # printer down the mid-print drying path, which caps the drying
  791. # temperature and skips the queue-only gating. A held printer is
  792. # idle; it should dry exactly as it did before.
  793. #
  794. # Only sensors we actually read and found alerting appear here; see
  795. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  796. # holds nothing.
  797. interlocked: dict[int, str] = {}
  798. try:
  799. interlocked = await ha_sensor_manager.blocked_printers(db)
  800. except Exception as e:
  801. # Never let the interlock stop the queue running. A broken
  802. # lookup means no holds, not no dispatches.
  803. logger.warning("Home Assistant interlock check failed: %s", e)
  804. interlocked = {}
  805. # Printers a smart plug can bring back, read once for the whole pass
  806. # (#2786). Used by the model-based branch both to word "Offline" in
  807. # the waiting reason and to decide what the wake step may switch on.
  808. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  809. # At most one power-on per queue check. Each one blocks this loop
  810. # for the boot wait, so a queue of ten class-targeted jobs must not
  811. # switch on ten printers inside a single pass — the next pass wakes
  812. # the next one (#2786).
  813. power_on_attempted = False
  814. # Log skip reasons once per queue check (not per item)
  815. skip_reasons: dict[str, int] = {}
  816. # Items selected for dispatch in this pass, one per printer. The
  817. # loop below only *decides* — the uploads happen afterwards, in
  818. # parallel (#2555). See _dispatch_selected().
  819. dispatch_ids: list[int] = []
  820. # Library rows queued with `cleanup_library_after_dispatch` (the
  821. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  822. # that prints them: the row is deleted and the 3MF is unlinked from
  823. # disk. That was safe only because dispatch was serial. Run two of
  824. # them against the same row at once and the second DELETE matches no
  825. # row (StaleDataError), and the winner's unlink can pull the file out
  826. # from under the loser's in-flight upload.
  827. #
  828. # Only the cleanup flag mutates the row. An ordinary library print
  829. # just reads it, so the common fan-out — one file, many printers,
  830. # which is exactly the reporter's workload — still goes out fully in
  831. # parallel. Narrow the guard to the mutating case; do not serialise
  832. # the case the whole fix exists for.
  833. dispatch_libs: set[int] = set()
  834. consumed_libs: set[int] = set()
  835. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  836. """True if dispatching `candidate` now would race another item's cleanup."""
  837. lib_id = candidate.library_file_id
  838. if lib_id is None:
  839. return False
  840. if candidate.cleanup_library_after_dispatch:
  841. # We would delete a row someone else in this pass is reading.
  842. return lib_id in dispatch_libs
  843. # Someone else in this pass will delete the row out from under us.
  844. return lib_id in consumed_libs
  845. def _claim_library_row(candidate: PrintQueueItem) -> None:
  846. lib_id = candidate.library_file_id
  847. if lib_id is None:
  848. return
  849. dispatch_libs.add(lib_id)
  850. if candidate.cleanup_library_after_dispatch:
  851. consumed_libs.add(lib_id)
  852. for item in items:
  853. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  854. if item.scheduled_time:
  855. sched = item.scheduled_time
  856. if sched.tzinfo is None:
  857. sched = sched.replace(tzinfo=timezone.utc)
  858. if sched > datetime.now(timezone.utc):
  859. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  860. continue
  861. # Skip items that require manual start
  862. if item.manual_start:
  863. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  864. continue
  865. if item.printer_id:
  866. # Held by a sensor interlock (#1148). Checked before the
  867. # busy_printers test that would otherwise swallow it
  868. # silently — "waiting for a printer" and "waiting for you
  869. # to shut the enclosure" need to read differently, and only
  870. # one of them is something the user can fix.
  871. #
  872. # The interlock is the only thing that writes a
  873. # waiting_reason on this branch — the model-based branch
  874. # nulls it at the moment it assigns a printer — so any
  875. # reason still standing once the hold lifts is stale and is
  876. # cleared here. Doing it at dispatch instead would leave a
  877. # shut door reading "Waiting on Enclosure Door" for as long
  878. # as the printer stayed busy with something else.
  879. interlock_reason = interlocked.get(item.printer_id)
  880. reason = f"Waiting on {interlock_reason}" if interlock_reason else None
  881. if item.waiting_reason != reason:
  882. item.waiting_reason = reason
  883. await db.commit()
  884. if interlock_reason:
  885. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  886. continue
  887. # Specific printer assignment (existing behavior)
  888. if item.printer_id in busy_printers:
  889. continue
  890. # Check if printer is idle
  891. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  892. printer_connected = printer_manager.is_connected(item.printer_id)
  893. # If printer not connected, try to power on via smart plug
  894. if not printer_connected:
  895. plugs = await self._get_smart_plugs(db, item.printer_id)
  896. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  897. if auto_on_plugs:
  898. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  899. # Power on using the plug that actually feeds the printer, and
  900. # wait for it to boot on that one only (#2629).
  901. primary_plug = self._pick_power_plug(auto_on_plugs)
  902. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  903. if powered_on:
  904. # Also turn on any remaining auto_on plugs (e.g., filter)
  905. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  906. try:
  907. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  908. await service.turn_on(extra_plug)
  909. logger.info(
  910. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  911. )
  912. except Exception as e:
  913. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  914. printer_connected = True
  915. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  916. else:
  917. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  918. busy_printers.add(item.printer_id)
  919. continue
  920. else:
  921. # No plug or auto_on disabled
  922. busy_printers.add(item.printer_id)
  923. continue
  924. # Check if printer is idle (busy with another print)
  925. if not printer_idle:
  926. busy_printers.add(item.printer_id)
  927. continue
  928. # Drying blocks the queue, if the user asked it to. A hold
  929. # is a skip like any other, so it belongs here with the
  930. # rest of the availability checks.
  931. if self._drying_in_progress.get(item.printer_id) and await self._get_bool_setting(
  932. db, "queue_drying_block"
  933. ):
  934. busy_printers.add(item.printer_id)
  935. continue
  936. # Check condition (previous print success)
  937. if item.require_previous_success:
  938. if not await self._check_previous_success(db, item):
  939. item.status = "skipped"
  940. item.error_message = "Previous print failed or was aborted"
  941. item.completed_at = datetime.now(timezone.utc)
  942. await db.commit()
  943. logger.info("Skipped queue item %s - previous print failed", item.id)
  944. # Send notification
  945. job_name = await self._get_job_name(db, item)
  946. printer = await self._get_printer(db, item.printer_id)
  947. await notification_service.on_queue_job_skipped(
  948. job_name=job_name,
  949. printer_id=item.printer_id,
  950. printer_name=printer.name if printer else "Unknown",
  951. reason="Previous print failed or was aborted",
  952. db=db,
  953. )
  954. continue
  955. # Resolve the AMS mapping when it's missing OR unresolved
  956. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  957. # frontend status-load race can persist [-1] (#2589) — and
  958. # must be recomputed from live trays rather than trusted.
  959. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  960. if unmappable:
  961. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  962. continue
  963. # Filament-deficit pre-dispatch check (#1496). If the
  964. # assigned spool can't satisfy any required slot grams,
  965. # promote the item to manual_start so the user must
  966. # acknowledge via the ▶ button (which re-checks live).
  967. if await self._block_on_filament_deficit(db, item):
  968. continue
  969. # Hold this item back for the next pass rather than racing
  970. # another dispatch over the same transient library row. The
  971. # printer is still marked busy so a later item does not jump
  972. # its place in this printer's queue.
  973. if _library_row_conflict(item):
  974. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  975. busy_printers.add(item.printer_id)
  976. continue
  977. # Print takes priority: stop a cycle Bambuddy armed, now
  978. # that this item is definitely going out.
  979. #
  980. # Placement is the whole point (#2801). This used to sit up
  981. # with the availability checks, inside the not-idle branch
  982. # -- so it fired only on the passes where the print was NOT
  983. # going to start, and never on the ones where it was.
  984. # Drying is not one of the things `_is_printer_idle` looks
  985. # at, so a stop could never have unblocked that printer
  986. # anyway; the cycle was spent for nothing, auto-drying
  987. # re-armed on the next tick, and a plate left
  988. # unacknowledged turned that into a loop on the scheduler
  989. # interval. Every skip between there and here -- a failed
  990. # previous print, an unmappable item, a filament deficit, a
  991. # contested library row -- is another way to lose a cycle
  992. # for a print that never happens, which is why this waits
  993. # until the decision is actually made.
  994. if self._drying_in_progress.get(
  995. item.printer_id
  996. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  997. await self._stop_drying(item.printer_id)
  998. # Queue the dispatch instead of running it here — see
  999. # _dispatch_selected(). busy_printers still gets the printer
  1000. # immediately, so nothing else in this pass can target it.
  1001. _claim_library_row(item)
  1002. dispatch_ids.append(item.id)
  1003. busy_printers.add(item.printer_id)
  1004. # SJF starvation guard: mark items that were jumped
  1005. if sjf_enabled and item.print_time_seconds is not None:
  1006. for other in items:
  1007. if (
  1008. other.id != item.id
  1009. and other.status == "pending"
  1010. and other.printer_id == item.printer_id
  1011. and not other.been_jumped
  1012. and other.position < item.position
  1013. and (
  1014. other.print_time_seconds is None
  1015. or other.print_time_seconds > item.print_time_seconds
  1016. )
  1017. ):
  1018. other.been_jumped = True
  1019. await db.commit()
  1020. elif item.target_model or item.variants:
  1021. # Model-based assignment - find any idle printer of matching model.
  1022. # A plain model-based item has exactly one candidate, built from
  1023. # its own columns. A cross-model item (#671) has one per sliced
  1024. # variant and takes the first that matches, walking them in the
  1025. # user's priority order so the pick is reproducible when more
  1026. # than one printer is free in the same pass.
  1027. candidates = _candidates_for(item)
  1028. printer_id = None
  1029. chosen: _ModelCandidate | None = None
  1030. per_model_reasons: list[tuple[str | None, str]] = []
  1031. # Candidates that cleared the cross-model gate below. The
  1032. # smart-plug wake step may only consider these — waking a
  1033. # printer for a file that can never legally run on it is
  1034. # worse than not waking at all (#2786).
  1035. wakeable_candidates: list[_ModelCandidate] = []
  1036. if not candidates:
  1037. # Every candidate file has been deleted or trashed out from
  1038. # under this item. Hold it with something the user can act
  1039. # on rather than letting it look dispatchable forever.
  1040. per_model_reasons.append(
  1041. (
  1042. item.target_model,
  1043. "Every file for this job has been deleted — add a file back or remove the item",
  1044. )
  1045. )
  1046. for candidate in candidates:
  1047. # Parse required filament types if present
  1048. required_types = None
  1049. if candidate.required_filament_types:
  1050. try:
  1051. required_types = json.loads(candidate.required_filament_types)
  1052. except json.JSONDecodeError:
  1053. pass # Ignore malformed filament types; treat as no constraint
  1054. # Parse filament overrides if present
  1055. filament_overrides = None
  1056. if candidate.filament_overrides:
  1057. try:
  1058. filament_overrides = json.loads(candidate.filament_overrides)
  1059. except json.JSONDecodeError:
  1060. pass
  1061. # If overrides exist, use override types for validation instead
  1062. effective_types = required_types
  1063. if filament_overrides:
  1064. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  1065. if override_types:
  1066. # Merge: keep original types for non-overridden slots, add override types
  1067. effective_types = sorted(set(required_types or []) | set(override_types))
  1068. # Cross-model safety gate (#2578): never hand a 3MF sliced
  1069. # for an incompatible model to a printer, no matter how the
  1070. # row got into the DB (old rows, direct API writes). Held
  1071. # as pending with an actionable waiting_reason — the user
  1072. # fixes it by editing the item's target model.
  1073. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  1074. per_model_reasons.append(
  1075. (
  1076. candidate.target_model,
  1077. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  1078. f"{candidate.target_model} — edit the item and fix its target model",
  1079. )
  1080. )
  1081. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  1082. continue
  1083. wakeable_candidates.append(candidate)
  1084. match_id, match_reason = await self._find_idle_printer_for_model(
  1085. db,
  1086. candidate.target_model,
  1087. # Sensor-held printers are unavailable to the
  1088. # matcher but stay out of busy_printers itself
  1089. # (#1148) — see where `interlocked` is built.
  1090. busy_printers | interlocked.keys(),
  1091. effective_types,
  1092. item.target_location,
  1093. filament_overrides=filament_overrides,
  1094. require_plate_clear=require_plate_clear,
  1095. wakeable_ids=wakeable_printer_ids,
  1096. )
  1097. if match_id:
  1098. printer_id = match_id
  1099. chosen = candidate
  1100. break
  1101. per_model_reasons.append((candidate.target_model, match_reason or ""))
  1102. # Nothing is available and nothing has been woken this pass:
  1103. # switch one matching printer on. Assignment is left to the
  1104. # next pass, which sees the booted printer's live state
  1105. # instead of guessing at it seconds after connect (#2786).
  1106. if printer_id is None and not power_on_attempted and wakeable_candidates:
  1107. woken_id, attempted_id = await self._wake_printer_for_model(
  1108. db,
  1109. wakeable_candidates,
  1110. item.target_location,
  1111. busy_printers | interlocked.keys(),
  1112. wakeable_printer_ids,
  1113. require_plate_clear,
  1114. )
  1115. # An attempt spends the pass's one wake whether or not
  1116. # it worked: it has already blocked the queue loop for
  1117. # the boot wait. A failed printer is held out of later
  1118. # passes by its own cool-off, deliberately NOT by
  1119. # busy_printers — it is off, not busy, and labelling it
  1120. # busy would both misdescribe it in every later item's
  1121. # waiting reason and suppress the notification, since
  1122. # an all-busy reason is treated as needing no action.
  1123. power_on_attempted = attempted_id is not None
  1124. if woken_id is not None:
  1125. # Hold this item back rather than dispatching onto a
  1126. # printer whose AMS has not reported yet.
  1127. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  1128. continue
  1129. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  1130. # Fold the winning variant's file and settings onto the item
  1131. # before anything else looks at them — the guards below and
  1132. # every step of the dispatch read the item's own columns.
  1133. if chosen is not None:
  1134. self._resolve_variant(item, chosen)
  1135. # Update waiting_reason if changed and send notification when first waiting
  1136. if item.waiting_reason != waiting_reason:
  1137. was_waiting = item.waiting_reason is not None
  1138. item.waiting_reason = waiting_reason
  1139. await db.commit()
  1140. # Send waiting notification only when transitioning to waiting state
  1141. # and the reason requires user action (not just "all printers busy")
  1142. if waiting_reason and not was_waiting and not self._is_busy_only(waiting_reason):
  1143. job_name = await self._get_job_name(db, item)
  1144. await notification_service.on_queue_job_waiting(
  1145. job_name=job_name,
  1146. target_model=_candidate_model_label(candidates) or item.target_model,
  1147. waiting_reason=waiting_reason,
  1148. db=db,
  1149. )
  1150. if printer_id:
  1151. # Before claiming the printer: hold back rather than race
  1152. # another dispatch over the same transient library row.
  1153. # Checked here so a held item does not get a printer
  1154. # assigned and then sit on it. See _library_row_conflict().
  1155. #
  1156. # No busy_printers.add() here, unlike the fixed-printer
  1157. # branch above: that one protects its printer's own queue
  1158. # ordering, but this item was never assigned to `printer_id`
  1159. # — the matcher merely offered it. Marking it busy would
  1160. # strand an idle printer for the rest of the pass.
  1161. if _library_row_conflict(item):
  1162. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  1163. continue
  1164. # Check condition (previous print success) before assigning
  1165. if item.require_previous_success:
  1166. if not await self._check_previous_success(db, item):
  1167. item.status = "skipped"
  1168. item.error_message = "Previous print failed or was aborted"
  1169. item.completed_at = datetime.now(timezone.utc)
  1170. await db.commit()
  1171. logger.info("Skipped queue item %s - previous print failed", item.id)
  1172. # Send notification
  1173. job_name = await self._get_job_name(db, item)
  1174. printer = await self._get_printer(db, printer_id)
  1175. await notification_service.on_queue_job_skipped(
  1176. job_name=job_name,
  1177. printer_id=printer_id,
  1178. printer_name=printer.name if printer else "Unknown",
  1179. reason="Previous print failed or was aborted",
  1180. db=db,
  1181. )
  1182. continue
  1183. # Assign printer and start - clear waiting reason
  1184. item.printer_id = printer_id
  1185. item.waiting_reason = None
  1186. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  1187. # Send assignment notification
  1188. job_name = await self._get_job_name(db, item)
  1189. printer = await self._get_printer(db, printer_id)
  1190. await notification_service.on_queue_job_assigned(
  1191. job_name=job_name,
  1192. printer_id=printer_id,
  1193. printer_name=printer.name if printer else "Unknown",
  1194. target_model=item.target_model,
  1195. db=db,
  1196. )
  1197. # Resolve the AMS mapping for the assigned printer when it's
  1198. # missing OR unresolved (all -1). Critical for model-based
  1199. # jobs where mapping wasn't computed upfront, and it also
  1200. # self-heals a bogus stored [-1] (#2589).
  1201. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  1202. if unmappable:
  1203. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  1204. continue
  1205. # Filament-deficit pre-dispatch check (#1496).
  1206. if await self._block_on_filament_deficit(db, item):
  1207. continue
  1208. _claim_library_row(item)
  1209. dispatch_ids.append(item.id)
  1210. busy_printers.add(printer_id)
  1211. # SJF starvation guard: mark model-based items that were jumped
  1212. if sjf_enabled and item.print_time_seconds is not None:
  1213. for other in items:
  1214. if (
  1215. other.id != item.id
  1216. and other.status == "pending"
  1217. and other.printer_id is None
  1218. and other.target_model
  1219. and other.target_model.upper() == item.target_model.upper()
  1220. and not other.been_jumped
  1221. and other.position < item.position
  1222. and (
  1223. other.print_time_seconds is None
  1224. or other.print_time_seconds > item.print_time_seconds
  1225. )
  1226. ):
  1227. other.been_jumped = True
  1228. await db.commit()
  1229. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  1230. # as long as the slowest upload takes (minutes on a big 3MF), and a
  1231. # skip summary that only lands after the transfers have finished is
  1232. # useless for working out why an item did not go out.
  1233. if skip_reasons:
  1234. logger.info("Queue skip summary: %s", skip_reasons)
  1235. if busy_printers:
  1236. # Log why each printer was busy (first time it was checked)
  1237. for pid in busy_printers:
  1238. state = printer_manager.get_status(pid)
  1239. connected = printer_manager.is_connected(pid)
  1240. awaiting = printer_manager.is_awaiting_plate_clear(pid)
  1241. state_name = state.state if state else "NO_STATUS"
  1242. logger.info(
  1243. "Queue: printer %d not available — connected=%s, state=%s, awaiting_plate_clear=%s",
  1244. pid,
  1245. connected,
  1246. state_name,
  1247. awaiting,
  1248. )
  1249. # Keep-warm is a comfort feature; dispatch is not. It sits between
  1250. # selection and `_launch_uploads`, so anything raising here would
  1251. # discard this tick's selections — computed AMS mappings and all —
  1252. # and, on a persistent fault, stop the queue dispatching entirely.
  1253. # Same reasoning as the deficit check's guard below: never let an
  1254. # auxiliary check wedge the queue. The bed simply stays wherever it
  1255. # was, and the next tick tries again.
  1256. try:
  1257. await self._apply_keep_warm(db, items, dispatch_ids, busy_printers, require_plate_clear)
  1258. except Exception as e:
  1259. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  1260. # Read the concurrency limit BEFORE the commit below, not inside
  1261. # _dispatch_selected(). A SELECT on this session after the commit
  1262. # implicitly opens a fresh transaction that nothing then closes, and
  1263. # it would stay open for the whole dispatch — minutes of "idle in
  1264. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  1265. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  1266. # checkpointed while every dispatch is writing to it.
  1267. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  1268. # Selection is done; every decision above is recorded on `db`
  1269. # (model-based printer assignment, computed ams_mapping). Flush it
  1270. # before the dispatch tasks open their own sessions, or they will
  1271. # read a row that still says printer_id=None. This also releases the
  1272. # connection back to the pool for the duration of the dispatch.
  1273. await db.commit()
  1274. if dispatch_ids:
  1275. item_printers = {it.id: it.printer_id for it in items}
  1276. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  1277. # Auto-drying: start drying on idle printers that have no pending queue items
  1278. await self._check_auto_drying(db, items, dispatching_printers)
  1279. # Keep the loop on the fast interval while any upload is in flight so
  1280. # a slot freed mid-tick refills within seconds rather than after the
  1281. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  1282. # deferred because the pool was full) also counts as productive.
  1283. return bool(dispatch_ids) or bool(self._inflight)
  1284. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  1285. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  1286. Dispatch used to happen inline in the selection loop: ``await
  1287. _start_print(db, item)`` per item in turn. Since ``_start_print``
  1288. performs the FTP upload, that serialized every printer behind every
  1289. other printer's transfer even though the printers are independent
  1290. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  1291. gather was awaited before ``check_queue`` returned, so the run loop
  1292. stayed blocked until the *slowest* upload in the batch finished — a
  1293. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  1294. 93-printer farm even as other printers came free (#2602).
  1295. Each upload now runs as an independent background task tracked in
  1296. ``self._inflight``. check_queue excludes in-flight item_ids (still
  1297. `pending` until their upload completes) and their printers from the
  1298. next pass's selection, and this method launches at most
  1299. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  1300. the next fast tick instead of waiting out the whole batch. The bound
  1301. exists because the printers are independent but the host is not: each
  1302. in-flight upload holds a thread in the FTP pool, a TLS session and a
  1303. file handle.
  1304. The no-overlapping-dispatch invariant the batch-await used to provide
  1305. is now carried by the in-flight exclusion in check_queue. Everything
  1306. else — the pending->printing CAS, the busy-printer guard (#2598), the
  1307. per-printer hold, and each item's independent failure handling — still
  1308. lives in ``_start_print`` and runs per task exactly as before.
  1309. Synchronous on purpose: it registers every launched task into
  1310. ``self._inflight`` before returning, so the next (sequential) tick sees
  1311. an accurate in-flight count with no interleaving await.
  1312. """
  1313. free = limit - len(self._inflight)
  1314. if free <= 0:
  1315. logger.info(
  1316. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  1317. len(self._inflight),
  1318. limit,
  1319. len(item_ids),
  1320. item_ids,
  1321. )
  1322. return
  1323. to_launch = item_ids[:free]
  1324. deferred = item_ids[free:]
  1325. logger.info(
  1326. "Launching %d upload(s) (pool %d/%d in flight)%s",
  1327. len(to_launch),
  1328. len(self._inflight),
  1329. limit,
  1330. f" — deferring {deferred} to a later tick" if deferred else "",
  1331. )
  1332. for item_id in to_launch:
  1333. task = spawn_background_task(
  1334. self._dispatch_one(item_id, item_printers.get(item_id)),
  1335. name=f"queue-upload-{item_id}",
  1336. )
  1337. self._inflight[item_id] = (task, item_printers.get(item_id))
  1338. # Prune on completion so the freed slot is refillable next tick.
  1339. # spawn_background_task already logs any uncaught exception; this
  1340. # only reclaims the pool slot (fires on success, failure, or cancel).
  1341. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  1342. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  1343. """Upload + start one queue item in its own session (pool worker, #2602).
  1344. Its own session: pool workers run concurrently and an AsyncSession is
  1345. not safe to share across tasks; it also keeps a slow upload from pinning
  1346. the scheduler's session (and, on SQLite, its transaction) open for the
  1347. transfer's duration.
  1348. ``selected_printer_id`` is the printer this item was selected for, taken
  1349. from the same snapshot the caller used. It exists so the preheat pin can
  1350. be unwound on the paths that never reach the ``finally`` below — see the
  1351. claim failure a few lines down. Optional so the direct-call tests keep
  1352. working; when it is absent those paths simply behave as they did before.
  1353. """
  1354. async with async_session() as item_db:
  1355. # Claim the row for dispatch BEFORE reading the printer snapshot or
  1356. # touching any slow I/O (#2615). The claim is an atomic CAS on
  1357. # (status='pending', dispatching_at IS NULL); while it's held the edit
  1358. # routes reject reassignment (409), so printer_id can't change out from
  1359. # under the in-flight upload and split the queue row from the
  1360. # archive/expected-print/physical command.
  1361. if not await self._claim_for_dispatch(item_db, item_id):
  1362. logger.info(
  1363. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  1364. item_id,
  1365. )
  1366. # This return is outside the try/finally below, so the rollback
  1367. # has to happen here. Selecting this item already handed any
  1368. # keep-warm hold on its printer over to the preheat pin
  1369. # (`_sweep_keep_warm`), on the promise that this dispatch would
  1370. # unwind it. Bailing without doing so leaves the bed hot with
  1371. # nothing tracking it: the keep-warm entry is gone, so the
  1372. # max-duration cap no longer applies, and if this was the
  1373. # printer's last pending item nothing else will ever turn it
  1374. # off. Reachable whenever a cancel or delete lands between
  1375. # selection and the claim.
  1376. if selected_printer_id is not None:
  1377. self._rollback_preheat_pin(item_id, selected_printer_id)
  1378. return
  1379. # Seeded from the caller's snapshot so the `item vanished` return
  1380. # below still unwinds the pin; overwritten with the row's own
  1381. # printer_id as soon as we have it.
  1382. item_printer_id: int | None = selected_printer_id
  1383. try:
  1384. item = await item_db.get(PrintQueueItem, item_id)
  1385. if not item:
  1386. logger.info("Queue item %s vanished after claim — skipping", item_id)
  1387. return
  1388. item_printer_id = item.printer_id
  1389. await self._start_print(item_db, item)
  1390. finally:
  1391. # Undo an expected-print registration whose print command never
  1392. # went out. One choke point covers every way `_start_print` can
  1393. # end without sending: a raised exception (a DB failure mid-
  1394. # dispatch is the reported case), an early return, a cancel
  1395. # winning the #1853 CAS, or `start_print()` returning False.
  1396. # A confirmed send removes the entry itself, so this is a no-op
  1397. # on the happy path.
  1398. self._rollback_unconfirmed_expected_print(item_id)
  1399. # Mirror the pre-#1625 background-dispatch lifecycle: a
  1400. # reservation survives only after start_print() accepted the
  1401. # command. Failure, cancellation, deferral, and exceptions all
  1402. # release it here.
  1403. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  1404. # Unwind preheat state (bed/chamber/airduct) if the
  1405. # dispatch aborted before the print's own gcode took over.
  1406. # `_start_print` clears the pin on successful `start_print()`;
  1407. # anything still present here is by definition an aborted
  1408. # dispatch and gets rolled back so the printer isn't left
  1409. # heating for a job that isn't happening.
  1410. if item_printer_id is not None:
  1411. self._rollback_preheat_pin(item_id, item_printer_id)
  1412. # The cancellation flag only has meaning while this dispatch is
  1413. # running; drop it so the set cannot grow without bound and a
  1414. # re-queued item never inherits a stale cancellation.
  1415. self._cancelled_dispatches.discard(item_id)
  1416. # Release the claim on every exit. Once dispatch has finished the
  1417. # row's status carries the lock (printing/failed/cancelled are all
  1418. # != pending), so the token is only needed for the duration of the
  1419. # upload. A row left pending (e.g. busy-printer deferral) becomes
  1420. # dispatchable again on the next tick.
  1421. await self._clear_dispatch_claim(item_db, item_id)
  1422. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  1423. """Drop an expectation for a print command that was never sent.
  1424. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  1425. where the interesting exception is usually the one already propagating.
  1426. """
  1427. pending = self._unconfirmed_expected_print.pop(item_id, None)
  1428. if pending is None:
  1429. return
  1430. printer_id, remote_filename, archive_id = pending
  1431. try:
  1432. from backend.app.main import unregister_expected_print
  1433. unregister_expected_print(printer_id, remote_filename, archive_id)
  1434. except Exception:
  1435. logger.warning(
  1436. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  1437. item_id,
  1438. printer_id,
  1439. remote_filename,
  1440. archive_id,
  1441. exc_info=True,
  1442. )
  1443. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  1444. """Release a queue reservation without touching the dispatch session."""
  1445. if item_id not in self._unconfirmed_budget_reservations:
  1446. return
  1447. for attempt in range(1, 4):
  1448. async with async_session() as cleanup_db:
  1449. try:
  1450. await release_budget_reservation(
  1451. cleanup_db,
  1452. source_type="print_queue",
  1453. source_id=item_id,
  1454. status="released",
  1455. )
  1456. await cleanup_db.commit()
  1457. self._unconfirmed_budget_reservations.discard(item_id)
  1458. return
  1459. except Exception as exc:
  1460. try:
  1461. await cleanup_db.rollback()
  1462. except Exception:
  1463. pass
  1464. if attempt == 3:
  1465. logger.error(
  1466. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  1467. item_id,
  1468. attempt,
  1469. exc,
  1470. )
  1471. return
  1472. await asyncio.sleep(0.5 * attempt)
  1473. @staticmethod
  1474. def _reported_bed_target(printer_id: int) -> int | None:
  1475. """The bed target firmware currently reports, or None if it can't be read.
  1476. None means "no evidence", not "zero" — callers must not treat it as a
  1477. temperature. Deliberately total: this feeds cleanup paths that run in a
  1478. ``finally``, where a malformed status must not become the exception the
  1479. caller sees.
  1480. """
  1481. try:
  1482. state = printer_manager.get_status(printer_id)
  1483. if state is None:
  1484. return None
  1485. temps = state.temperatures
  1486. if not isinstance(temps, dict):
  1487. return None
  1488. return int(float(temps.get("bed_target", 0) or 0))
  1489. except (TypeError, ValueError, AttributeError):
  1490. return None
  1491. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  1492. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  1493. Turns the bed heater off, the chamber heater off, and opens the
  1494. airduct flap back to cooling — for whichever of those preheat
  1495. actually applied. `_start_print` clears the pin on successful
  1496. `start_print()`; anything still present when `_dispatch_one` exits
  1497. is by definition an aborted dispatch and gets rolled back here.
  1498. The bed is the one action that can be declined: if firmware has since
  1499. been given a target other than the one we pinned, it belongs to someone
  1500. else and is left alone. See the comment at that branch.
  1501. Also called directly from `_dispatch_one`'s claim-failure return, which
  1502. never reaches the ``finally``.
  1503. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  1504. """
  1505. pin = self._preheat_pin.pop(printer_id, set())
  1506. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  1507. if not pin:
  1508. return
  1509. client = printer_manager.get_client(printer_id)
  1510. if client is None:
  1511. logger.info(
  1512. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  1513. item_id,
  1514. printer_id,
  1515. )
  1516. return
  1517. if "bed" in pin:
  1518. # Only undo our own target. If firmware reports something else, the
  1519. # user or another writer owns the bed now and zeroing it would
  1520. # clobber their choice -- the same guard `_release_keep_warm`
  1521. # applies to a keep-warm hold.
  1522. #
  1523. # Every uncertain case switches the bed off rather than leaving it:
  1524. # no recorded target (a pin written before this bookkeeping, or a
  1525. # setter that raised after pinning) and an unreadable status both
  1526. # fall through. A bed left hot with no owner is the worse failure,
  1527. # and this runs in a `finally` where raising would mask the real
  1528. # exception.
  1529. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  1530. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  1531. logger.info(
  1532. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  1533. item_id,
  1534. printer_id,
  1535. cur_bed_target,
  1536. pinned_bed,
  1537. )
  1538. else:
  1539. try:
  1540. client.set_bed_temperature(0)
  1541. except Exception as exc:
  1542. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  1543. if "chamber" in pin:
  1544. try:
  1545. client.set_chamber_temperature(0)
  1546. except Exception as exc:
  1547. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  1548. if "airduct" in pin:
  1549. try:
  1550. client.set_airduct_mode("cooling")
  1551. except Exception as exc:
  1552. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  1553. logger.info(
  1554. "Dispatch item %s (printer %d): preheat rollback → %s",
  1555. item_id,
  1556. printer_id,
  1557. sorted(pin),
  1558. )
  1559. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int) -> bool:
  1560. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  1561. Returns True if this call won the claim, False if the row was already
  1562. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  1563. the load-bearing guard against reassign-during-dispatch (#2615)."""
  1564. res = await db.execute(
  1565. update(PrintQueueItem)
  1566. .where(PrintQueueItem.id == item_id)
  1567. .where(PrintQueueItem.status == "pending")
  1568. .where(PrintQueueItem.dispatching_at.is_(None))
  1569. .values(dispatching_at=datetime.now(timezone.utc))
  1570. )
  1571. await db.commit()
  1572. return res.rowcount > 0
  1573. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  1574. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  1575. mask the dispatch outcome.
  1576. Retried, because the failure mode in practice is transient and narrow: a
  1577. database that is momentarily unreachable — PostgreSQL out of connection
  1578. slots is the observed case — refuses this write for a second or two while
  1579. the dispatch that just ended is still holding the row out of the selection
  1580. query. One attempt was enough to wedge the item; a couple of spaced
  1581. attempts clear it. Each attempt rolls back first, since a failed write
  1582. leaves the session needing it before it can be reused.
  1583. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  1584. on the next quiet tick.
  1585. """
  1586. for attempt in range(1, 4):
  1587. try:
  1588. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  1589. await db.commit()
  1590. return
  1591. except Exception as exc:
  1592. try:
  1593. await db.rollback()
  1594. except Exception:
  1595. pass
  1596. if attempt == 3:
  1597. logger.warning(
  1598. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  1599. "— a later quiet tick will release it",
  1600. item_id,
  1601. attempt,
  1602. exc,
  1603. )
  1604. return
  1605. await asyncio.sleep(0.5 * attempt)
  1606. async def _printers_for_model(
  1607. self,
  1608. db: AsyncSession,
  1609. model: str,
  1610. target_location: str | None = None,
  1611. ) -> list[Printer]:
  1612. """Active printers of *model*, optionally narrowed to one location.
  1613. Shared by the matcher and by the smart-plug wake step (#2786) so both
  1614. answer "which printers can this job run on" from one query — a job can
  1615. only be woken onto a printer the matcher would also have considered.
  1616. """
  1617. normalized_model = normalize_printer_model(model) or model
  1618. query = (
  1619. select(Printer)
  1620. .where(func.lower(Printer.model) == normalized_model.lower())
  1621. .where(Printer.is_active == True) # noqa: E712
  1622. )
  1623. if target_location:
  1624. query = query.where(Printer.location == target_location)
  1625. result = await db.execute(query)
  1626. return list(result.scalars().all())
  1627. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  1628. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  1629. Read once per queue check rather than per printer: it decides both
  1630. whether the wake step has anything to do and how an offline printer is
  1631. worded in the waiting reason — "Offline" and "offline with no Auto On
  1632. plug" are different problems, and the second is the one the user has to
  1633. fix themselves (#2786).
  1634. """
  1635. result = await db.execute(
  1636. select(SmartPlug.printer_id)
  1637. .where(SmartPlug.printer_id.is_not(None))
  1638. .where(SmartPlug.enabled == True) # noqa: E712
  1639. .where(SmartPlug.auto_on == True) # noqa: E712
  1640. )
  1641. return {pid for (pid,) in result.all() if pid is not None}
  1642. def _wake_recently_failed(self, printer_id: int) -> bool:
  1643. """True while this printer's failed power-on is still cooling off (#2786)."""
  1644. deadline = self._wake_failures.get(printer_id)
  1645. if deadline is None:
  1646. return False
  1647. if time.monotonic() >= deadline:
  1648. del self._wake_failures[printer_id]
  1649. return False
  1650. return True
  1651. async def _wake_printer_for_model(
  1652. self,
  1653. db: AsyncSession,
  1654. candidates: list[_ModelCandidate],
  1655. target_location: str | None,
  1656. exclude_ids: set[int],
  1657. wakeable_ids: set[int],
  1658. require_plate_clear: bool,
  1659. ) -> tuple[int | None, int | None]:
  1660. """Power on one offline printer a model-based item could run on (#2786).
  1661. The fixed-printer branch has powered a printer on since smart plugs
  1662. existed. The model-based branch never could: its matcher drops an
  1663. offline printer into the "Offline:" waiting reason and nothing looks at
  1664. its plugs, so a class-targeted job with every matching printer switched
  1665. off sat pending forever. The reporter's log is the controlled
  1666. experiment — the same item, same plug, same Auto On setting, dispatched
  1667. the moment they edited it onto a specific printer.
  1668. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  1669. power-on was actually tried, so the caller can tell "nothing here was
  1670. wakeable" (both None — cheap, other items may still find something)
  1671. from "we tried and it did not come up" (only ``attempted_id`` — the
  1672. boot timeout has already been spent).
  1673. Deliberately does NOT go on to match the job: AMS trays arrive with the
  1674. first status push after connect, so a filament check against a printer
  1675. that booted seconds ago can reject the printer we just woke. The next
  1676. queue pass matches it with live state.
  1677. At most one printer per pass. Each wake blocks the queue loop for the
  1678. boot wait, and a queue of ten class-targeted jobs must not switch on
  1679. ten printers inside one check.
  1680. """
  1681. for candidate in candidates:
  1682. if not candidate.target_model:
  1683. continue
  1684. printers = await self._printers_for_model(db, candidate.target_model, target_location)
  1685. for printer in sorted(printers, key=lambda p: p.id):
  1686. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  1687. continue
  1688. if printer_manager.is_connected(printer.id):
  1689. continue
  1690. if self._wake_recently_failed(printer.id):
  1691. # Its plug did not bring it back a moment ago. Move on to a
  1692. # sibling instead of spending this pass — and every pass —
  1693. # on the same printer.
  1694. continue
  1695. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  1696. # Waking this one buys nothing: it would boot into IDLE and
  1697. # then be held by the plate-clear gate, which is exactly
  1698. # what the reporter's log shows happening for 80 minutes
  1699. # after a fixed-printer wake. The flag is Bambuddy-side and
  1700. # persisted, so it is readable while the printer is off.
  1701. logger.info(
  1702. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  1703. printer.id,
  1704. candidate.target_model,
  1705. )
  1706. continue
  1707. plugs = await self._get_smart_plugs(db, printer.id)
  1708. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1709. if not auto_on_plugs:
  1710. # wakeable_ids said otherwise — the plug changed under us
  1711. # mid-pass. Nothing to do but move on.
  1712. continue
  1713. logger.info(
  1714. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  1715. candidate.target_model,
  1716. printer.id,
  1717. )
  1718. primary_plug = self._pick_power_plug(auto_on_plugs)
  1719. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  1720. logger.warning(
  1721. "Could not power on printer %s via smart plug; not trying it again for %ss",
  1722. printer.id,
  1723. self._wake_failure_cooloff,
  1724. )
  1725. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  1726. return None, printer.id
  1727. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1728. try:
  1729. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1730. await service.turn_on(extra_plug)
  1731. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  1732. except Exception as e:
  1733. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1734. return printer.id, printer.id
  1735. return None, None
  1736. async def _find_idle_printer_for_model(
  1737. self,
  1738. db: AsyncSession,
  1739. model: str,
  1740. exclude_ids: set[int],
  1741. required_filament_types: list[str] | None = None,
  1742. target_location: str | None = None,
  1743. filament_overrides: list[dict] | None = None,
  1744. require_plate_clear: bool = True,
  1745. wakeable_ids: set[int] | None = None,
  1746. ) -> tuple[int | None, str | None]:
  1747. """Find an idle, connected printer matching the model with compatible filaments.
  1748. Args:
  1749. db: Database session
  1750. model: Printer model to match (e.g., "X1C", "P1S")
  1751. exclude_ids: Printer IDs to exclude (already busy)
  1752. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  1753. If provided, only printers with all required types loaded will match.
  1754. target_location: Optional location filter. If provided, only printers in this location are considered.
  1755. filament_overrides: Optional list of override dicts. Each entry may include
  1756. ``force_color_match: true`` to require an exact type+color match
  1757. on the printer for that slot. Without the flag the existing
  1758. colour-preference logic applies.
  1759. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  1760. offline printer is worded: one Bambuddy will switch on reads
  1761. differently from one the user has to go and switch on themselves.
  1762. Returns:
  1763. Tuple of (printer_id, waiting_reason):
  1764. - (printer_id, None) if a matching printer was found
  1765. - (None, reason) if no printer is available, with explanation
  1766. """
  1767. normalized_model = normalize_printer_model(model) or model
  1768. printers = await self._printers_for_model(db, model, target_location)
  1769. location_suffix = f" in {target_location}" if target_location else ""
  1770. if not printers:
  1771. return None, f"No active {normalized_model} printers{location_suffix} configured"
  1772. # Separate force-matched overrides from preference-only overrides
  1773. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  1774. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  1775. # Track reasons for skipping printers
  1776. printers_busy = []
  1777. printers_offline = []
  1778. printers_offline_no_plug = []
  1779. printers_missing_filament: list[tuple[str, list[str]]] = []
  1780. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  1781. for printer in printers:
  1782. if printer.id in exclude_ids:
  1783. # Printer is already claimed by another job in this scheduling run.
  1784. # For force-color jobs, still check if the color would match — if not,
  1785. # report it as a color mismatch rather than plain "Busy" so the user
  1786. # knows the job needs a filament change, not just to wait for availability.
  1787. if force_overrides and not pref_overrides:
  1788. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  1789. if missing_colors:
  1790. printers_missing_filament.append((printer.name, missing_colors))
  1791. continue
  1792. printers_busy.append(printer.name)
  1793. continue
  1794. is_connected = printer_manager.is_connected(printer.id)
  1795. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  1796. if not is_connected:
  1797. if wakeable_ids is not None and printer.id not in wakeable_ids:
  1798. printers_offline_no_plug.append(printer.name)
  1799. else:
  1800. printers_offline.append(printer.name)
  1801. continue
  1802. if not is_idle:
  1803. # Printer is currently printing. For force-color jobs, check whether the
  1804. # loaded color would satisfy the requirement — if not, surface it as a
  1805. # color-mismatch reason rather than plain "Busy" so the user understands
  1806. # that the job is waiting for a filament change, not just printer availability.
  1807. if force_overrides and not pref_overrides:
  1808. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  1809. if missing_colors:
  1810. printers_missing_filament.append((printer.name, missing_colors))
  1811. logger.debug(
  1812. "Printer %s (%s) is busy but also has wrong force-color: %s",
  1813. printer.id,
  1814. printer.name,
  1815. missing_colors,
  1816. )
  1817. continue
  1818. printers_busy.append(printer.name)
  1819. continue
  1820. # Validate filament compatibility if required types are specified
  1821. if required_filament_types:
  1822. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  1823. if missing:
  1824. # When force_overrides are present, enrich missing entries with color info
  1825. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  1826. if force_overrides:
  1827. force_color_map = {
  1828. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  1829. for o in force_overrides
  1830. }
  1831. missing_enriched = [
  1832. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  1833. for t in missing
  1834. ]
  1835. printers_missing_filament.append((printer.name, missing_enriched))
  1836. else:
  1837. printers_missing_filament.append((printer.name, missing))
  1838. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  1839. continue
  1840. # Force color match: ALL flagged slots must have an exact type+color match
  1841. if force_overrides:
  1842. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  1843. if missing_colors:
  1844. printers_missing_filament.append((printer.name, missing_colors))
  1845. logger.debug(
  1846. "Skipping printer %s (%s) - missing force-matched colors: %s",
  1847. printer.id,
  1848. printer.name,
  1849. missing_colors,
  1850. )
  1851. continue
  1852. # If preference-only overrides exist, rank by color matches (existing behaviour)
  1853. if pref_overrides:
  1854. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  1855. if color_matches > 0:
  1856. candidates.append((printer.id, color_matches))
  1857. else:
  1858. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  1859. printers_missing_filament.append((printer.name, override_colors))
  1860. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  1861. continue
  1862. elif force_overrides:
  1863. # Passed all force checks — immediately eligible (no preference ordering needed)
  1864. return printer.id, None
  1865. else:
  1866. # No overrides at all - take first available (existing behavior)
  1867. return printer.id, None
  1868. # If we have candidates from preference override matching, pick the one with most color matches
  1869. if candidates:
  1870. candidates.sort(key=lambda c: c[1], reverse=True)
  1871. return candidates[0][0], None
  1872. # Build waiting reason from what we found
  1873. reasons = []
  1874. if printers_missing_filament:
  1875. # Filament/color mismatch is most actionable - show first
  1876. if force_overrides and not pref_overrides:
  1877. # All mismatches are force-color failures — use descriptive message only;
  1878. # but only if there are no busy printers that DO have the matching color.
  1879. # If a printer has the right color but is busy, surface "Busy" instead so
  1880. # the user knows the job will start automatically once that printer is free.
  1881. if not printers_busy:
  1882. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  1883. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  1884. # else: fall through — printers_busy will be appended below
  1885. else:
  1886. names_and_missing = [
  1887. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  1888. ]
  1889. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  1890. if printers_busy:
  1891. reasons.append(f"Busy: {', '.join(printers_busy)}")
  1892. if printers_offline:
  1893. reasons.append(f"Offline: {', '.join(printers_offline)}")
  1894. if printers_offline_no_plug:
  1895. # Named separately because it is the one entry on this list the
  1896. # user has to act on: no enabled Auto On plug means Bambuddy will
  1897. # never power this printer on for the queue (#2786).
  1898. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  1899. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  1900. @staticmethod
  1901. def _is_busy_only(waiting_reason: str) -> bool:
  1902. """Check if the waiting reason only contains 'Busy' entries.
  1903. When all matching printers are simply busy printing, the queued job
  1904. will start automatically once a printer finishes — no user action
  1905. is required, so we skip the notification.
  1906. """
  1907. parts = [p.strip() for p in waiting_reason.split(" | ")]
  1908. return all(p.startswith("Busy:") for p in parts)
  1909. def _get_missing_force_color_slots(self, printer_id: int, force_overrides: list[dict]) -> list[str]:
  1910. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  1911. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  1912. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  1913. with an exact type+color match.
  1914. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  1915. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  1916. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  1917. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  1918. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  1919. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  1920. setups are unaffected.
  1921. Returns:
  1922. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  1923. """
  1924. status = printer_manager.get_status(printer_id)
  1925. if not status:
  1926. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  1927. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  1928. loaded: list[tuple[str, str, str]] = []
  1929. for ams_unit in status.raw_data.get("ams", []):
  1930. for tray in ams_unit.get("tray", []):
  1931. tray_type = tray.get("tray_type")
  1932. if tray_type:
  1933. color_norm = (tray.get("tray_color", "") or "").replace("#", "").lower()[:6]
  1934. loaded.append(
  1935. (_canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or "")
  1936. )
  1937. for vt in status.raw_data.get("vt_tray") or []:
  1938. vt_type = vt.get("tray_type")
  1939. if vt_type:
  1940. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  1941. loaded.append((_canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  1942. missing = []
  1943. for o in force_overrides:
  1944. o_type = _canonical_filament_type(o.get("type") or "")
  1945. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  1946. o_idx = o.get("tray_info_idx") or ""
  1947. satisfied = any(
  1948. t_type == o_type and t_color == o_color and (not o_idx or not t_idx or o_idx == t_idx)
  1949. for t_type, t_color, t_idx in loaded
  1950. )
  1951. if not satisfied:
  1952. color_label = o.get("color_name") or o.get("color", "?")
  1953. missing.append(f"{o_type} ({color_label})")
  1954. return missing
  1955. def _get_missing_filament_types(self, printer_id: int, required_types: list[str]) -> list[str]:
  1956. """Get the list of required filament types that are not loaded on the printer.
  1957. Args:
  1958. printer_id: The printer ID
  1959. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  1960. Returns:
  1961. List of missing filament types (empty if all are loaded)
  1962. """
  1963. status = printer_manager.get_status(printer_id)
  1964. if not status:
  1965. return required_types # Can't determine, assume all missing
  1966. # Collect all filament types loaded on this printer (AMS units + external spool)
  1967. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  1968. loaded_types: set[str] = set()
  1969. # Check AMS units (stored in raw_data["ams"])
  1970. ams_data = status.raw_data.get("ams", [])
  1971. if ams_data:
  1972. for ams_unit in ams_data:
  1973. for tray in ams_unit.get("tray", []):
  1974. tray_type = tray.get("tray_type")
  1975. if tray_type:
  1976. loaded_types.add(_canonical_filament_type(tray_type))
  1977. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  1978. for vt in status.raw_data.get("vt_tray") or []:
  1979. vt_type = vt.get("tray_type")
  1980. if vt_type:
  1981. loaded_types.add(_canonical_filament_type(vt_type))
  1982. # Find which required types are missing (using canonical type for equivalence)
  1983. missing = []
  1984. for req_type in required_types:
  1985. if _canonical_filament_type(req_type) not in loaded_types:
  1986. missing.append(req_type)
  1987. return missing
  1988. def _count_override_color_matches(self, printer_id: int, overrides: list[dict]) -> int:
  1989. """Count how many filament overrides have an exact color match on the printer.
  1990. Used to prefer printers that already have the desired override colors loaded.
  1991. """
  1992. status = printer_manager.get_status(printer_id)
  1993. if not status:
  1994. return 0
  1995. # Collect loaded filaments' type+color pairs
  1996. loaded: set[tuple[str, str]] = set()
  1997. for ams_unit in status.raw_data.get("ams", []):
  1998. for tray in ams_unit.get("tray", []):
  1999. tray_type = tray.get("tray_type")
  2000. tray_color = tray.get("tray_color", "")
  2001. if tray_type:
  2002. color_norm = tray_color.replace("#", "").lower()[:6]
  2003. loaded.add((tray_type.upper(), color_norm))
  2004. for vt in status.raw_data.get("vt_tray") or []:
  2005. vt_type = vt.get("tray_type")
  2006. if vt_type:
  2007. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  2008. loaded.add((vt_type.upper(), color_norm))
  2009. matches = 0
  2010. for o in overrides:
  2011. o_type = (o.get("type") or "").upper()
  2012. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  2013. if (o_type, o_color) in loaded:
  2014. matches += 1
  2015. return matches
  2016. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  2017. """Fold the winning candidate's file and settings onto the queue row (#671).
  2018. This is the whole trick that keeps cross-model items cheap: the many-to-many
  2019. never escapes the selection loop. By the time the pass commits, the row
  2020. looks exactly like an ordinary single-file model-based item, so the upload,
  2021. archive creation, expected-print registration, print history and reprint
  2022. paths need no knowledge that variants exist.
  2023. No-ops for a non-variant candidate, which is already the item's own columns.
  2024. Safe to run and re-run: the item's file columns are only ever *read* when it
  2025. has no variants, so an item that gets resolved and then skipped (library-row
  2026. conflict, previous-print gate) is simply resolved again on the next pass.
  2027. """
  2028. variant = candidate.variant
  2029. if variant is None:
  2030. return
  2031. item.library_file_id = variant.library_file_id
  2032. item.library_file = variant.library_file
  2033. # The dispatcher checks archive_id first and would print that instead of
  2034. # the file we just picked. Creation refuses to combine the two, so this
  2035. # only ever fires on a hand-written row — clear it rather than silently
  2036. # dispatch something the matcher never considered.
  2037. item.archive_id = None
  2038. item.archive = None
  2039. item.target_model = variant.target_model
  2040. item.plate_id = variant.plate_id
  2041. item.ams_mapping = variant.ams_mapping
  2042. item.nozzle_mapping = variant.nozzle_mapping
  2043. item.filament_overrides = variant.filament_overrides
  2044. item.required_filament_types = variant.required_filament_types
  2045. if variant.print_time_seconds is not None:
  2046. # The row carried the shortest candidate's estimate so SJF could order
  2047. # it before a printer was known; now that one is chosen, record what is
  2048. # actually going to run so history and the ETA agree with reality.
  2049. item.print_time_seconds = variant.print_time_seconds
  2050. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  2051. """Ensure the queue item carries a usable AMS mapping before dispatch.
  2052. Recomputes from live printer status when the stored mapping is missing OR
  2053. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  2054. frontend status-load race can serialize [-1] before the printer's AMS
  2055. trays are known (#2589) — and must not be trusted: downstream it would be
  2056. silently downgraded to external-spool mode and print against an empty
  2057. feed. A resolved mapping (including manual overrides, or a partially
  2058. padded one) is left untouched.
  2059. When recompute cannot resolve it either (no compatible tray loaded), the
  2060. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  2061. external selection; the print command then keeps use_ams=True and the
  2062. firmware surfaces a clear AMS-mapping error instead of silently printing
  2063. to the empty external feed.
  2064. Returns an actionable message when that firmware error is the only
  2065. possible outcome — the matcher ran, matched nothing, and the printer has
  2066. no AMS to load a different spool into (#2771). The caller fails the item
  2067. on it instead of spending an upload on a print that cannot start.
  2068. Returns None everywhere else, including every case where we simply lack
  2069. the data to judge, so dispatch is only ever blocked on a positive
  2070. finding.
  2071. """
  2072. stored_mapping: list | None = None
  2073. if item.ams_mapping:
  2074. try:
  2075. stored_mapping = json.loads(item.ams_mapping)
  2076. except (json.JSONDecodeError, TypeError):
  2077. stored_mapping = None
  2078. # Already resolved (present and not all-unresolved) — keep as-is so a
  2079. # user's manual mapping is never overwritten.
  2080. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  2081. return None
  2082. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  2083. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  2084. item.ams_mapping = json.dumps(computed_mapping)
  2085. logger.info(
  2086. "Queue item %s: Computed AMS mapping for printer %s: %s",
  2087. item.id,
  2088. printer_id,
  2089. computed_mapping,
  2090. )
  2091. await db.commit()
  2092. return None
  2093. if _mapping_is_all_unresolved(stored_mapping):
  2094. logger.warning(
  2095. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  2096. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  2097. item.id,
  2098. stored_mapping,
  2099. printer_id,
  2100. )
  2101. item.ams_mapping = None
  2102. await db.commit()
  2103. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  2104. async def _unmappable_without_ams_message(
  2105. self,
  2106. db: AsyncSession,
  2107. printer_id: int,
  2108. item: PrintQueueItem,
  2109. computed_mapping: list[int] | None,
  2110. ) -> str | None:
  2111. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  2112. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  2113. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  2114. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  2115. uploaded several megabytes and burned its dispatch retries. With an AMS
  2116. attached that error is worth reaching: the user can load the right spool
  2117. and press Resume, so this returns None and today's behaviour stands. With
  2118. no AMS there is nothing to resume into — the external spool holder is the
  2119. whole inventory — so the useful answer is to say which filament is
  2120. missing and stop.
  2121. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  2122. every branch that lacks the evidence to be sure returns None.
  2123. """
  2124. # None means the matcher never ran (no requirements parsed from the 3MF,
  2125. # or nothing loaded at all) rather than "ran and matched nothing". Those
  2126. # dispatch as they always have.
  2127. if not _mapping_is_all_unresolved(computed_mapping):
  2128. return None
  2129. status = printer_manager.get_status(printer_id)
  2130. if status is None:
  2131. return None
  2132. # "No AMS" has to be a fact the printer stated, not the absence of a
  2133. # statement. `raw_data["ams"]` is written only once an AMS push has been
  2134. # handled and is preserved across partial pushes thereafter, so a missing
  2135. # key means we have not heard yet — most likely a reconnect, where the
  2136. # trays of a fully loaded AMS would be invisible for a few seconds. An
  2137. # empty list is the positive report of a printer with no AMS.
  2138. ams_units = status.raw_data.get("ams")
  2139. if not isinstance(ams_units, list) or ams_units:
  2140. return None
  2141. required = await self._get_filament_requirements(db, item)
  2142. loaded = self._build_loaded_filaments(status)
  2143. if not required or not loaded:
  2144. # Both were non-empty moments ago or the matcher could not have run.
  2145. # If the picture changed under us, say nothing rather than fail an
  2146. # item on stale evidence.
  2147. return None
  2148. self._apply_filament_overrides(item, required)
  2149. return _unmatched_filament_message(required, loaded)
  2150. async def _fail_unmappable_item(
  2151. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  2152. ) -> None:
  2153. """Fail a queue item whose filament mapping cannot resolve (#2771).
  2154. This replaces a failure, not a success: without it the item is uploaded,
  2155. rejected by the firmware with 0700_8012, retried twice more and failed
  2156. anyway with "never started the print after N dispatch attempts". So this
  2157. applies on the model-based path too, even though it means an "Any <model>"
  2158. job stops at the first printer offered rather than trying its siblings —
  2159. deferring instead would need the check to move inside
  2160. ``_find_printer_for_model``'s candidate loop, since un-assigning here just
  2161. re-assigns the same printer on the next tick.
  2162. """
  2163. item.status = "failed"
  2164. item.error_message = message
  2165. item.completed_at = datetime.now(timezone.utc)
  2166. item.waiting_reason = None
  2167. await db.commit()
  2168. logger.warning(
  2169. "Queue item %s: no usable AMS mapping on printer %s — %s",
  2170. item.id,
  2171. printer_id,
  2172. message,
  2173. )
  2174. job_name = await self._get_job_name(db, item)
  2175. printer = await self._get_printer(db, printer_id)
  2176. await notification_service.on_queue_job_failed(
  2177. job_name=job_name,
  2178. printer_id=printer_id,
  2179. printer_name=printer.name if printer else "Unknown",
  2180. reason=message,
  2181. db=db,
  2182. )
  2183. try:
  2184. await ws_manager.send_queue_item_failed(
  2185. user_id=item.created_by_id,
  2186. queue_item_id=item.id,
  2187. printer_id=printer_id,
  2188. reason="filament_unmappable",
  2189. )
  2190. except Exception:
  2191. pass
  2192. async def _compute_ams_mapping_for_printer(
  2193. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  2194. ) -> list[int] | None:
  2195. """Compute AMS mapping for a printer based on filament requirements.
  2196. Called when a queue item has no ams_mapping set — either for model-based
  2197. items after printer assignment, or printer-specific items (e.g. from VP).
  2198. Args:
  2199. db: Database session
  2200. printer_id: The assigned printer ID
  2201. item: The queue item (contains archive_id or library_file_id)
  2202. Returns:
  2203. AMS mapping array or None if no mapping needed/possible
  2204. """
  2205. # Get printer status
  2206. status = printer_manager.get_status(printer_id)
  2207. if not status:
  2208. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  2209. return None
  2210. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  2211. # either extruder, so the per-nozzle hard filter below must NOT apply.
  2212. # Otherwise a print on one nozzle can't use a spool physically loaded in
  2213. # an AMS on the *other* nozzle, and the matcher falls through to a
  2214. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  2215. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  2216. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  2217. # Get filament requirements from source file
  2218. filament_reqs = await self._get_filament_requirements(db, item)
  2219. if not filament_reqs:
  2220. # When the 3MF can't be read but force-color overrides are present, build a
  2221. # direct mapping from the overrides so the printer uses the correct AMS slot.
  2222. if item.filament_overrides:
  2223. try:
  2224. overrides = json.loads(item.filament_overrides)
  2225. force_overrides = [o for o in overrides if o.get("force_color_match")]
  2226. if force_overrides:
  2227. logger.info(
  2228. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  2229. "force-color override(s)",
  2230. item.id,
  2231. len(force_overrides),
  2232. )
  2233. return self._build_override_direct_mapping(force_overrides, status)
  2234. except (json.JSONDecodeError, KeyError, TypeError) as e:
  2235. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  2236. logger.debug("No filament requirements found for queue item %s", item.id)
  2237. return None
  2238. self._apply_filament_overrides(item, filament_reqs)
  2239. # Build loaded filaments from printer status
  2240. loaded_filaments = self._build_loaded_filaments(status)
  2241. if not loaded_filaments:
  2242. logger.debug("No filaments loaded on printer %s", printer_id)
  2243. return None
  2244. # Check if user prefers lowest remaining filament when multiple spools match
  2245. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  2246. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  2247. # Without backup, the printer will not switch to a second spool when the
  2248. # picked one runs out — so sorting toward the lowest leaves the print
  2249. # at risk of running dry mid-job. None (unknown / A1 family) preserves
  2250. # today's behaviour intentionally.
  2251. if prefer_lowest and status.ams_filament_backup is False:
  2252. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  2253. prefer_lowest = False
  2254. # When the preference is on, surface Bambuddy's inventory-side
  2255. # remaining for each slot that's bound to a tracked spool, so the
  2256. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  2257. # entirely when the preference is off — no behaviour change for
  2258. # users who haven't opted in.
  2259. inventory_remain_overrides: dict[int, float] | None = None
  2260. if prefer_lowest:
  2261. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  2262. # Compute mapping: match required filaments to available slots
  2263. return self._match_filaments_to_slots(
  2264. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  2265. )
  2266. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  2267. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  2268. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  2269. diagnosis (#2771) describes the filament the matcher actually looked
  2270. for, not the one the 3MF was sliced with — naming the pre-override
  2271. filament in a user-facing error would send the user to load the wrong
  2272. spool.
  2273. """
  2274. if not item.filament_overrides:
  2275. return
  2276. try:
  2277. overrides = json.loads(item.filament_overrides)
  2278. override_map = {o["slot_id"]: o for o in overrides}
  2279. for req in filament_reqs:
  2280. if req["slot_id"] in override_map:
  2281. override = override_map[req["slot_id"]]
  2282. req["type"] = override["type"]
  2283. req["color"] = override["color"]
  2284. # A manual/preference override SWAPS the slot's filament, so the
  2285. # 3MF's original tray_info_idx now points at the old spool and must
  2286. # be cleared — matching then falls back to type+colour. A
  2287. # force_color_match override is not a swap: it carries the 3MF's
  2288. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  2289. # it here too, letting the matcher pin the correct variant slot on a
  2290. # printer holding two same-colour spools of different variants (#2650).
  2291. # If that variant isn't loaded the matcher falls back to type+colour,
  2292. # so an eligible printer never fails to map.
  2293. req["tray_info_idx"] = (
  2294. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  2295. )
  2296. logger.debug(
  2297. "Queue item %s: Override slot %d -> %s %s",
  2298. item.id,
  2299. req["slot_id"],
  2300. override["type"],
  2301. override["color"],
  2302. )
  2303. except (json.JSONDecodeError, KeyError, TypeError) as e:
  2304. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  2305. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  2306. """Build an AMS mapping directly from force-color overrides without a 3MF.
  2307. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  2308. slice_info is missing or unreadable) but ``force_color_match`` overrides
  2309. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  2310. treated as the filament requirement for that slot and matched against the
  2311. current AMS state of the printer.
  2312. Returns the same format as ``_match_filaments_to_slots``, or None when
  2313. the AMS has no loaded filaments.
  2314. """
  2315. loaded = self._build_loaded_filaments(status)
  2316. if not loaded:
  2317. return None
  2318. reqs = [
  2319. {
  2320. "slot_id": o["slot_id"],
  2321. "type": o.get("type", ""),
  2322. "color": o.get("color", ""),
  2323. # These are all force_color_match overrides, so the idx (when the
  2324. # 3MF carried one) is the intended variant, not a stale swap —
  2325. # keep it so the matcher pins the right variant slot, falling back
  2326. # to type+colour when it isn't loaded (#2650).
  2327. "tray_info_idx": o.get("tray_info_idx", ""),
  2328. }
  2329. for o in force_overrides
  2330. ]
  2331. return self._match_filaments_to_slots(reqs, loaded)
  2332. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  2333. """Resolve the queue item's source 3MF and parse the per-slot
  2334. filament requirements out of it. Thin DB-resolver wrapper around
  2335. ``filament_requirements.extract_filament_requirements`` so the VP
  2336. queue-mode write path (#1188) can reuse the same parser at upload
  2337. time.
  2338. """
  2339. from backend.app.services.filament_requirements import extract_filament_requirements
  2340. file_path: Path | None = None
  2341. if item.archive_id:
  2342. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  2343. archive = result.scalar_one_or_none()
  2344. if archive:
  2345. file_path = settings.base_dir / archive.file_path
  2346. elif item.library_file_id:
  2347. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  2348. library_file = result.scalar_one_or_none()
  2349. if library_file:
  2350. lib_path = Path(library_file.file_path)
  2351. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  2352. if not file_path or not file_path.exists():
  2353. return None
  2354. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  2355. return filaments if filaments else None
  2356. def _build_loaded_filaments(self, status) -> list[dict]:
  2357. """Build list of loaded filaments from printer status.
  2358. Args:
  2359. status: PrinterState from printer_manager
  2360. Returns:
  2361. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  2362. """
  2363. filaments = []
  2364. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  2365. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  2366. # Dual-nozzle detection, used below to route external spools to an
  2367. # extruder (#2771). Mirrors `buildLoadedFilaments` in the frontend,
  2368. # which was corrected for #1257 while this copy kept the old signal.
  2369. #
  2370. # `ams_extruder_map` is derived from AMS info bits, so a dual-nozzle
  2371. # printer with zero AMS units reports an empty map — and every external
  2372. # spool then got `extruder_id=None`, which the nozzle-aware filter in
  2373. # `_match_filaments_to_slots` rejects outright because `None` equals
  2374. # neither 0 nor 1. On an X2D feeding from external spools only that left
  2375. # nothing to match, the mapping came back all -1, and the print went out
  2376. # with `use_ams: true` and no mapping table at all — firmware 0700_8012,
  2377. # "Failed to get AMS mapping table".
  2378. #
  2379. # `nozzles` is always a two-entry list (the state seeds it with two empty
  2380. # NozzleInfo stubs), so its length proves nothing; only a populated
  2381. # diameter on the second entry means real hardware. The other two signals
  2382. # are fallbacks for firmware revisions that surface one but not the
  2383. # other: a populated `ams_extruder_map` is dual-nozzle by construction,
  2384. # and so is more than one `vt_tray` entry, since single-nozzle printers
  2385. # expose exactly one external feed.
  2386. nozzles = getattr(status, "nozzles", None) or []
  2387. vt_trays = status.raw_data.get("vt_tray") or []
  2388. is_dual_nozzle = bool(
  2389. (len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""))
  2390. or ams_extruder_map
  2391. # isinstance, because a dict here would count its ~30 keys as trays.
  2392. # bambu_mqtt normalises vt_tray to a list before it reaches raw_data,
  2393. # so this is unreachable — but the loop below would raise on a dict
  2394. # and that is the pre-existing behaviour to keep, not to paper over.
  2395. or (isinstance(vt_trays, list) and len(vt_trays) > 1)
  2396. )
  2397. # Parse AMS units from raw_data
  2398. ams_data = status.raw_data.get("ams", [])
  2399. for ams_unit in ams_data:
  2400. ams_id = int(ams_unit.get("id", 0))
  2401. trays = ams_unit.get("tray", [])
  2402. is_ht = len(trays) == 1 # AMS-HT has single tray
  2403. for tray in trays:
  2404. tray_type = tray.get("tray_type")
  2405. if tray_type:
  2406. tray_id = int(tray.get("id", 0))
  2407. tray_color = tray.get("tray_color", "")
  2408. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  2409. tray_info_idx = tray.get("tray_info_idx", "")
  2410. # Normalize color: remove alpha, add hash
  2411. color = self._normalize_color(tray_color)
  2412. # Calculate global tray ID
  2413. # AMS-HT units have IDs starting at 128 with a single tray
  2414. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  2415. filaments.append(
  2416. {
  2417. "type": tray_type,
  2418. "color": color,
  2419. "tray_info_idx": tray_info_idx,
  2420. "ams_id": ams_id,
  2421. "tray_id": tray_id,
  2422. "is_ht": is_ht,
  2423. "is_external": False,
  2424. "global_tray_id": global_tray_id,
  2425. "extruder_id": ams_extruder_map.get(str(ams_id)),
  2426. "remain": tray.get("remain", -1),
  2427. }
  2428. )
  2429. # Check external spool(s) (vt_tray is a list)
  2430. for idx, vt in enumerate(vt_trays):
  2431. if vt.get("tray_type"):
  2432. color = self._normalize_color(vt.get("tray_color", ""))
  2433. tray_id = int(vt.get("id", 254))
  2434. filaments.append(
  2435. {
  2436. "type": vt["tray_type"],
  2437. "color": color,
  2438. "tray_info_idx": vt.get("tray_info_idx", ""),
  2439. "ams_id": -1,
  2440. "tray_id": idx,
  2441. "is_ht": False,
  2442. "is_external": True,
  2443. "global_tray_id": tray_id,
  2444. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  2445. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  2446. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  2447. "remain": vt.get("remain", -1),
  2448. }
  2449. )
  2450. return filaments
  2451. def _normalize_color(self, color: str | None) -> str:
  2452. """Normalize color to #RRGGBB format."""
  2453. if not color:
  2454. return "#808080"
  2455. hex_color = color.replace("#", "")[:6]
  2456. return f"#{hex_color}"
  2457. def _normalize_color_for_compare(self, color: str | None) -> str:
  2458. """Normalize color for comparison (lowercase, no hash)."""
  2459. if not color:
  2460. return ""
  2461. return color.replace("#", "").lower()[:6]
  2462. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  2463. """Check if two colors are visually similar within a threshold."""
  2464. hex1 = self._normalize_color_for_compare(color1)
  2465. hex2 = self._normalize_color_for_compare(color2)
  2466. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  2467. return False
  2468. try:
  2469. r1 = int(hex1[0:2], 16)
  2470. g1 = int(hex1[2:4], 16)
  2471. b1 = int(hex1[4:6], 16)
  2472. r2 = int(hex2[0:2], 16)
  2473. g2 = int(hex2[2:4], 16)
  2474. b2 = int(hex2[4:6], 16)
  2475. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  2476. except ValueError:
  2477. return False
  2478. async def _build_inventory_remain_overrides(
  2479. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  2480. ) -> dict[int, float]:
  2481. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  2482. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  2483. The MQTT ``remain`` field on a tray is the printer firmware's
  2484. RFID-decremented value, which has two limitations the "Prefer Lowest
  2485. Remaining Filament" feature has been ignoring (#1508):
  2486. - it's only meaningful for Bambu RFID spools; everything else reports
  2487. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  2488. compare equal and the sort collapses to AMS-slot order — the user
  2489. who's curating inventory weights gets the lower-slot pick instead
  2490. of the lower-remaining pick;
  2491. - even when set, it's the *printer's* counter, not Bambuddy's
  2492. ``label_weight - weight_used`` (internal mode) or Spoolman's
  2493. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  2494. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  2495. When the user has bound a spool to a slot, their own inventory
  2496. tracking is authoritative; this helper surfaces that value so the
  2497. sort can prefer it. Slots without a binding are absent from the
  2498. returned map — the caller then falls back to MQTT ``remain`` for
  2499. those, preserving the pre-#1508 behaviour for un-tracked spools.
  2500. Returns an empty map on any failure (no inventory bindings, DB
  2501. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  2502. is a preference, not a guarantee.
  2503. """
  2504. if not loaded:
  2505. return {}
  2506. # External / virtual-tray slots are tracked separately from AMS — skip
  2507. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  2508. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  2509. # match is fiddly and out of scope for this fix).
  2510. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  2511. if not tracked_slots:
  2512. return {}
  2513. is_spoolman = await self._is_spoolman_mode(db)
  2514. overrides: dict[int, float] = {}
  2515. if is_spoolman:
  2516. result = await db.execute(
  2517. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2518. )
  2519. assignments = list(result.scalars().all())
  2520. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  2521. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  2522. for ams_id, tray_id, gtid in tracked_slots:
  2523. spoolman_id = by_slot.get((ams_id, tray_id))
  2524. if spoolman_id is None:
  2525. continue
  2526. grams = await _spoolman_remaining_grams(spoolman_id)
  2527. if grams is not None:
  2528. overrides[gtid] = grams
  2529. return overrides
  2530. # Internal inventory mode (default). selectinload matches the pattern
  2531. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  2532. # plus an eager-loaded relationship rather than an explicit join, so
  2533. # the row-attribute shape is exactly what those routes already rely on.
  2534. result = await db.execute(
  2535. select(SpoolAssignment)
  2536. .options(selectinload(SpoolAssignment.spool))
  2537. .where(SpoolAssignment.printer_id == printer_id)
  2538. )
  2539. assignments = list(result.scalars().all())
  2540. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  2541. for ams_id, tray_id, gtid in tracked_slots:
  2542. spool = by_slot.get((ams_id, tray_id))
  2543. if spool is None:
  2544. continue
  2545. label = float(spool.label_weight or 0)
  2546. used = float(spool.weight_used or 0)
  2547. overrides[gtid] = max(0.0, label - used)
  2548. return overrides
  2549. @staticmethod
  2550. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  2551. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  2552. here to avoid making this module import-dependent on that private
  2553. helper's signature."""
  2554. try:
  2555. from backend.app.api.routes.settings import get_setting
  2556. v = await get_setting(db, "spoolman_enabled")
  2557. return bool(v) and v.lower() == "true"
  2558. except Exception:
  2559. return False
  2560. @staticmethod
  2561. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  2562. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  2563. Three bands, matched to the emission order in ``_build_loaded_filaments``
  2564. so a tied sort produces the same physical-position order the pre-#1508
  2565. stable sort did (preserves the regression-free baseline):
  2566. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  2567. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  2568. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  2569. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  2570. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  2571. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  2572. """
  2573. if ams_id is None or ams_id < 0:
  2574. return 10_000
  2575. if ams_id >= 128:
  2576. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  2577. return ams_id * 4 + (tray_id or 0)
  2578. @staticmethod
  2579. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  2580. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  2581. Two-tier ordering: inventory-tracked spools always sort BEFORE
  2582. non-tracked spools (the user has told us they care about these
  2583. specifically), then ascending by remaining within each tier, then
  2584. ascending by AMS slot position as the deterministic tie-breaker.
  2585. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  2586. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  2587. because the tier flag dominates — which is what lets us mix grams
  2588. (inventory) and percent (MQTT) without a unit conversion.
  2589. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  2590. spools the printer DOES know something about sort ahead of those
  2591. it knows nothing about — preserves pre-#1508 behaviour for the
  2592. no-inventory-binding case.
  2593. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  2594. external on ties, matching the legacy emission-order stable sort.
  2595. """
  2596. gtid = f.get("global_tray_id")
  2597. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  2598. if overrides and gtid in overrides:
  2599. return (0, overrides[gtid], slot_order)
  2600. remain = f.get("remain", -1)
  2601. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  2602. def _match_filaments_to_slots(
  2603. self,
  2604. required: list[dict],
  2605. loaded: list[dict],
  2606. prefer_lowest: bool = False,
  2607. inventory_remain_overrides: dict[int, float] | None = None,
  2608. fts_installed: bool = False,
  2609. ) -> list[int] | None:
  2610. """Match required filaments to loaded filaments and build AMS mapping.
  2611. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  2612. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  2613. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  2614. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  2615. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  2616. matching among those trays.
  2617. Args:
  2618. required: List of required filaments with slot_id, type, color, tray_info_idx
  2619. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  2620. Returns:
  2621. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  2622. """
  2623. if not required:
  2624. return None
  2625. # Track used trays to avoid duplicate assignment
  2626. used_tray_ids: set[int] = set()
  2627. comparisons = []
  2628. for req in required:
  2629. req_type = (req.get("type") or "").upper()
  2630. req_color = req.get("color", "")
  2631. req_tray_info_idx = req.get("tray_info_idx", "")
  2632. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  2633. idx_match = None
  2634. exact_match = None
  2635. similar_match = None
  2636. type_only_match = None
  2637. # Get available trays (not already used)
  2638. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  2639. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  2640. # Hard filter — cross-nozzle assignment causes print failures
  2641. # ("position of left hotend is abnormal"), so never fall back.
  2642. # Skipped when an FTS is installed: it routes any AMS slot to either
  2643. # extruder, so restricting to one nozzle would wrongly exclude the
  2644. # correct spool sitting in the other nozzle's AMS (#2186).
  2645. req_nozzle_id = req.get("nozzle_id")
  2646. if req_nozzle_id is not None and not fts_installed:
  2647. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  2648. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  2649. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  2650. # _prefer_lowest_sort_key for the full rationale.
  2651. if prefer_lowest:
  2652. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  2653. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  2654. # One line per filament req so a bug report can be diagnosed
  2655. # without enabling debug logging: shows what the matcher saw
  2656. # (req shape + sorted candidate trays with their remain values
  2657. # and any inventory override that was applied). Mirrored by
  2658. # the picked-match log at the bottom of the loop.
  2659. logger.info(
  2660. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  2661. req.get("slot_id"),
  2662. req_type,
  2663. req_color,
  2664. req_tray_info_idx,
  2665. req_nozzle_id,
  2666. [
  2667. {
  2668. "gtid": f.get("global_tray_id"),
  2669. "type": f.get("type"),
  2670. "color": f.get("color"),
  2671. "tii": f.get("tray_info_idx"),
  2672. "remain": f.get("remain"),
  2673. "inv_g": (
  2674. inventory_remain_overrides.get(f.get("global_tray_id"))
  2675. if inventory_remain_overrides
  2676. else None
  2677. ),
  2678. }
  2679. for f in available
  2680. ],
  2681. )
  2682. # Check if tray_info_idx is unique among available trays
  2683. if req_tray_info_idx:
  2684. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  2685. if len(idx_matches) == 1:
  2686. # Unique tray_info_idx - use it as definitive match
  2687. idx_match = idx_matches[0]
  2688. logger.debug(
  2689. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  2690. f"-> tray {idx_match['global_tray_id']}"
  2691. )
  2692. elif len(idx_matches) > 1:
  2693. # Multiple trays with same tray_info_idx - use color matching among them
  2694. logger.debug(
  2695. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  2696. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  2697. )
  2698. if prefer_lowest:
  2699. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  2700. # Use color matching within this subset
  2701. for f in idx_matches:
  2702. f_color = f.get("color", "")
  2703. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  2704. if not exact_match:
  2705. exact_match = f
  2706. elif self._colors_are_similar(f_color, req_color):
  2707. if not similar_match:
  2708. similar_match = f
  2709. elif not type_only_match:
  2710. type_only_match = f
  2711. # If no idx_match yet, do standard type/color matching on all available trays
  2712. if not idx_match and not exact_match and not similar_match and not type_only_match:
  2713. for f in available:
  2714. f_type = (f.get("type") or "").upper()
  2715. if _canonical_filament_type(f_type) != _canonical_filament_type(req_type):
  2716. continue
  2717. # Type matches - check color
  2718. f_color = f.get("color", "")
  2719. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  2720. if not exact_match:
  2721. exact_match = f
  2722. elif self._colors_are_similar(f_color, req_color):
  2723. if not similar_match:
  2724. similar_match = f
  2725. elif not type_only_match:
  2726. type_only_match = f
  2727. match = idx_match or exact_match or similar_match or type_only_match
  2728. if match:
  2729. used_tray_ids.add(match["global_tray_id"])
  2730. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  2731. else:
  2732. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  2733. if prefer_lowest:
  2734. # Pair with the "available (sorted)" log above so the reporter
  2735. # bundle shows BOTH what the matcher saw AND which match bucket
  2736. # won — fast triage when "Prefer Lowest Filament" picks the
  2737. # wrong slot (#1766).
  2738. if match:
  2739. bucket = (
  2740. "idx"
  2741. if idx_match is not None
  2742. else "exact_color"
  2743. if exact_match is not None
  2744. else "similar_color"
  2745. if similar_match is not None
  2746. else "type_only"
  2747. )
  2748. logger.info(
  2749. "[prefer-lowest] picked gtid=%s via %s for req slot=%s",
  2750. match["global_tray_id"],
  2751. bucket,
  2752. req.get("slot_id"),
  2753. )
  2754. else:
  2755. logger.info(
  2756. "[prefer-lowest] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  2757. req.get("slot_id"),
  2758. req_type,
  2759. req_color,
  2760. req_tray_info_idx,
  2761. )
  2762. # Build mapping array
  2763. if not comparisons:
  2764. return None
  2765. max_slot_id = max(c["slot_id"] for c in comparisons)
  2766. if max_slot_id <= 0:
  2767. return None
  2768. mapping = [-1] * max_slot_id
  2769. for c in comparisons:
  2770. slot_id = c["slot_id"]
  2771. if slot_id and slot_id > 0:
  2772. mapping[slot_id - 1] = c["global_tray_id"]
  2773. return mapping
  2774. def _mark_printer_dispatched(
  2775. self,
  2776. printer_id: int,
  2777. pre_state: str | None,
  2778. pre_subtask_id: str | None,
  2779. ) -> None:
  2780. """Record that a print command was just sent to ``printer_id``.
  2781. Held until either the watchdog observes a state/subtask transition
  2782. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  2783. """
  2784. if not pre_state:
  2785. # No pre_state means we can't detect a transition — fall back to a
  2786. # pure time-based hold using empty string as a sentinel that won't
  2787. # match any real printer state.
  2788. pre_state = ""
  2789. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  2790. def _release_dispatch_hold(self, printer_id: int) -> None:
  2791. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  2792. self._dispatch_holds.pop(printer_id, None)
  2793. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  2794. """True if ``printer_id`` is still inside its post-dispatch hold window.
  2795. Returns False (and clears the hold) once any of these are true:
  2796. - hard timeout (``_dispatch_max_hold``) has elapsed
  2797. - the printer has transitioned out of pre_state and we're past the
  2798. minimum cooldown
  2799. - the printer's subtask_id has advanced past pre_subtask_id and we're
  2800. past the minimum cooldown
  2801. Otherwise the printer is held — caller should treat it as busy.
  2802. """
  2803. entry = self._dispatch_holds.get(printer_id)
  2804. if not entry:
  2805. return False
  2806. started_at, pre_state, pre_subtask_id = entry
  2807. elapsed = time.monotonic() - started_at
  2808. if elapsed >= self._dispatch_max_hold:
  2809. self._dispatch_holds.pop(printer_id, None)
  2810. return False
  2811. # Without a pre_state we can't detect a transition — fall back to the
  2812. # min cooldown alone, then drop the hold.
  2813. if not pre_state:
  2814. if elapsed >= self._dispatch_min_cooldown:
  2815. self._dispatch_holds.pop(printer_id, None)
  2816. return False
  2817. return True
  2818. status = printer_manager.get_status(printer_id)
  2819. current_state = getattr(status, "state", None) if status else None
  2820. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  2821. transitioned = (current_state is not None and current_state != pre_state) or (
  2822. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  2823. )
  2824. if transitioned and elapsed >= self._dispatch_min_cooldown:
  2825. self._dispatch_holds.pop(printer_id, None)
  2826. return False
  2827. return True
  2828. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  2829. """Check if a printer is connected and idle."""
  2830. if not printer_manager.is_connected(printer_id):
  2831. logger.debug("Printer %d: not connected", printer_id)
  2832. return False
  2833. state = printer_manager.get_status(printer_id)
  2834. if not state:
  2835. logger.debug("Printer %d: no status available", printer_id)
  2836. return False
  2837. # Plate-clear gate: if the printer finished/failed a previous print and the user
  2838. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  2839. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  2840. # printer, it boots back into IDLE with no memory of the previous finish; without
  2841. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  2842. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  2843. logger.debug(
  2844. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  2845. printer_id,
  2846. state.state,
  2847. )
  2848. return False
  2849. idle = state.state in ("IDLE", "FINISH", "FAILED")
  2850. if not idle:
  2851. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  2852. return idle
  2853. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  2854. """Read a setting value from the database."""
  2855. result = await db.execute(select(Settings).where(Settings.key == key))
  2856. setting = result.scalar_one_or_none()
  2857. return setting.value if setting else None
  2858. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  2859. """Read a boolean setting from the database."""
  2860. result = await db.execute(select(Settings).where(Settings.key == key))
  2861. setting = result.scalar_one_or_none()
  2862. if setting:
  2863. return setting.value.lower() == "true"
  2864. return default
  2865. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  2866. """Read an int setting; falls back to default on missing/unparseable rows."""
  2867. result = await db.execute(select(Settings).where(Settings.key == key))
  2868. setting = result.scalar_one_or_none()
  2869. if setting and setting.value:
  2870. try:
  2871. return int(setting.value)
  2872. except ValueError:
  2873. pass
  2874. return default
  2875. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  2876. """Get drying presets (user-configured or built-in defaults)."""
  2877. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  2878. setting = result.scalar_one_or_none()
  2879. if setting and setting.value:
  2880. try:
  2881. presets = json.loads(setting.value)
  2882. if isinstance(presets, dict) and presets:
  2883. return presets
  2884. except json.JSONDecodeError:
  2885. pass
  2886. return self.DEFAULT_DRYING_PRESETS
  2887. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  2888. """Per-filament humidity thresholds (#1605).
  2889. Returns the user-configured overrides map keyed by normalized filament
  2890. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  2891. unknown / unmapped types. Empty / unset → empty dict, in which case
  2892. callers fall back to ``ams_humidity_fair``.
  2893. """
  2894. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  2895. setting = result.scalar_one_or_none()
  2896. if not setting or not setting.value:
  2897. return {}
  2898. try:
  2899. data = json.loads(setting.value)
  2900. except json.JSONDecodeError:
  2901. return {}
  2902. if not isinstance(data, dict):
  2903. return {}
  2904. out: dict[str, int] = {}
  2905. for key, value in data.items():
  2906. try:
  2907. out[str(key).upper() if key != "default" else "default"] = int(value)
  2908. except (TypeError, ValueError):
  2909. continue
  2910. return out
  2911. @staticmethod
  2912. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  2913. """Resolve the effective humidity threshold for an AMS unit (#1605).
  2914. For mixed filament types loaded into one AMS, returns the most
  2915. restrictive (lowest) threshold across all loaded tray types — matches
  2916. the conservative-params strategy already used for drying temp/hours.
  2917. Empty / unloaded trays contribute no constraint. Unknown types use the
  2918. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  2919. when no per-type map is configured at all.
  2920. """
  2921. default = thresholds.get("default", fallback)
  2922. if not thresholds:
  2923. return fallback
  2924. candidates: list[int] = []
  2925. for tray in trays:
  2926. tray_type = str(tray.get("tray_type") or "").strip()
  2927. if not tray_type:
  2928. continue
  2929. base_type = tray_type.split()[0].upper()
  2930. candidates.append(thresholds.get(base_type, default))
  2931. if not candidates:
  2932. return default
  2933. return min(candidates)
  2934. def _get_conservative_drying_params(
  2935. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  2936. ) -> tuple[int, int, str] | None:
  2937. """Get the most conservative drying params for mixed filament types in an AMS unit.
  2938. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  2939. """
  2940. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  2941. hours_key = f"{temp_key}_hours"
  2942. min_temp = None
  2943. max_hours = None
  2944. filament_type = ""
  2945. for tray in trays:
  2946. tray_type = tray.get("tray_type", "")
  2947. if not tray_type:
  2948. continue
  2949. # Normalize filament type for preset lookup (e.g., "PLA Basic" -> "PLA")
  2950. base_type = tray_type.split()[0].upper()
  2951. preset = presets.get(base_type)
  2952. if not preset:
  2953. continue
  2954. temp = preset.get(temp_key, 55)
  2955. hours = preset.get(hours_key, 12)
  2956. # Conservative: lowest temp, longest duration
  2957. if min_temp is None or temp < min_temp:
  2958. min_temp = temp
  2959. if max_hours is None or hours > max_hours:
  2960. max_hours = hours
  2961. if not filament_type:
  2962. filament_type = base_type
  2963. if min_temp is None:
  2964. return None
  2965. return (min_temp, max_hours or 12, filament_type)
  2966. async def _check_auto_drying(
  2967. self,
  2968. db: AsyncSession,
  2969. queue_items: list[PrintQueueItem],
  2970. dispatching_printers: set[int],
  2971. ):
  2972. """Start drying on idle printers based on humidity.
  2973. Three modes (can all be enabled independently):
  2974. - queue_drying_enabled: Dry between scheduled queue prints
  2975. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  2976. - print_drying_enabled: Also evaluate printers that are currently printing,
  2977. when model+firmware supports "Print While Drying" (gated by
  2978. supports_drying_while_printing). Drying temperature is capped at
  2979. max(40, preset_temp - 5) to protect spools mid-print.
  2980. """
  2981. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  2982. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  2983. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  2984. if not queue_drying_enabled and not ambient_drying_enabled:
  2985. # Stop active drying on all printers if both features disabled
  2986. if self._drying_in_progress:
  2987. for pid in list(self._drying_in_progress):
  2988. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  2989. await self._stop_drying(pid)
  2990. return
  2991. # Update drying state from printer status (handles backend restart)
  2992. self._sync_drying_state()
  2993. # Find printers with scheduled items (for queue drying mode)
  2994. printers_with_scheduled: set[int] = set()
  2995. printers_with_items: set[int] = set()
  2996. for item in queue_items:
  2997. if item.printer_id:
  2998. printers_with_items.add(item.printer_id)
  2999. if item.scheduled_time and not item.manual_start:
  3000. printers_with_scheduled.add(item.printer_id)
  3001. # If only queue mode is on and no printers have scheduled items, stop drying
  3002. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  3003. # may still be eligible for mid-print drying regardless of queue state).
  3004. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  3005. for pid in list(self._drying_in_progress):
  3006. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  3007. await self._stop_drying(pid)
  3008. return
  3009. # Get humidity threshold (global fallback)
  3010. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  3011. setting = result.scalar_one_or_none()
  3012. global_humidity_threshold = int(setting.value) if setting else 60
  3013. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  3014. # to the global threshold for every AMS unit.
  3015. per_type_thresholds = await self._get_humidity_thresholds(db)
  3016. # Get drying presets
  3017. presets = await self._get_drying_presets(db)
  3018. # Determine if drying should be skipped for printers with pending items
  3019. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  3020. # Get all active printers
  3021. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  3022. for printer in all_printers.scalars():
  3023. pid = printer.id
  3024. # Resolve model+firmware up front — needed to decide whether this printer
  3025. # qualifies for mid-print drying (busy printer on capable hardware).
  3026. state = printer_manager.get_status(pid)
  3027. if not state:
  3028. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  3029. continue
  3030. model = printer_manager.get_model(pid)
  3031. firmware = state.firmware_version
  3032. # "Mid-print" has to mean the printer is actually printing (#2801).
  3033. # It used to be inferred from the dispatch set, which also holds
  3034. # printers that merely could not be dispatched to -- so a printer
  3035. # sitting in FINISH behind an unacknowledged plate was treated as
  3036. # printing, had its drying temperature capped by the mid-print
  3037. # spool protection, and was logged as (mid-print) while idle.
  3038. is_printing = state.state in _ACTIVE_PRINT_STATES
  3039. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  3040. # A printer whose print is running or imminent is left alone unless
  3041. # it can dry through it. `dispatching_printers` is deliberately the
  3042. # narrow set: running, held post-dispatch, or mid-upload.
  3043. if (is_printing or pid in dispatching_printers) and not mid_print:
  3044. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  3045. continue
  3046. if not mid_print:
  3047. # In queue-only mode, only dry printers that have scheduled prints
  3048. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  3049. if self._drying_in_progress.get(pid):
  3050. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  3051. await self._stop_drying(pid)
  3052. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  3053. continue
  3054. # When block mode is on, don't START new drying on printers with pending items.
  3055. # But allow already-drying printers through so humidity auto-stop logic still runs.
  3056. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  3057. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  3058. continue
  3059. if not printer_manager.is_connected(pid):
  3060. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  3061. continue
  3062. # Plate-clear is deliberately ignored here (#2801). It answers
  3063. # "is the bed ready for the next job", which says nothing about
  3064. # whether the AMS may heat -- and the gap between a finished print
  3065. # and the acknowledgment is exactly when drying is most useful,
  3066. # because the printer is free and nobody is waiting on it. Leaving
  3067. # the plate unacknowledged is also how people hold the queue by
  3068. # hand, and that hold should not cost them their drying.
  3069. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  3070. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  3071. continue
  3072. # Check drying capability. For mid-print path, supports_drying_while_printing
  3073. # was already verified when computing mid_print above.
  3074. if not mid_print and not supports_drying(model, firmware):
  3075. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  3076. continue
  3077. # Check each AMS unit from raw_data
  3078. ams_list = state.raw_data.get("ams", [])
  3079. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  3080. for ams_data in ams_list:
  3081. module_type = str(ams_data.get("module_type") or "")
  3082. ams_id = int(ams_data.get("id", 0))
  3083. # Only n3f/n3s support drying
  3084. if module_type not in ("n3f", "n3s"):
  3085. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  3086. continue
  3087. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  3088. # Most-restrictive of all loaded tray types; falls back to the
  3089. # global threshold when no overrides are configured.
  3090. trays = ams_data.get("tray", []) or []
  3091. humidity_threshold = self.resolve_humidity_threshold(
  3092. trays, per_type_thresholds, global_humidity_threshold
  3093. )
  3094. dry_time = int(ams_data.get("dry_time") or 0)
  3095. # Read humidity — prefer humidity_raw (actual %) over humidity (index 1-5)
  3096. humidity = None
  3097. h_raw = ams_data.get("humidity_raw")
  3098. if h_raw is not None:
  3099. try:
  3100. humidity = int(h_raw)
  3101. except (ValueError, TypeError):
  3102. pass
  3103. if humidity is None:
  3104. h_idx = ams_data.get("humidity")
  3105. if h_idx is not None:
  3106. try:
  3107. humidity = int(h_idx)
  3108. except (ValueError, TypeError):
  3109. pass
  3110. unit_key = (pid, ams_id)
  3111. unit_state = self._auto_dry_units.get(unit_key)
  3112. # Already drying — let it run to its configured duration (#1892).
  3113. #
  3114. # We deliberately do NOT stop drying from a humidity re-check here.
  3115. # Relative humidity drops steeply in heated air, so the AMS sensor
  3116. # reads ~15-20% within minutes of the dryer starting even while the
  3117. # filament is still saturated. A humidity-based early-stop therefore
  3118. # always fires at the minimum-time floor, truncating both user-started
  3119. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  3120. # The firmware stops when the configured duration elapses; scheduling
  3121. # stops (print takes priority, queue no longer needs drying) are
  3122. # handled separately via _stop_drying().
  3123. if dry_time > 0:
  3124. if pid not in self._drying_in_progress:
  3125. # Drying we didn't start (manual or from before restart) —
  3126. # track it so scheduling stops still apply; never auto-stop it.
  3127. self._drying_in_progress[pid] = time.monotonic()
  3128. if unit_state is not None:
  3129. unit_state["running"] = True
  3130. logger.debug(
  3131. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  3132. pid,
  3133. ams_id,
  3134. dry_time,
  3135. humidity,
  3136. )
  3137. continue
  3138. # Nothing is drying. Close out a cycle we armed ourselves and
  3139. # judge whether it achieved anything (#2770).
  3140. #
  3141. # "Achieved anything" is measured against the LOWEST reading any
  3142. # cycle on this unit has ended at, not against the threshold and
  3143. # not against the previous cycle. A spool that is genuinely wet
  3144. # in a humid room comes down slowly — 40, 37, 35 — and must be
  3145. # allowed to keep going for as long as it is still coming down,
  3146. # however far it still is from the threshold. What must not
  3147. # continue is a cycle that ends exactly where the last one did,
  3148. # which is the reporter's signature: 15, 15, 16, 15, forever.
  3149. # Comparing against the running minimum rather than the previous
  3150. # end is what stops a sensor oscillating by one point between two
  3151. # values from reading as progress every other cycle.
  3152. if unit_state is not None and unit_state.pop("running", False):
  3153. unit_state["ended_at"] = time.monotonic()
  3154. if humidity is not None and humidity > humidity_threshold:
  3155. best = unit_state.get("best_end_humidity")
  3156. if isinstance(best, int) and humidity < best:
  3157. # Still coming down. Keep going, however far the
  3158. # threshold still is.
  3159. unproductive = 0
  3160. else:
  3161. unproductive = int(unit_state.get("unproductive", 0)) + 1
  3162. if not isinstance(best, int) or humidity < best:
  3163. unit_state["best_end_humidity"] = humidity
  3164. unit_state["unproductive"] = unproductive
  3165. logger.info(
  3166. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  3167. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  3168. pid,
  3169. ams_id,
  3170. humidity,
  3171. humidity_threshold,
  3172. unit_state.get("best_end_humidity"),
  3173. unproductive,
  3174. )
  3175. # A cycle that ended at or below the threshold needs no
  3176. # counter reset here: the branch below drops the whole entry.
  3177. # Humidity below threshold — no need to start drying. This is
  3178. # also the only thing that lifts a suspension: the reading we
  3179. # gave up on has come down, so auto-drying works again and the
  3180. # unit goes back to having no history at all.
  3181. if humidity is None or humidity <= humidity_threshold:
  3182. if unit_state is not None and unit_state.get("suspended"):
  3183. logger.info(
  3184. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  3185. "threshold, resuming automatic drying",
  3186. pid,
  3187. ams_id,
  3188. humidity,
  3189. humidity_threshold,
  3190. )
  3191. # Clear the judgement, keep the clock (#2801). Dropping the
  3192. # whole entry also dropped `ended_at`, and with it the
  3193. # 30-minute cooldown -- so a reading that dips to the
  3194. # threshold as the AMS cools and comes back above it once
  3195. # warm wiped its own history and re-armed immediately. That
  3196. # oscillation is the very thing #2770's cooldown exists to
  3197. # ride out, and it is worst at exactly the margin that makes
  3198. # a unit dry repeatedly: a point or two above the threshold.
  3199. if unit_state is not None:
  3200. unit_state.pop("suspended", None)
  3201. unit_state.pop("unproductive", None)
  3202. unit_state.pop("best_end_humidity", None)
  3203. logger.debug(
  3204. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  3205. pid,
  3206. ams_id,
  3207. humidity,
  3208. humidity_threshold,
  3209. )
  3210. continue
  3211. if unit_state is not None:
  3212. if unit_state.get("suspended"):
  3213. logger.debug(
  3214. "Auto-drying: printer %d AMS %d skipped — suspended, %d cycles left humidity "
  3215. "above the %d%% threshold",
  3216. pid,
  3217. ams_id,
  3218. int(unit_state.get("unproductive", 0)),
  3219. humidity_threshold,
  3220. )
  3221. continue
  3222. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  3223. unit_state["suspended"] = True
  3224. logger.warning(
  3225. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  3226. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  3227. "higher while it is warm, so a threshold in that range can never be reached and "
  3228. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  3229. pid,
  3230. ams_id,
  3231. int(unit_state.get("unproductive", 0)),
  3232. humidity,
  3233. humidity_threshold,
  3234. )
  3235. await self._notify_auto_drying_suspended(
  3236. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  3237. )
  3238. continue
  3239. ended_at = unit_state.get("ended_at")
  3240. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  3241. logger.debug(
  3242. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  3243. "cycle before the humidity reading is worth acting on",
  3244. pid,
  3245. ams_id,
  3246. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  3247. )
  3248. continue
  3249. # Check cannot-dry reasons (power constraints etc.)
  3250. sf_reasons = ams_data.get("dry_sf_reason", [])
  3251. if sf_reasons:
  3252. logger.debug(
  3253. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  3254. pid,
  3255. ams_id,
  3256. sf_reasons,
  3257. )
  3258. continue
  3259. # Get conservative drying params for mixed filaments
  3260. params = self._get_conservative_drying_params(trays, module_type, presets)
  3261. if not params:
  3262. logger.debug(
  3263. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  3264. )
  3265. continue
  3266. temp, duration_hours, filament_type = params
  3267. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  3268. # "drying temperature must not exceed the filament's softening temperature"
  3269. # for Print While Drying). Floor at 40 degC — below that the dryer is
  3270. # ineffective and firmware will reject anyway.
  3271. if mid_print:
  3272. temp = max(40, temp - 5)
  3273. # Start drying
  3274. logger.info(
  3275. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  3276. "starting %s drying at %d°C for %dh%s",
  3277. pid,
  3278. ams_id,
  3279. humidity,
  3280. humidity_threshold,
  3281. filament_type,
  3282. temp,
  3283. duration_hours,
  3284. " (mid-print)" if mid_print else "",
  3285. )
  3286. success = printer_manager.send_drying_command(
  3287. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  3288. )
  3289. if success:
  3290. self._drying_in_progress[pid] = time.monotonic()
  3291. armed = self._auto_dry_units.setdefault(
  3292. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  3293. )
  3294. armed["running"] = True
  3295. async def _notify_auto_drying_suspended(
  3296. self,
  3297. db: AsyncSession,
  3298. printer: Printer,
  3299. ams_id: int,
  3300. humidity: int,
  3301. threshold: int,
  3302. cycles: int,
  3303. ) -> None:
  3304. """Tell the user auto-drying has given up on one AMS unit (#2770).
  3305. Fires once per suspension — the caller sets ``suspended`` before calling
  3306. and every later pass short-circuits on it — because the whole point is
  3307. that Bambuddy has stopped acting. Somebody whose printer sits in another
  3308. building needs that to reach them, and the hourly humidity alarm they
  3309. are already getting says the opposite of what happened here.
  3310. Never raises: a notification provider being down must not stop the
  3311. suspension itself from taking effect.
  3312. """
  3313. ams_label = f"HT-{chr(65 + (ams_id - 128))}" if ams_id >= 128 else f"AMS-{chr(65 + ams_id)}"
  3314. try:
  3315. await notification_service.on_ams_drying_suspended(
  3316. printer.id,
  3317. printer.name,
  3318. ams_label,
  3319. float(humidity),
  3320. float(threshold),
  3321. cycles,
  3322. db,
  3323. )
  3324. except Exception as e:
  3325. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  3326. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  3327. """Stop judging the drying cycle currently on this AMS unit (#2770).
  3328. The unproductive-cycle counter exists to notice that *drying* is not
  3329. moving the humidity reading. A cycle that ended because somebody sent a
  3330. stop says nothing about that — it was cut short before it had a chance —
  3331. so counting it would suspend auto-drying for a reason that has nothing to
  3332. do with the loop the counter is there to break.
  3333. Two callers, both of them a stop Bambuddy is responsible for: the
  3334. print-takes-priority stop below, and the manual Stop button. Left
  3335. uncalled, an install that dries between queue jobs would suspend its own
  3336. auto-drying after two prints interrupted a dry — exactly the install
  3337. queue-drying exists for.
  3338. The rest of the unit's history is kept: the cooldown before re-arming
  3339. still applies, and an earlier count still stands.
  3340. """
  3341. state = self._auto_dry_units.get((printer_id, ams_id))
  3342. if state is not None:
  3343. state.pop("running", None)
  3344. state["ended_at"] = time.monotonic()
  3345. def _sync_drying_state(self):
  3346. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  3347. One direction only: it prunes, it never adds. A printer drying without an
  3348. entry here — because the user started the cycle from Studio, the printer's
  3349. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  3350. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  3351. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  3352. That is deliberate for now rather than an oversight: populating this from
  3353. telemetry would hand the scheduler authority to stop drying a user started
  3354. by hand. It also means the backend-restart case this used to claim to
  3355. handle is not handled.
  3356. """
  3357. to_remove = []
  3358. for pid in self._drying_in_progress:
  3359. state = printer_manager.get_status(pid)
  3360. if not state:
  3361. to_remove.append(pid)
  3362. continue
  3363. # Check if any AMS unit is still drying
  3364. ams_list = state.raw_data.get("ams", [])
  3365. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  3366. if not any_drying:
  3367. to_remove.append(pid)
  3368. for pid in to_remove:
  3369. self._drying_in_progress.pop(pid, None)
  3370. # A printer that has gone away entirely takes its per-AMS auto-drying
  3371. # history with it (#2770), so a printer deleted and re-added does not
  3372. # inherit a suspension it never earned.
  3373. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  3374. self._auto_dry_units.pop(key, None)
  3375. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  3376. """True when a running cycle can be left alone while the next print runs.
  3377. Some hardware dries happily through a print and #2758 settled that we
  3378. should not tear those cycles down: the X2D there was refusing to
  3379. *start* a job, which is a different problem, and stopping drying before
  3380. every dispatch would throw away cycles the printer was content to run.
  3381. Where the model cannot do it, or the user has not enabled it, the print
  3382. takes priority and the cycle stops -- which is what the queue_drying_block
  3383. setting has always promised in its off position.
  3384. """
  3385. if not await self._get_bool_setting(db, "print_drying_enabled"):
  3386. return False
  3387. status = printer_manager.get_status(printer_id)
  3388. return supports_drying_while_printing(
  3389. printer_manager.get_model(printer_id),
  3390. status.firmware_version if status else None,
  3391. )
  3392. async def _stop_drying(self, printer_id: int):
  3393. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  3394. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  3395. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  3396. enough to kill a cycle the user had started by hand on a *different*
  3397. unit of the same printer (#2801). That contradicted the contract
  3398. ``_sync_drying_state`` already documents -- the entry gate deliberately
  3399. only knows about cycles Bambuddy began, so the action must not reach
  3400. past them either.
  3401. """
  3402. state = printer_manager.get_status(printer_id)
  3403. if not state:
  3404. self._drying_in_progress.pop(printer_id, None)
  3405. return
  3406. ams_list = state.raw_data.get("ams", [])
  3407. for ams_data in ams_list:
  3408. dry_time = int(ams_data.get("dry_time") or 0)
  3409. if dry_time > 0:
  3410. ams_id = int(ams_data.get("id", 0))
  3411. if (printer_id, ams_id) not in self._auto_dry_units:
  3412. logger.debug(
  3413. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  3414. printer_id,
  3415. ams_id,
  3416. )
  3417. continue
  3418. logger.info(
  3419. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  3420. printer_id,
  3421. ams_id,
  3422. )
  3423. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  3424. self.forget_auto_dry_cycle(printer_id, ams_id)
  3425. self._drying_in_progress.pop(printer_id, None)
  3426. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  3427. """Get all smart plugs associated with a printer."""
  3428. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  3429. return list(result.scalars().all())
  3430. @staticmethod
  3431. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  3432. """Pick the plug to power-cycle a printer back online with (#2629).
  3433. Only a plug flagged ``controls_printer_power`` can actually bring the
  3434. printer back; waiting for a boot on an accessory (filter fan, lights)
  3435. just burns the power-on timeout and fails the dispatch. Falls back to
  3436. the first plug when none is flagged, which is the pre-#2629 behaviour.
  3437. Callers must pass a non-empty list.
  3438. """
  3439. for plug in auto_on_plugs:
  3440. if plug.controls_printer_power:
  3441. return plug
  3442. return auto_on_plugs[0]
  3443. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  3444. # chamber-temperature recommendations BambuStudio ships for the matching
  3445. # filament profile; users can override via Settings → Workflow → Preheat
  3446. # card. "default" applies when a loaded tray's normalised type isn't in
  3447. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  3448. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  3449. "PLA": 0,
  3450. "PETG": 0,
  3451. "PETG-CF": 40,
  3452. "ABS": 45,
  3453. "ASA": 45,
  3454. "PA": 50,
  3455. "PA-CF": 55,
  3456. "PC": 50,
  3457. "PC-FR": 50,
  3458. "TPU": 0,
  3459. "PVA": 0,
  3460. "default": 0,
  3461. }
  3462. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  3463. """Parse the user-configured filament→chamber-target map, falling back
  3464. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  3465. are uppercased and the 'default' fallback is always present in the
  3466. returned dict so the resolution loop can index it unconditionally."""
  3467. raw = await self._get_setting(db, "preheat_filament_targets")
  3468. if not raw:
  3469. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  3470. try:
  3471. parsed = json.loads(raw)
  3472. if not isinstance(parsed, dict):
  3473. raise ValueError("not an object")
  3474. except (json.JSONDecodeError, ValueError) as exc:
  3475. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  3476. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  3477. # Coerce values to int; drop unparseable rows so a stray string
  3478. # doesn't crash the loop.
  3479. out: dict[str, int] = {}
  3480. for key, value in parsed.items():
  3481. try:
  3482. out[str(key).upper()] = int(value)
  3483. except (TypeError, ValueError):
  3484. continue
  3485. if "DEFAULT" not in out:
  3486. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  3487. return out
  3488. @staticmethod
  3489. def _normalize_filament_type(tray_type: str) -> str:
  3490. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  3491. existing drying-preset normalisation (split-at-space, upper-case) so
  3492. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  3493. "PA-CF" (no space to split on)."""
  3494. return tray_type.split()[0].upper() if tray_type else ""
  3495. def _derive_chamber_target(
  3496. self,
  3497. printer: Printer,
  3498. targets: dict[str, int],
  3499. ) -> int:
  3500. """Look up the chamber target for each loaded AMS tray and return the
  3501. max. Returns 0 when no AMS data is available (e.g. external-spool
  3502. prints) or when every loaded slot maps to 0 — the chamber phase then
  3503. short-circuits in the main loop.
  3504. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  3505. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  3506. less slots have empty `tray_type` and contribute nothing."""
  3507. state = printer_manager.get_status(printer.id)
  3508. if state is None:
  3509. return 0
  3510. ams_list = (state.raw_data or {}).get("ams") if state.raw_data else None
  3511. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  3512. if isinstance(ams_list, dict):
  3513. ams_list = ams_list.get("ams") or []
  3514. if not isinstance(ams_list, list):
  3515. return 0
  3516. best = 0
  3517. for ams in ams_list:
  3518. for tray in (ams.get("tray") or []) if isinstance(ams, dict) else []:
  3519. normalised = self._normalize_filament_type(tray.get("tray_type") or "")
  3520. if not normalised:
  3521. continue
  3522. target = targets.get(normalised, targets.get("DEFAULT", 0))
  3523. if target > best:
  3524. best = target
  3525. return best
  3526. def _release_keep_warm(self, pid: int) -> None:
  3527. """Release keep-warm on a printer that left the candidate set.
  3528. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  3529. reports the target we set (``entry.held_target``), so a user or
  3530. subsequent print that changed the bed target since is not clobbered.
  3531. Best-effort, never raises.
  3532. The entry is kept, not dropped, when the printer cannot be reached
  3533. right now: a printer that is briefly offline still has a hot bed, and
  3534. holding the entry is what keeps the max-duration timeout applying and
  3535. lets a later tick retry the release. Only a printer that has left the
  3536. manager entirely gives up on that, in ``_sample_chamber_temps``.
  3537. """
  3538. entry = self._keep_warm.get(pid)
  3539. if entry is None:
  3540. return
  3541. state = printer_manager.get_status(pid)
  3542. client = printer_manager.get_client(pid)
  3543. if state is None or client is None:
  3544. logger.debug(
  3545. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  3546. pid,
  3547. )
  3548. return
  3549. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  3550. if int(cur_bed_target) != entry.held_target:
  3551. # Someone else owns the bed now, so there is nothing of ours to
  3552. # undo and nothing left to track.
  3553. logger.info(
  3554. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  3555. pid,
  3556. int(cur_bed_target),
  3557. entry.held_target,
  3558. )
  3559. self._keep_warm.pop(pid, None)
  3560. return
  3561. try:
  3562. client.set_bed_temperature(0)
  3563. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  3564. self._keep_warm.pop(pid, None)
  3565. except Exception as exc:
  3566. # Keep the entry so the next tick tries again rather than leaving
  3567. # the bed hot with nothing tracking it.
  3568. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  3569. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  3570. """Release printers that dropped out of the keep-warm candidate set.
  3571. Called from ``_apply_keep_warm`` on every tick (with the current
  3572. candidate set), and from ``check_queue``'s no-pending-items early
  3573. return (with an empty candidate set) so orphaned holds still get
  3574. released when the queue empties. Also called with an empty candidate
  3575. set when any of the three gate settings toggles off, so a printer
  3576. whose feature was disabled mid-hold gets its bed released.
  3577. Printers being dispatched this tick are excluded from the bed-off
  3578. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  3579. transient 0 in between would just churn against preheat. Ownership of
  3580. the hot bed transfers to the preheat rollback pin instead — if the
  3581. dispatch aborts before the print starts (failed upload, cancelled
  3582. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  3583. skips (e.g. the item has no bed_temperature metadata) the pin entry
  3584. is the ONLY thing standing between an aborted dispatch and a bed
  3585. left hot with no owner. A successful print start clears the pin and
  3586. the print's own gcode takes over, as usual.
  3587. """
  3588. for _pid in list(self._keep_warm):
  3589. if _pid in active_candidates:
  3590. continue
  3591. if _pid in dispatched:
  3592. handed_over = self._keep_warm.pop(_pid, None)
  3593. self._preheat_pin.setdefault(_pid, set()).add("bed")
  3594. if handed_over is not None:
  3595. self._preheat_pin_bed[_pid] = handed_over.held_target
  3596. continue
  3597. self._release_keep_warm(_pid)
  3598. async def _apply_keep_warm(
  3599. self,
  3600. db: AsyncSession,
  3601. items: list[PrintQueueItem],
  3602. dispatch_ids: list[int] | set[int],
  3603. busy_printers: set[int],
  3604. require_plate_clear: bool,
  3605. ) -> None:
  3606. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  3607. When a printer just finished a job (FINISH state) and the next queued
  3608. item needs chamber heating, hold the bed hot so the chamber stays warm
  3609. during the bed-clearing window. The bed is the chamber's heating
  3610. element here, not a print surface — nothing is printing during the
  3611. hold and the dispatched print's own preheat/gcode re-targets the bed —
  3612. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  3613. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  3614. aftermarket chamber heaters), raised to the item's own parsed
  3615. bed_temperature when that is higher. Items whose archive metadata has
  3616. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  3617. get a hold — chamber need is what gates the feature, not metadata.
  3618. Skips entirely for filaments that map to a 0°C chamber target
  3619. (PLA, PETG, etc.). Printers being dispatched this cycle are excluded:
  3620. ``_preheat_and_soak`` already handles their bed temperature.
  3621. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  3622. released to 0 and the entry is latched ``expired=True`` so
  3623. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  3624. MQTT: publish is skipped when firmware already has the target.
  3625. The release sweep runs BEFORE the engagement gate so a printer that
  3626. was owned by keep-warm still gets its bed released when any of the
  3627. three gate settings is toggled off mid-hold. The
  3628. ``check_queue`` early-return-when-no-items path also calls
  3629. ``_sweep_keep_warm`` directly to release orphaned holds.
  3630. """
  3631. dispatch_set = set(dispatch_ids)
  3632. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  3633. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  3634. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  3635. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  3636. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  3637. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  3638. # Release sweep first — must run even when gate_open is False so a
  3639. # printer owned by keep-warm when a gate toggles off gets released.
  3640. self._sweep_keep_warm(
  3641. active_candidates=warm_candidates if gate_open else set(),
  3642. dispatched=dispatched_printers,
  3643. )
  3644. if not gate_open:
  3645. return
  3646. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  3647. max_hold_seconds = (
  3648. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  3649. )
  3650. now_mono = time.monotonic()
  3651. filament_targets: dict[str, int] | None = None
  3652. for pid in warm_candidates:
  3653. entry = self._keep_warm.get(pid)
  3654. # Latched-expired: max-duration timeout already fired for this
  3655. # printer. Skip until the release sweep drops the entry (i.e.
  3656. # until the printer leaves the candidate set).
  3657. if entry is not None and entry.expired:
  3658. continue
  3659. # These two guards sit ahead of the max-duration check below, so an
  3660. # engaged hold only ages out while its printer is still reachable
  3661. # and still in FINISH. That is deliberate rather than a hole: with
  3662. # no status or no client there is no M140 to send anyway, and the
  3663. # elapsed check runs off `entry.started` so it fires on the first
  3664. # tick after the printer comes back. Leaving FINISH means the plate
  3665. # was cleared, which drops the printer out of `warm_candidates` and
  3666. # hands it to `_release_keep_warm` instead. The invariant worth
  3667. # preserving if this is ever reordered: every path out of an
  3668. # engaged hold ends in a bed-off, whether by timeout or release.
  3669. state = printer_manager.get_status(pid)
  3670. if state is None or state.state != "FINISH":
  3671. continue
  3672. client = printer_manager.get_client(pid)
  3673. if client is None:
  3674. continue
  3675. next_item = next((it for it in items if it.printer_id == pid), None)
  3676. if next_item is None:
  3677. continue
  3678. # Hold temperature: the configured keep-warm temp, raised to the
  3679. # item's own bed temp when the metadata reports a higher one. A
  3680. # missing bed_temperature (Orca gcode.3mf exports parse without
  3681. # one) does NOT skip the hold — chamber need gates the feature.
  3682. archive = next_item.archive
  3683. item_bed = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  3684. bed_target = max(item_bed, hold_temp)
  3685. if bed_target <= 0:
  3686. continue
  3687. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  3688. if explicit is not None:
  3689. chamber_needed = int(explicit) > 0
  3690. else:
  3691. if filament_targets is None:
  3692. filament_targets = await self._get_preheat_filament_targets(db)
  3693. printer_obj = await self._get_printer(db, pid)
  3694. chamber_needed = (
  3695. printer_obj is not None and self._derive_chamber_target(printer_obj, filament_targets) > 0
  3696. )
  3697. if not chamber_needed:
  3698. continue
  3699. # Seed the timer on first engagement; keep it on subsequent ticks
  3700. # (never re-seed — that would defeat the max-duration cap).
  3701. if entry is None:
  3702. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  3703. self._keep_warm[pid] = entry
  3704. elapsed = now_mono - entry.started
  3705. if elapsed > max_hold_seconds:
  3706. # Timeout: publish bed → 0 once (if firmware still holds our
  3707. # target) and latch expired. The entry stays until the release
  3708. # sweep drops it, preventing the next tick from re-seeding.
  3709. logger.warning(
  3710. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  3711. pid,
  3712. elapsed,
  3713. )
  3714. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  3715. if int(cur_bed_target) == entry.held_target:
  3716. try:
  3717. client.set_bed_temperature(0)
  3718. except Exception as exc:
  3719. logger.warning(
  3720. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  3721. pid,
  3722. exc,
  3723. )
  3724. else:
  3725. logger.info(
  3726. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  3727. pid,
  3728. int(cur_bed_target),
  3729. entry.held_target,
  3730. )
  3731. entry.expired = True
  3732. continue
  3733. # Idempotence: skip publish when firmware already has our target.
  3734. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  3735. if int(cur_bed_target) == bed_target:
  3736. entry.held_target = bed_target
  3737. continue
  3738. try:
  3739. client.set_bed_temperature(bed_target)
  3740. entry.held_target = bed_target
  3741. logger.info(
  3742. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  3743. bed_target,
  3744. pid,
  3745. )
  3746. except Exception as exc:
  3747. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  3748. def _sample_chamber_temps(self) -> None:
  3749. """Record a chamber temperature sample for every connected printer.
  3750. Called once per scheduler tick (every 3–30 s). Entries older than
  3751. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  3752. Also evicts per-printer state whose printer_id is no longer registered
  3753. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  3754. """
  3755. now = time.monotonic()
  3756. cutoff = now - self._chamber_history_ttl
  3757. statuses = printer_manager.get_all_statuses()
  3758. known_pids = set(statuses.keys())
  3759. for pid, status in statuses.items():
  3760. if status is None or not status.connected:
  3761. continue
  3762. temps = status.temperatures or {}
  3763. chamber = temps.get("chamber")
  3764. if chamber is None:
  3765. continue
  3766. hist = self._chamber_history.setdefault(pid, deque())
  3767. hist.append((now, float(chamber)))
  3768. while hist and hist[0][0] < cutoff:
  3769. hist.popleft()
  3770. # Evict state for printers that are no longer registered with the manager.
  3771. # This is the one place a keep-warm entry is dropped without releasing
  3772. # the bed: the printer is gone from the manager, so there is no client
  3773. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  3774. # for printers that are merely unreachable, which is what makes this
  3775. # the terminal case rather than a silent leak.
  3776. for pid in list(self._chamber_history):
  3777. if pid not in known_pids:
  3778. self._chamber_history.pop(pid, None)
  3779. for pid in list(self._keep_warm):
  3780. if pid not in known_pids:
  3781. logger.info(
  3782. "Queue: dropping keep-warm state for printer %d — no longer registered",
  3783. pid,
  3784. )
  3785. self._keep_warm.pop(pid, None)
  3786. for pid in list(self._preheat_pin):
  3787. if pid not in known_pids:
  3788. self._preheat_pin.pop(pid, None)
  3789. self._preheat_pin_bed.pop(pid, None)
  3790. def _chamber_soak_remaining(
  3791. self,
  3792. printer_id: int,
  3793. chamber_target: float,
  3794. soak_seconds: int,
  3795. tolerance: float = 2.0,
  3796. ) -> int:
  3797. """Return how many seconds of soak time are still needed.
  3798. Credits the time the chamber has already spent at temperature against
  3799. the configured soak. The credit may not start earlier than any of:
  3800. * **The newest sample.** Nothing recent means the printer stopped
  3801. reporting mid-observation and the chamber may have cooled unseen, so
  3802. the full soak is required. (A 2 h history whose last reading is half
  3803. an hour old is not evidence of anything — the measured cooling rate
  3804. is fast enough to cross the threshold in that time.)
  3805. * **The most recent contiguous run of samples.** A gap wider than
  3806. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  3807. far side is not evidence of temperature.
  3808. * **The end of the most recent real dip below the threshold.**
  3809. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  3810. — see that constant for the thermal reasoning. A stray low reading is
  3811. an artifact, and treating it as cooling would discard a soak that
  3812. actually happened.
  3813. Returns ``soak_seconds`` when nothing can be credited (no history,
  3814. stale history, or the chamber is below the threshold right now) and 0
  3815. once the credited time covers the whole soak.
  3816. """
  3817. hist = self._chamber_history.get(printer_id)
  3818. if not hist:
  3819. return soak_seconds
  3820. now = time.monotonic()
  3821. newest_ts, newest_temp = hist[-1]
  3822. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  3823. return soak_seconds # stale — no fresh evidence to credit
  3824. threshold = chamber_target - tolerance
  3825. if newest_temp < threshold:
  3826. return soak_seconds # below target right now; nothing is soaked
  3827. samples = list(hist)
  3828. # Earliest point we have unbroken observations for.
  3829. credit_from = samples[-1][0]
  3830. for i in range(len(samples) - 1, 0, -1):
  3831. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  3832. break
  3833. credit_from = samples[i - 1][0]
  3834. # Pull the credit forward to the end of the last significant dip. Each
  3835. # excursion is measured between the in-range readings that bracket it,
  3836. # so a lone stray sample is charged one sampling interval rather than
  3837. # zero, and the comparison errs towards calling a dip real.
  3838. i = 0
  3839. while i < len(samples):
  3840. if samples[i][1] >= threshold:
  3841. i += 1
  3842. continue
  3843. j = i
  3844. while j < len(samples) and samples[j][1] < threshold:
  3845. j += 1
  3846. # `newest_temp >= threshold` was checked above, so j is in range.
  3847. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  3848. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  3849. # Credit resumes at the last below-threshold sample rather than
  3850. # the first good one after it, so a recovered dip over-credits
  3851. # by up to one sampling interval — the opposite lean to the
  3852. # bracketing above. Both are bounded by the sample cadence and
  3853. # dwarfed by the grace period, so neither is worth the extra
  3854. # arithmetic to remove.
  3855. credit_from = max(credit_from, samples[j - 1][0])
  3856. i = j
  3857. return max(0, soak_seconds - int(now - credit_from))
  3858. def notify_dispatch_cancelled(self, item_id: int) -> None:
  3859. """Tell an in-flight dispatch that its item no longer wants to print.
  3860. Called by the queue's cancel and delete routes. Those only write to the
  3861. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  3862. observe — so preheat would keep heating for the rest of max_wait + soak
  3863. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  3864. blocking every other queued item behind a print that is not happening.
  3865. Signalling in memory rather than re-reading the row keeps this off the
  3866. database entirely: no second session, no transaction held across a long
  3867. sleep, and no snapshot staleness deciding whether a print goes ahead.
  3868. Bambuddy serves from a single uvicorn process with one scheduler task,
  3869. so the route and the dispatch always share this object. The flag is
  3870. advisory — dropping it (e.g. after a restart) only costs a wasted
  3871. preheat, never a wrongly-abandoned print.
  3872. Only ids with a dispatch actually in flight are recorded, so the set
  3873. stays bounded by the upload pool rather than growing once per cancelled
  3874. item for the life of the process. Skipping the rest loses nothing: an
  3875. item that is not in flight cannot start heating later either, because
  3876. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  3877. the caller has already committed a terminal status (or deleted the row)
  3878. before calling this.
  3879. """
  3880. if item_id in self._inflight:
  3881. self._cancelled_dispatches.add(item_id)
  3882. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  3883. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  3884. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  3885. while it is parked, so the wait is chopped into
  3886. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  3887. """
  3888. remaining = float(seconds)
  3889. while remaining > 0:
  3890. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  3891. await asyncio.sleep(slice_secs)
  3892. remaining -= slice_secs
  3893. if item_id in self._cancelled_dispatches:
  3894. return False
  3895. return True
  3896. async def _preheat_and_soak(
  3897. self,
  3898. db: AsyncSession,
  3899. item: PrintQueueItem,
  3900. printer: Printer,
  3901. archive: PrintArchive | None,
  3902. ) -> bool:
  3903. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  3904. Returns True when the dispatch should carry on to the upload — including
  3905. every case where preheat is skipped, since a skipped preheat is not a
  3906. reason to abandon the print. Returns False only when the item stopped
  3907. wanting to be printed while the stage was waiting (cancelled or
  3908. deleted); the caller must then abandon the dispatch, and
  3909. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  3910. Resolution order:
  3911. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  3912. to the global `preheat_enabled` setting; 'on' forces the stage on
  3913. even if the global is off.
  3914. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  3915. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  3916. across loaded AMS slots; else 0 (skips chamber phase, keeps bed
  3917. phase + soak timer).
  3918. 3. Three hardware tiers branch the wait loop:
  3919. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  3920. send M141 to the resolved target, then wait for the chamber sensor
  3921. to reach it (or the max-wait timeout to elapse).
  3922. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  3923. no M141; the bed is the only heat source, so we wait for the chamber
  3924. sensor to rise via bed radiation OR fall through on timeout.
  3925. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  3926. temperature; the function just heats the bed and holds for the
  3927. configured soak duration.
  3928. The bed target comes from the archive's parsed metadata
  3929. (`bed_temperature`); if missing the preheat stage logs and returns
  3930. without dispatching anything, rather than guessing at a default that
  3931. might wreck filament setup.
  3932. Failures are logged but never re-raised — preheat is best-effort. A
  3933. printer that goes offline mid-soak, a refused gcode command, or a
  3934. missing temperature reading must not turn into a failed queue item; the
  3935. normal upload + start path runs immediately after this method returns.
  3936. """
  3937. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  3938. if override == "off":
  3939. return True
  3940. if override == "inherit":
  3941. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  3942. if not enabled:
  3943. return True
  3944. # override == "on" forces the stage on regardless of the global setting.
  3945. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  3946. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  3947. # Chamber target resolution:
  3948. # 1. Explicit per-item override beats everything (user knows best).
  3949. # 2. Otherwise derive from loaded AMS filament types via the per-
  3950. # filament target map. PLA-only print derives 0 → chamber phase
  3951. # auto-skips without the user touching anything.
  3952. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  3953. if explicit_target is not None and explicit_target > 0:
  3954. chamber_target = int(explicit_target)
  3955. chamber_source = "item-override"
  3956. elif explicit_target == 0:
  3957. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  3958. chamber_source = "item-override-zero"
  3959. else:
  3960. targets = await self._get_preheat_filament_targets(db)
  3961. chamber_target = self._derive_chamber_target(printer, targets)
  3962. chamber_source = "filament-map"
  3963. bed_target = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  3964. if bed_target <= 0:
  3965. # No bed temperature in the slicer metadata. When the print needs a
  3966. # hot chamber the bed is simply how we heat it, so fall back to the
  3967. # configured chamber-heating bed temperature rather than skipping
  3968. # the whole stage — otherwise the print starts with a cold chamber,
  3969. # which is exactly what preheat exists to prevent. Without a chamber
  3970. # requirement there is nothing to preheat *for*, so skip as before
  3971. # rather than guess a bed temperature for the print itself.
  3972. if chamber_target <= 0:
  3973. logger.info(
  3974. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  3975. item.id,
  3976. )
  3977. return True
  3978. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  3979. logger.info(
  3980. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  3981. "%d°C to drive the chamber to %d°C",
  3982. item.id,
  3983. bed_target,
  3984. chamber_target,
  3985. )
  3986. client = printer_manager.get_client(printer.id)
  3987. if client is None:
  3988. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  3989. return True
  3990. model = printer.model or ""
  3991. has_heater = supports_chamber_heater(model)
  3992. has_sensor = supports_chamber_temp(model)
  3993. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  3994. # Fast path: if the chamber has been continuously above target for at
  3995. # least soak_seconds and the bed is already at temperature, skip the
  3996. # entire preheat stage. Typical case: keep-warm held the bed between
  3997. # consecutive same-material prints and the chamber never dropped.
  3998. if do_chamber and has_sensor and soak_seconds > 0:
  3999. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  4000. if remaining == 0:
  4001. cur = printer_manager.get_status(printer.id)
  4002. if cur:
  4003. cur_temps = cur.temperatures or {}
  4004. if (
  4005. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  4006. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  4007. ):
  4008. logger.info(
  4009. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  4010. "and bed is already at temperature (chamber history fast-path)",
  4011. item.id,
  4012. chamber_target,
  4013. soak_seconds,
  4014. )
  4015. # Still set targets to prevent cooling during the 3MF upload window.
  4016. # Register each successful set in the preheat pin so `_dispatch_one`
  4017. # unwinds them on any non-success exit.
  4018. pin = self._preheat_pin.setdefault(printer.id, set())
  4019. try:
  4020. client.set_bed_temperature(bed_target)
  4021. pin.add("bed")
  4022. self._preheat_pin_bed[printer.id] = bed_target
  4023. except Exception as exc:
  4024. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  4025. if supports_airduct(model):
  4026. cur_airduct = getattr(cur, "airduct_mode", None)
  4027. if cur_airduct != _AIRDUCT_MODE_HEATING:
  4028. try:
  4029. client.set_airduct_mode("heating")
  4030. # Only undo what we can see we replaced. `None`
  4031. # means no mode has been observed yet, and
  4032. # rolling that back to cooling would assert a
  4033. # state the printer never reported.
  4034. if cur_airduct == _AIRDUCT_MODE_COOLING:
  4035. pin.add("airduct")
  4036. except Exception as exc:
  4037. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  4038. if has_heater:
  4039. try:
  4040. client.set_chamber_temperature(chamber_target)
  4041. pin.add("chamber")
  4042. except Exception as exc:
  4043. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  4044. return True
  4045. logger.info(
  4046. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  4047. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  4048. item.id,
  4049. bed_target,
  4050. chamber_target if do_chamber else 0,
  4051. chamber_source,
  4052. override,
  4053. model,
  4054. has_heater,
  4055. has_sensor,
  4056. max_wait,
  4057. soak_seconds,
  4058. )
  4059. # Preheat rollback registry: everything we set below is recorded here so
  4060. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  4061. # (bed off, chamber off, airduct back to cooling) on any non-success
  4062. # exit. Populated as each command succeeds; consumed and cleared by
  4063. # `_dispatch_one`.
  4064. pin = self._preheat_pin.setdefault(printer.id, set())
  4065. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  4066. # cache the target locally so the polling reads below see consistent
  4067. # state (firmware MQTT echoes lag by ~1s).
  4068. try:
  4069. client.set_bed_temperature(bed_target)
  4070. pin.add("bed")
  4071. self._preheat_pin_bed[printer.id] = bed_target
  4072. except Exception as exc:
  4073. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  4074. return True
  4075. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  4076. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  4077. # left it on, regardless of M141. Default cooling actively vents the
  4078. # chamber, so a `chamber_target > 0` print with the flap stuck in
  4079. # cooling never converges — the heater fights the open exhaust. We
  4080. # flip the flap BEFORE M141 to "heating" when the preheat wants
  4081. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  4082. # on an H2D that was previously running ABS would otherwise stay in
  4083. # heating mode and overheat PLA). The current-state read keeps the
  4084. # command idempotent — no MQTT chatter when the flap is already where
  4085. # we want it.
  4086. if supports_airduct(model):
  4087. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  4088. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  4089. current_state = printer_manager.get_status(printer.id)
  4090. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  4091. if current_airduct != desired_id:
  4092. try:
  4093. client.set_airduct_mode(desired_airduct)
  4094. # As in the fast path: only pin a rollback for a flap we
  4095. # saw in cooling. `current_airduct` of None means no mode
  4096. # has been observed, so there is nothing to restore to.
  4097. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  4098. pin.add("airduct")
  4099. except Exception as exc:
  4100. logger.warning(
  4101. "Queue item %s: preheat airduct %s mode failed: %s",
  4102. item.id,
  4103. desired_airduct,
  4104. exc,
  4105. )
  4106. if do_chamber and has_heater:
  4107. try:
  4108. client.set_chamber_temperature(chamber_target)
  4109. pin.add("chamber")
  4110. except Exception as exc:
  4111. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  4112. # Release the pooled DB connection before the (potentially many-minute)
  4113. # heat-soak wait below (#2572). Every setting this method needs is read
  4114. # above; the wait/soak loop only polls printer_manager state and sleeps —
  4115. # it never touches the DB. Without this the caller's transaction sat
  4116. # "idle in transaction" for the whole soak, pinning one pooled connection
  4117. # per preheating printer. expire_on_commit=False keeps item/printer
  4118. # readable afterwards; there are no pending writes to lose here.
  4119. await db.commit()
  4120. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  4121. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  4122. # Poll every 3s — frequent enough for responsive logging without
  4123. # spamming the MQTT state stream. The "converged" predicate is:
  4124. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  4125. # AND
  4126. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  4127. BED_TOLERANCE = 2.0
  4128. CHAMBER_TOLERANCE = 2.0
  4129. POLL_INTERVAL = 3.0
  4130. deadline = asyncio.get_event_loop().time() + max_wait
  4131. while True:
  4132. state = printer_manager.get_status(printer.id)
  4133. if state is None:
  4134. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  4135. break
  4136. temps = state.temperatures or {}
  4137. bed_now = float(temps.get("bed", 0) or 0)
  4138. chamber_now = float(temps.get("chamber", 0) or 0)
  4139. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  4140. if not do_chamber:
  4141. chamber_ok = True # phase disabled or model has neither sensor nor heater
  4142. elif not has_sensor:
  4143. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  4144. else:
  4145. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  4146. if bed_ok and chamber_ok:
  4147. logger.info(
  4148. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  4149. item.id,
  4150. bed_now,
  4151. chamber_now,
  4152. )
  4153. break
  4154. if asyncio.get_event_loop().time() >= deadline:
  4155. logger.info(
  4156. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  4157. item.id,
  4158. bed_now,
  4159. bed_target,
  4160. chamber_now,
  4161. chamber_target if do_chamber else 0,
  4162. )
  4163. break
  4164. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  4165. logger.info(
  4166. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  4167. item.id,
  4168. )
  4169. return False
  4170. if soak_seconds > 0:
  4171. if do_chamber and has_sensor:
  4172. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  4173. else:
  4174. remaining = soak_seconds # no sensor — can't verify history, run full soak
  4175. if remaining > 0:
  4176. logger.info(
  4177. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  4178. "has been above target for ~%ds already)",
  4179. item.id,
  4180. remaining,
  4181. soak_seconds,
  4182. soak_seconds - remaining,
  4183. )
  4184. if not await self._preheat_sleep(item.id, remaining):
  4185. logger.info(
  4186. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  4187. item.id,
  4188. )
  4189. return False
  4190. else:
  4191. logger.info(
  4192. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  4193. item.id,
  4194. chamber_target,
  4195. soak_seconds,
  4196. )
  4197. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  4198. return True
  4199. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  4200. """Turn on smart plug and wait for printer to connect.
  4201. Returns True if printer connected successfully within timeout.
  4202. """
  4203. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  4204. service = await smart_plug_manager.get_service_for_plug(plug, db)
  4205. # Check current plug state
  4206. status = await service.get_status(plug)
  4207. if not status.get("reachable"):
  4208. logger.warning("Smart plug '%s' is not reachable", plug.name)
  4209. return False
  4210. # Turn on if not already on
  4211. if status.get("state") != "ON":
  4212. success = await service.turn_on(plug)
  4213. if not success:
  4214. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  4215. return False
  4216. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  4217. # Get printer from database for connection
  4218. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4219. printer = result.scalar_one_or_none()
  4220. if not printer:
  4221. logger.error("Printer %s not found in database", printer_id)
  4222. return False
  4223. # Wait for printer to boot (give it some time before trying to connect)
  4224. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  4225. await asyncio.sleep(30)
  4226. # Try to connect to the printer periodically
  4227. elapsed = 30 # Already waited 30s
  4228. while elapsed < self._power_on_wait_time:
  4229. # Try to connect
  4230. logger.info("Attempting to connect to printer %s...", printer_id)
  4231. try:
  4232. connected = await printer_manager.connect_printer(printer)
  4233. if connected:
  4234. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  4235. # Give it a moment to stabilize and get status
  4236. await asyncio.sleep(5)
  4237. return True
  4238. except Exception as e:
  4239. logger.debug("Connection attempt failed: %s", e)
  4240. await asyncio.sleep(self._power_on_check_interval)
  4241. elapsed += self._power_on_check_interval
  4242. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  4243. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  4244. return False
  4245. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  4246. """Check if the previous print on this printer succeeded.
  4247. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  4248. deliberate action, not a failure, so subsequent items should still
  4249. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  4250. a skip isn't an actual print attempt, so it must not gate downstream
  4251. items — counting it as a failed predecessor was the cascade bug that
  4252. let a single cancellation block 18 items over 3 days for the reporter.
  4253. Only `failed` and `aborted` — real print-attempt failures — block.
  4254. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  4255. action — #1818) are also excluded from the lookback so the user can
  4256. clear the gate after fixing the physical issue without having to
  4257. re-queue every downstream job.
  4258. """
  4259. result = await db.execute(
  4260. select(PrintQueueItem)
  4261. .where(PrintQueueItem.printer_id == item.printer_id)
  4262. .where(PrintQueueItem.id != item.id)
  4263. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  4264. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  4265. .order_by(PrintQueueItem.completed_at.desc())
  4266. .limit(1)
  4267. )
  4268. prev_item = result.scalar_one_or_none()
  4269. # If no previous item, assume success (first in queue)
  4270. if not prev_item:
  4271. return True
  4272. return prev_item.status in ("completed", "cancelled")
  4273. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  4274. """Schedule power-off if the queue item enabled auto_off_after.
  4275. Delegates to the smart-plug manager so the off honours each plug's
  4276. configured strategy (time delay or temperature threshold), is cancelled
  4277. if the printer starts printing again, and never cuts power on a loaded
  4278. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  4279. powered off on the timeout regardless of print state.
  4280. """
  4281. if not item.auto_off_after:
  4282. return
  4283. try:
  4284. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  4285. except Exception as e:
  4286. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  4287. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  4288. """Get a human-readable name for a queue item."""
  4289. if item.archive_id:
  4290. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  4291. archive = result.scalar_one_or_none()
  4292. if archive:
  4293. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  4294. if item.library_file_id:
  4295. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  4296. library_file = result.scalar_one_or_none()
  4297. if library_file:
  4298. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  4299. # A cross-model item (#671) holds no file of its own until a printer is
  4300. # picked, so name it after its first candidate — otherwise every waiting
  4301. # notification for one reads "Job #12". Queried rather than read off
  4302. # item.variants because callers outside the selection loop have not
  4303. # eager-loaded them, and a lazy load raises in async.
  4304. first_variant_name = (
  4305. await db.execute(
  4306. select(LibraryFile.filename)
  4307. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  4308. .where(PrintQueueVariant.queue_item_id == item.id)
  4309. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  4310. .limit(1)
  4311. )
  4312. ).scalar_one_or_none()
  4313. if first_variant_name:
  4314. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  4315. return f"Job #{item.id}"
  4316. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  4317. """Get printer by ID."""
  4318. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4319. return result.scalar_one_or_none()
  4320. async def _notify_dispatch_gave_up(
  4321. self,
  4322. queue_item_id: int,
  4323. printer_id: int,
  4324. created_by_id: int | None,
  4325. reason: str = "Printer accepted the file but never started printing",
  4326. ) -> None:
  4327. """Tell the user the queue item was failed after exhausting its dispatch retries.
  4328. Called from the watchdog, which is a background task with no session of
  4329. its own — hence the fresh one here. Best-effort throughout: the row is
  4330. already marked failed and that is the load-bearing part; a notification
  4331. provider being down must not resurrect the retry loop we just stopped.
  4332. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  4333. path passes its own, because "accepted the file but never started" is the
  4334. opposite of what happened there — the printer refused it outright (#2732).
  4335. """
  4336. try:
  4337. async with async_session() as db:
  4338. item = await db.get(PrintQueueItem, queue_item_id)
  4339. if not item:
  4340. return
  4341. job_name = await self._get_job_name(db, item)
  4342. printer = await self._get_printer(db, printer_id)
  4343. await notification_service.on_queue_job_failed(
  4344. job_name=job_name,
  4345. printer_id=printer_id,
  4346. printer_name=printer.name if printer else "Unknown",
  4347. reason=reason,
  4348. db=db,
  4349. )
  4350. except Exception as e:
  4351. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  4352. try:
  4353. await ws_manager.send_queue_item_failed(
  4354. user_id=created_by_id,
  4355. queue_item_id=queue_item_id,
  4356. printer_id=printer_id,
  4357. reason="never_started",
  4358. )
  4359. except Exception:
  4360. pass # toast is best-effort
  4361. async def _block_on_filament_deficit(
  4362. self,
  4363. db: AsyncSession,
  4364. item: PrintQueueItem,
  4365. ) -> bool:
  4366. """Promote the item to manual_start when the assigned spool is short (#1496).
  4367. Returns True when this dispatch attempt was blocked, False when the
  4368. item is clear to start. A previously-flagged item whose spool has
  4369. since been swapped to one with enough material clears the flag here
  4370. so the next scheduler tick dispatches it.
  4371. """
  4372. # User has explicitly acknowledged the deficit ("Print Anyway") —
  4373. # don't re-flag, don't even compute. Without this short-circuit the
  4374. # scheduler bounces between "user said anyway" (route clears
  4375. # manual_start) and "scheduler re-blocked" (this method re-flags it
  4376. # on identical spool state) (#1698-followup).
  4377. if item.skip_filament_check:
  4378. # #1762 diagnostic: surface the short-circuit at INFO so a
  4379. # future "Print Anyway didn't work" report (e.g. issue #1762
  4380. # comment 3) has actionable evidence in the support bundle
  4381. # without needing DEBUG enabled.
  4382. logger.info(
  4383. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  4384. item.id,
  4385. )
  4386. return False
  4387. try:
  4388. deficit = await compute_deficit_for_queue_item(db, item)
  4389. except Exception as e:
  4390. # Never let a flaky deficit check wedge the queue — log and let
  4391. # dispatch proceed. The PrintModal-side check still runs on the
  4392. # manual paths.
  4393. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  4394. return False
  4395. if deficit:
  4396. item.filament_short = True
  4397. item.manual_start = True
  4398. await db.commit()
  4399. job_name = await self._get_job_name(db, item)
  4400. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  4401. logger.info(
  4402. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  4403. item.id,
  4404. len(deficit),
  4405. )
  4406. try:
  4407. await notification_service.on_queue_job_waiting(
  4408. job_name=job_name,
  4409. target_model=(printer.model if printer else "") or "",
  4410. waiting_reason="filament_short",
  4411. db=db,
  4412. )
  4413. except Exception as e:
  4414. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  4415. return True
  4416. # No deficit — clear any stale flag from a previous tick.
  4417. if item.filament_short:
  4418. item.filament_short = False
  4419. await db.commit()
  4420. return False
  4421. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  4422. """Hand the queue item's owner to printer_manager so the
  4423. print-complete callback can credit the user in PrintLogEntry (#1670).
  4424. No-ops when the item has no `created_by_id` or the referenced user
  4425. row is missing (e.g. user deleted between queue-add and dispatch —
  4426. in that case the print log row falls back to the existing un-credited
  4427. behaviour rather than crashing the dispatch).
  4428. """
  4429. if not item.created_by_id:
  4430. return
  4431. from backend.app.models.user import User
  4432. owner = await db.get(User, item.created_by_id)
  4433. if owner:
  4434. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username)
  4435. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  4436. """Upload file and start print for a queue item.
  4437. Supports two sources:
  4438. - archive_id: Print from an existing archive
  4439. - library_file_id: Print from a library file (file manager)
  4440. """
  4441. logger.info("Starting queue item %s", item.id)
  4442. # Also covers a reservation left active by a process interruption
  4443. # during an earlier attempt. `_dispatch_one` releases this marker on
  4444. # every exit unless start_print() confirms that the command was sent.
  4445. self._unconfirmed_budget_reservations.add(item.id)
  4446. try:
  4447. from backend.app.models.user import User
  4448. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  4449. # Recompute at the final authorization boundary as well as enqueue
  4450. # time. This covers rows created before the server-side estimate
  4451. # migration and prevents any alternate write path from weakening
  4452. # the budget reservation.
  4453. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  4454. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  4455. item.estimated_cost = await estimate_queue_source_cost(
  4456. db,
  4457. archive=archive,
  4458. library_file=library_file,
  4459. plate_id=item.plate_id,
  4460. ams_mapping=item.ams_mapping,
  4461. printer_id=item.printer_id,
  4462. )
  4463. await validate_print_budget(
  4464. db,
  4465. cost_center_id=item.cost_center_id,
  4466. estimated_cost=item.estimated_cost,
  4467. current_user=queue_user,
  4468. exclude_queue_item_id=item.id,
  4469. exclude_reservation_source_type="print_queue",
  4470. exclude_reservation_source_id=item.id,
  4471. )
  4472. budget_reservation = await create_budget_reservation(
  4473. db,
  4474. cost_center_id=item.cost_center_id,
  4475. estimated_cost=item.estimated_cost,
  4476. current_user=queue_user,
  4477. source_type="print_queue",
  4478. source_id=item.id,
  4479. print_archive_id=item.archive_id,
  4480. exclude_queue_item_id=item.id,
  4481. )
  4482. await db.commit()
  4483. except HTTPException as exc:
  4484. item.status = "failed"
  4485. item.error_message = str(exc.detail)
  4486. item.completed_at = datetime.now(timezone.utc)
  4487. await db.commit()
  4488. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  4489. await self._power_off_if_needed(db, item)
  4490. return
  4491. # Get printer first (needed for both paths)
  4492. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  4493. printer = result.scalar_one_or_none()
  4494. if not printer:
  4495. item.status = "failed"
  4496. item.error_message = "Printer not found"
  4497. item.completed_at = datetime.now(timezone.utc)
  4498. await db.commit()
  4499. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  4500. await self._power_off_if_needed(db, item)
  4501. return
  4502. # Check printer is connected
  4503. if not printer_manager.is_connected(item.printer_id):
  4504. item.status = "failed"
  4505. item.error_message = "Printer not connected"
  4506. item.completed_at = datetime.now(timezone.utc)
  4507. await db.commit()
  4508. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  4509. await self._power_off_if_needed(db, item)
  4510. return
  4511. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  4512. # `items` was taken at the top of check_queue, but the user can /cancel
  4513. # any pending row in the gap before we reach this point. Re-read the
  4514. # row and bail out cleanly instead of starting an FTP upload for a row
  4515. # that's already cancelled. The atomic CAS at the pending→printing
  4516. # transition (below, before start_print) is the load-bearing guard;
  4517. # this is the early-exit optimisation that avoids wasted FTP I/O.
  4518. await db.refresh(item)
  4519. if item.status != "pending":
  4520. logger.info(
  4521. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  4522. item.id,
  4523. item.status,
  4524. )
  4525. return
  4526. # Busy-printer guard (#2598). check_queue gates dispatch on
  4527. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  4528. # keep reporting FINISH for tens of seconds *after* it accepted a
  4529. # project_file (see the watchdog's phase-B note). A watchdog revert
  4530. # (#2555) also releases the dispatch hold, so a re-selected item can
  4531. # reach here while its printer has actually started printing. Uploading
  4532. # and dispatching then collides with the live job — the firmware answers
  4533. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  4534. # live state right before the expensive FTP upload: if the printer is
  4535. # busy, leave the item pending and let a later tick dispatch it once the
  4536. # printer is genuinely idle. No wasted upload, no collision.
  4537. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  4538. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  4539. logger.info(
  4540. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  4541. "leaving item pending for a later tick (#2598)",
  4542. item.id,
  4543. item.printer_id,
  4544. pre_dispatch_state,
  4545. )
  4546. return
  4547. # Determine source: archive or library file
  4548. archive = None
  4549. library_file = None
  4550. file_path = None
  4551. filename = None
  4552. cleanup_disk_paths: list[Path] = []
  4553. if item.archive_id:
  4554. # Print from archive
  4555. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  4556. archive = result.scalar_one_or_none()
  4557. if not archive:
  4558. item.status = "failed"
  4559. item.error_message = "Archive not found"
  4560. item.completed_at = datetime.now(timezone.utc)
  4561. await db.commit()
  4562. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  4563. await self._power_off_if_needed(db, item)
  4564. return
  4565. # Persist the queue item's selected plate onto the archive so Print
  4566. # History can show the actual plate after cancel/fail/complete (#2603).
  4567. # Only when the archive doesn't already carry one, so a reprint of a
  4568. # plate-specific archive isn't relabelled by a differently-plated
  4569. # queue row.
  4570. if archive.plate_id is None and item.plate_id is not None:
  4571. archive.plate_id = item.plate_id
  4572. file_path = settings.base_dir / archive.file_path
  4573. filename = archive.filename
  4574. elif item.library_file_id:
  4575. # Print from library file (file manager)
  4576. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  4577. library_file = result.scalar_one_or_none()
  4578. if not library_file:
  4579. item.status = "failed"
  4580. item.error_message = "Library file not found"
  4581. item.completed_at = datetime.now(timezone.utc)
  4582. await db.commit()
  4583. logger.error("Queue item %s: Library file %s not found", item.id, item.library_file_id)
  4584. await self._power_off_if_needed(db, item)
  4585. return
  4586. # Library files store absolute paths
  4587. lib_path = Path(library_file.file_path)
  4588. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  4589. filename = library_file.filename
  4590. # Create archive from library file so usage tracking has access to the 3MF
  4591. queue_item_id = item.id
  4592. try:
  4593. from backend.app.services.archive import ArchiveService
  4594. archive_service = ArchiveService(db)
  4595. archive = await archive_service.archive_print(
  4596. printer_id=item.printer_id,
  4597. source_file=file_path,
  4598. original_filename=filename,
  4599. created_by_id=item.created_by_id,
  4600. project_id=item.project_id,
  4601. cost_center_id=item.cost_center_id,
  4602. library_file_id=item.library_file_id, # per-file project progress (#1897)
  4603. plate_id=item.plate_id, # selected plate → Print History (#2603)
  4604. )
  4605. if archive:
  4606. item.archive_id = archive.id
  4607. if budget_reservation is not None:
  4608. budget_reservation.print_archive_id = archive.id
  4609. if item.cleanup_library_after_dispatch and not library_file.is_external:
  4610. item.library_file_id = None
  4611. cleanup_disk_paths.append(file_path)
  4612. if library_file.thumbnail_path:
  4613. thumb_path = Path(library_file.thumbnail_path)
  4614. if not thumb_path.is_absolute():
  4615. thumb_path = settings.base_dir / library_file.thumbnail_path
  4616. cleanup_disk_paths.append(thumb_path)
  4617. await db.delete(library_file)
  4618. file_path = settings.base_dir / archive.file_path
  4619. filename = archive.filename
  4620. # Commit, not flush — flush opens the SQLite write
  4621. # transaction (item.archive_id update + library_file
  4622. # delete) and would hold the WAL writer lock through the
  4623. # FTP upload below, causing "database is locked" cascades
  4624. # for sensor history + concurrent cancels (#1853).
  4625. await db.commit()
  4626. logger.info(
  4627. "Queue item %s: Created archive %s from library file %s",
  4628. item.id,
  4629. archive.id,
  4630. item.library_file_id,
  4631. )
  4632. except Exception as e:
  4633. logger.warning(
  4634. "Queue item %s: Failed to create archive from library file: %s",
  4635. queue_item_id,
  4636. e,
  4637. exc_info=True,
  4638. )
  4639. await db.rollback()
  4640. item = await db.get(PrintQueueItem, queue_item_id)
  4641. if item:
  4642. item.status = "failed"
  4643. item.error_message = "Failed to create archive from library file"
  4644. item.completed_at = datetime.now(timezone.utc)
  4645. await db.commit()
  4646. await self._power_off_if_needed(db, item)
  4647. return
  4648. if not archive:
  4649. item.status = "failed"
  4650. item.error_message = "Failed to create archive from library file"
  4651. item.completed_at = datetime.now(timezone.utc)
  4652. await db.commit()
  4653. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  4654. await self._power_off_if_needed(db, item)
  4655. return
  4656. else:
  4657. # Neither archive nor library file specified
  4658. item.status = "failed"
  4659. item.error_message = "No source file specified"
  4660. item.completed_at = datetime.now(timezone.utc)
  4661. await db.commit()
  4662. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  4663. await self._power_off_if_needed(db, item)
  4664. return
  4665. # Check file exists on disk
  4666. if not file_path.exists():
  4667. item.status = "failed"
  4668. item.error_message = "Source file not found on disk"
  4669. item.completed_at = datetime.now(timezone.utc)
  4670. await db.commit()
  4671. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  4672. await self._power_off_if_needed(db, item)
  4673. return
  4674. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  4675. # size dispatched to a printer with a different nozzle installed is
  4676. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  4677. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  4678. # gives the user no idea what went wrong. Catch it here, before we spend
  4679. # time preheating and uploading, and fail with an actionable message.
  4680. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  4681. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  4682. # the printer hasn't reported its nozzles yet, we fall through and let the
  4683. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  4684. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  4685. # as one of the two hotends is a 0.6.
  4686. sliced_nozzle = archive.nozzle_diameter if archive else None
  4687. if sliced_nozzle:
  4688. installed = _installed_nozzle_diameters(printer_manager.get_status(item.printer_id))
  4689. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed)
  4690. if mismatch_msg:
  4691. item.status = "failed"
  4692. item.error_message = mismatch_msg
  4693. item.completed_at = datetime.now(timezone.utc)
  4694. await db.commit()
  4695. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  4696. await notification_service.on_queue_job_failed(
  4697. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  4698. printer_id=printer.id,
  4699. printer_name=printer.name,
  4700. reason=mismatch_msg,
  4701. db=db,
  4702. )
  4703. try:
  4704. await ws_manager.send_queue_item_failed(
  4705. user_id=item.created_by_id,
  4706. queue_item_id=item.id,
  4707. printer_id=item.printer_id,
  4708. reason="nozzle_mismatch",
  4709. )
  4710. except Exception:
  4711. pass
  4712. await self._power_off_if_needed(db, item)
  4713. return
  4714. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  4715. # bed (and chamber, if applicable) is at temperature when the firmware
  4716. # starts the actual print routine. Best-effort: any failure logs and
  4717. # falls through to the normal upload+start path rather than turning a
  4718. # configuration issue into a failed queue item.
  4719. # Returns False only when the item was cancelled or deleted while the
  4720. # stage was holding at temperature. Uploading and starting it anyway
  4721. # would print a job the user has already called off, so abandon the
  4722. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  4723. if not await self._preheat_and_soak(db, item, printer, archive):
  4724. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  4725. return
  4726. # G-code injection for auto-print systems (#422)
  4727. injected_path = None
  4728. # #2547: tracked separately from `injected_path`, which is also set when
  4729. # only a START snippet was injected. Only an END snippet changes what the
  4730. # camera sees at print completion.
  4731. end_gcode_injected = False
  4732. if item.gcode_injection:
  4733. try:
  4734. snippets_raw = await self._get_setting(db, "gcode_snippets")
  4735. if snippets_raw:
  4736. snippets = json.loads(snippets_raw)
  4737. model_snippets = snippets.get(printer.model, {})
  4738. start_gc = (model_snippets.get("start_gcode") or "").strip()
  4739. end_gc = (model_snippets.get("end_gcode") or "").strip()
  4740. if start_gc or end_gc:
  4741. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  4742. injected_path = inject_gcode_into_3mf(
  4743. file_path, item.plate_id or 1, start_gc or None, end_gc or None
  4744. )
  4745. if injected_path:
  4746. file_path = injected_path
  4747. end_gcode_injected = bool(end_gc)
  4748. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  4749. else:
  4750. logger.warning(
  4751. "Queue item %s: G-code injection returned no result, using original", item.id
  4752. )
  4753. except Exception as e:
  4754. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  4755. # #2547: the finish-photo path can't learn from telemetry that this print
  4756. # ends with user End G-code — which means the plate may be gone by the
  4757. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  4758. # the print once the printer confirms it running.
  4759. if end_gcode_injected:
  4760. print_dispatch_context.mark_pending(printer.id)
  4761. # Upload to root directory (not /cache/) - the start_print command references
  4762. # files by name only (ftp://{filename}), so they must be in the root
  4763. remote_filename = derive_remote_filename(filename)
  4764. remote_path = f"/{remote_filename}"
  4765. # Get FTP retry settings
  4766. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  4767. logger.info(
  4768. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  4769. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  4770. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  4771. )
  4772. # Release the pooled DB connection before the FTP delete/upload (#2572).
  4773. # Every read this method needs (printer, archive/library, preheat) is
  4774. # done, and the library-file branch already committed its archive
  4775. # creation. Without this the transaction opened by the first SELECT above
  4776. # stays "idle in transaction" for the entire upload — multiple seconds
  4777. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  4778. # a farm dispatching many jobs at once then exhausts the pool. This was
  4779. # correlated to an exact idle-in-transaction session on a 93-printer farm
  4780. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  4781. # readable; the status writes below (upload-failure path and the
  4782. # pending->printing CAS) transparently open a fresh transaction.
  4783. await db.commit()
  4784. # Delete existing file if present (avoids 553 error on overwrite)
  4785. try:
  4786. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  4787. delete_result = await delete_file_async(
  4788. printer.ip_address,
  4789. printer.access_code,
  4790. remote_path,
  4791. socket_timeout=ftp_timeout,
  4792. printer_model=printer.model,
  4793. )
  4794. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  4795. except Exception as e:
  4796. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  4797. # Dispatch toast — announce the upload start with the total byte
  4798. # count so the frontend can render an honest progress bar.
  4799. toast_uid = item.created_by_id
  4800. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  4801. try:
  4802. total_bytes = file_path.stat().st_size
  4803. except OSError:
  4804. total_bytes = 0
  4805. try:
  4806. await ws_manager.send_queue_item_uploading(
  4807. user_id=toast_uid,
  4808. queue_item_id=item.id,
  4809. printer_id=item.printer_id,
  4810. printer_name=printer.name,
  4811. file_name=toast_file_name,
  4812. total_bytes=total_bytes,
  4813. )
  4814. except Exception:
  4815. pass # toast is best-effort
  4816. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  4817. # A deadline expiry gets its own message: "check your SD card" is the
  4818. # wrong advice for a link that was simply too slow to finish (#2529).
  4819. upload_error: str | None = None
  4820. try:
  4821. if ftp_retry_enabled:
  4822. uploaded = await with_ftp_retry(
  4823. upload_file_async,
  4824. printer.ip_address,
  4825. printer.access_code,
  4826. file_path,
  4827. remote_path,
  4828. socket_timeout=ftp_timeout,
  4829. printer_model=printer.model,
  4830. progress_callback=progress_bridge,
  4831. max_retries=ftp_retry_count,
  4832. retry_delay=ftp_retry_delay,
  4833. operation_name=f"Upload print to {printer.name}",
  4834. )
  4835. else:
  4836. uploaded = await upload_file_async(
  4837. printer.ip_address,
  4838. printer.access_code,
  4839. file_path,
  4840. remote_path,
  4841. socket_timeout=ftp_timeout,
  4842. printer_model=printer.model,
  4843. progress_callback=progress_bridge,
  4844. )
  4845. except UploadCancelled as e:
  4846. uploaded = False
  4847. upload_error = (
  4848. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  4849. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  4850. )
  4851. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  4852. except Exception as e:
  4853. uploaded = False
  4854. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  4855. # Clean up injected temp file after upload attempt
  4856. if injected_path and injected_path.exists():
  4857. injected_path.unlink(missing_ok=True)
  4858. if not uploaded:
  4859. error_msg = upload_error or (
  4860. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  4861. "See server logs for detailed diagnostics."
  4862. )
  4863. item.status = "failed"
  4864. item.error_message = error_msg
  4865. item.completed_at = datetime.now(timezone.utc)
  4866. await db.commit()
  4867. logger.error(
  4868. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  4869. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  4870. )
  4871. # Send failure notification
  4872. await notification_service.on_queue_job_failed(
  4873. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  4874. printer_id=printer.id,
  4875. printer_name=printer.name,
  4876. reason="Failed to upload file to printer",
  4877. db=db,
  4878. )
  4879. try:
  4880. await ws_manager.send_queue_item_failed(
  4881. user_id=toast_uid,
  4882. queue_item_id=item.id,
  4883. printer_id=item.printer_id,
  4884. reason="upload_failed",
  4885. )
  4886. except Exception:
  4887. pass
  4888. await self._power_off_if_needed(db, item)
  4889. return
  4890. # Parse AMS mapping if stored
  4891. ams_mapping = None
  4892. if item.ams_mapping:
  4893. try:
  4894. ams_mapping = json.loads(item.ams_mapping)
  4895. except json.JSONDecodeError:
  4896. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  4897. # Register as expected print so we don't create a duplicate archive
  4898. # Only applicable for archive-based prints
  4899. if archive:
  4900. from backend.app.main import register_expected_print
  4901. register_expected_print(
  4902. item.printer_id,
  4903. remote_filename,
  4904. archive.id,
  4905. ams_mapping=ams_mapping,
  4906. created_by_id=item.created_by_id,
  4907. cost_center_id=item.cost_center_id,
  4908. plate_id=item.plate_id,
  4909. )
  4910. # Registration happens before the print command by necessity (the
  4911. # printer can report the print before the send returns), so record
  4912. # what to undo if we never get as far as sending. `_dispatch_one`
  4913. # rolls back anything still pending here on every exit — exception,
  4914. # early return, or cancel winning the CAS below.
  4915. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  4916. # Propagate the queue item's owner into printer_manager so the
  4917. # print-complete callback can credit the user in the PrintLogEntry
  4918. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  4919. # items) or when the user clicks the manual-start button.
  4920. await self._propagate_owner_to_printer_manager(db, item)
  4921. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  4922. # This prevents phantom reprints if the backend crashes/restarts after the
  4923. # print command is sent but before the status update is committed.
  4924. # If we crash after this commit but before start_print(), the item will be
  4925. # in "printing" status without actually printing - but that's safer than
  4926. # accidentally reprinting the same file hours later.
  4927. #
  4928. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  4929. # initial pending read at the top of check_queue and this point) flips
  4930. # the row to "cancelled" in a separate session. Without the WHERE
  4931. # status='pending' clause, the unconditional update here would silently
  4932. # overwrite that cancellation and we'd ship the MQTT start_print below
  4933. # — printer obeys, user sees "I pressed cancel and the print started".
  4934. # rowcount==0 means the user won the race; bail out, best-effort delete
  4935. # the file we just uploaded, do NOT send start_print.
  4936. now_utc = datetime.now(timezone.utc)
  4937. billing_run_id = str(uuid.uuid4())
  4938. cas = await db.execute(
  4939. update(PrintQueueItem)
  4940. .where(PrintQueueItem.id == item.id)
  4941. .where(PrintQueueItem.status == "pending")
  4942. .values(status="printing", started_at=now_utc, billing_run_id=billing_run_id)
  4943. )
  4944. await db.commit()
  4945. if cas.rowcount == 0:
  4946. logger.info(
  4947. "Queue item %s no longer pending at print-command time "
  4948. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  4949. item.id,
  4950. )
  4951. try:
  4952. await delete_file_async(
  4953. printer.ip_address,
  4954. printer.access_code,
  4955. remote_path,
  4956. socket_timeout=ftp_timeout,
  4957. printer_model=printer.model,
  4958. )
  4959. except Exception as cleanup_err:
  4960. logger.debug(
  4961. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  4962. item.id,
  4963. cleanup_err,
  4964. )
  4965. try:
  4966. await ws_manager.send_queue_item_failed(
  4967. user_id=toast_uid,
  4968. queue_item_id=item.id,
  4969. printer_id=item.printer_id,
  4970. reason="cancelled_mid_dispatch",
  4971. )
  4972. except Exception:
  4973. pass
  4974. return
  4975. # Sync the in-memory item so subsequent code that reads item.status /
  4976. # item.started_at sees the values we just persisted.
  4977. item.status = "printing"
  4978. item.started_at = now_utc
  4979. item.billing_run_id = billing_run_id
  4980. if archive is not None:
  4981. archive.billing_run_id = billing_run_id
  4982. # Legacy transaction deletion used an archive-wide skip flag.
  4983. # A newly dispatched run has its own UUID/tombstone, so it must be
  4984. # billable independently of any older deleted run on this archive.
  4985. archive.wallet_charge_skipped = False
  4986. # Persist before MQTT send so completion and restart recovery can
  4987. # always recover the internal billing identity.
  4988. await db.commit()
  4989. for cleanup_path in cleanup_disk_paths:
  4990. try:
  4991. if cleanup_path.exists():
  4992. cleanup_path.unlink()
  4993. except OSError as cleanup_err:
  4994. logger.warning(
  4995. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  4996. json.dumps(
  4997. {
  4998. "queue_item_id": item.id,
  4999. "path": str(cleanup_path),
  5000. "error": str(cleanup_err),
  5001. },
  5002. sort_keys=True,
  5003. ),
  5004. )
  5005. # Clear the awaiting-plate-clear flag now that we're starting a new print
  5006. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  5007. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  5008. # Capture state before dispatch so the watchdog can detect whether the
  5009. # printer actually transitioned (#967). Also capture subtask_id so the
  5010. # watchdog can recognise "command landed but state hasn't flipped yet"
  5011. # on slow H2D transitions (#1078).
  5012. pre_status = printer_manager.get_status(item.printer_id)
  5013. pre_state = getattr(pre_status, "state", None) if pre_status else None
  5014. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  5015. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  5016. # #1721: respect the user's explicit timelapse choice. The #1397
  5017. # force-on at dispatch was removed because it caused per-layer nozzle
  5018. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  5019. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  5020. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  5021. # FINISH-state fallback — no need to force a video.
  5022. effective_timelapse = bool(item.timelapse)
  5023. # Nozzle-rack fallback (#2800). A job that never passed through the
  5024. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  5025. # dispatches with no nozzle field at all and chooses for itself — which
  5026. # is how a print levelled on one hotend and then printed on another,
  5027. # millimetres above the plate. Derive the per-slot extruder assignment
  5028. # from the file being dispatched.
  5029. #
  5030. # Done here rather than at queue time because this is the first point
  5031. # that knows both the actual printer and the actual file: an item can
  5032. # be created without a printer (model-based assignment), reassigned
  5033. # afterwards, or have its file swapped for a G-code-injected copy just
  5034. # above. Every queue-creation path — the print dialog, a bulk library
  5035. # add, the webhook, a pipeline run — is covered by the one call.
  5036. # Skipped when the item already carries a Bambu Studio capture: that
  5037. # one wins downstream anyway, so reading the 3MF again would be work
  5038. # thrown away on every dispatch.
  5039. nozzle_slot_extruders = None
  5040. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  5041. slot_extruders = extract_slot_extruders_from_3mf(file_path)
  5042. if slot_extruders:
  5043. nozzle_slot_extruders = json.dumps(slot_extruders)
  5044. # Start the print with AMS mapping, plate_id and print options.
  5045. # nozzle_mapping rides through verbatim — JSON string captured from
  5046. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  5047. # parses + injects it only for dual-nozzle models so a null on every
  5048. # other model is a transparent pass-through. The rack fallback is
  5049. # resolved down there too, where the live rack position is known.
  5050. started = printer_manager.start_print(
  5051. item.printer_id,
  5052. remote_filename,
  5053. plate_id=item.plate_id or 1,
  5054. ams_mapping=ams_mapping,
  5055. bed_levelling=item.bed_levelling,
  5056. flow_cali=item.flow_cali,
  5057. vibration_cali=item.vibration_cali,
  5058. layer_inspect=item.layer_inspect,
  5059. timelapse=effective_timelapse,
  5060. use_ams=item.use_ams,
  5061. nozzle_offset_cali=item.nozzle_offset_cali,
  5062. nozzle_mapping=item.nozzle_mapping,
  5063. nozzle_slot_extruders=nozzle_slot_extruders,
  5064. )
  5065. if started:
  5066. # The command is away, so the expectation is now legitimate and must
  5067. # survive. Anything still in this dict when _dispatch_one exits gets
  5068. # rolled back.
  5069. self._unconfirmed_expected_print.pop(item.id, None)
  5070. self._unconfirmed_budget_reservations.discard(item.id)
  5071. # Handoff to the print's own gcode: keep whatever preheat set (bed
  5072. # target, chamber target, airduct heating) — the gcode owns
  5073. # heater/flap control from here. Clearing the pin prevents
  5074. # `_dispatch_one`'s finally from unwinding a live print.
  5075. self._preheat_pin.pop(item.printer_id, None)
  5076. self._preheat_pin_bed.pop(item.printer_id, None)
  5077. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  5078. # No dispatch-toast event here: the legacy bg-dispatch path kept
  5079. # status='processing' from upload start until the printer acked
  5080. # (or timed out). The frontend derives "Awaiting printer…" purely
  5081. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  5082. # event would push the status chip out of 'PROCESSING' prematurely
  5083. # — which is exactly what the screenshot at #1625-followup
  5084. # complained about.
  5085. # Register the local 3MF in the cover-cache so /cover skips FTP
  5086. # (#1166 follow-up). file_path was resolved earlier from either the
  5087. # archive or the library file row.
  5088. if file_path is not None:
  5089. cache_3mf_download(item.printer_id, remote_filename, file_path)
  5090. # Hold the printer against further dispatches until the watchdog
  5091. # confirms the printer transitioned (or until the hard timeout).
  5092. # Prevents multi-plate batches from triple-dispatching onto the
  5093. # same H2D Pro while it digests the first project_file (#1157).
  5094. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  5095. # Watchdog: if the printer never transitions out of pre_state AND
  5096. # never advances subtask_id, the MQTT publish was accepted locally but
  5097. # didn't reach the printer (half-broken session — same shape as
  5098. # #887/#936). Revert the queue item so the next dispatch can pick it
  5099. # up instead of leaving it stuck in "printing" (#967). subtask_id
  5100. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  5101. # that would otherwise cause the item to re-dispatch as a reprint
  5102. # of the just-finished job (#1078).
  5103. if pre_state:
  5104. spawn_background_task(
  5105. self._watchdog_print_start(
  5106. item.id,
  5107. item.printer_id,
  5108. pre_state,
  5109. pre_subtask_id,
  5110. pre_gcode_file,
  5111. created_by_id=toast_uid,
  5112. ),
  5113. name=f"watchdog-print-start-{item.id}",
  5114. )
  5115. # Get estimated time for notification.
  5116. #
  5117. # This used to fall back to `library_file.print_time_seconds`, a column
  5118. # LibraryFile does not have — the print time it knows about lives in
  5119. # `file_metadata`. So a library print whose archive carried no parseable
  5120. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  5121. # AttributeError right here, *after* the printer had already been sent
  5122. # the job: the started-notification never fired, and the exception
  5123. # unwound the whole queue pass, so every other printer still waiting to
  5124. # be dispatched on that tick silently missed its turn.
  5125. #
  5126. # The queue item caches the print time at creation ("Cached from
  5127. # archive/library"), which is the value this was reaching for.
  5128. estimated_time = None
  5129. if archive and archive.print_time_seconds:
  5130. estimated_time = archive.print_time_seconds
  5131. elif item.print_time_seconds:
  5132. estimated_time = item.print_time_seconds
  5133. # Send job started notification
  5134. await notification_service.on_queue_job_started(
  5135. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  5136. printer_id=printer.id,
  5137. printer_name=printer.name,
  5138. db=db,
  5139. estimated_time=estimated_time,
  5140. )
  5141. # MQTT relay - publish queue job started
  5142. try:
  5143. from backend.app.services.mqtt_relay import mqtt_relay
  5144. await mqtt_relay.on_queue_job_started(
  5145. job_id=item.id,
  5146. filename=filename,
  5147. printer_id=printer.id,
  5148. printer_name=printer.name,
  5149. printer_serial=printer.serial_number,
  5150. )
  5151. except Exception:
  5152. pass # Don't fail if MQTT fails
  5153. else:
  5154. # Clean up uploaded file from SD card to prevent phantom prints
  5155. try:
  5156. await delete_file_async(
  5157. printer.ip_address,
  5158. printer.access_code,
  5159. remote_path,
  5160. printer_model=printer.model,
  5161. )
  5162. except Exception:
  5163. pass # Best-effort — don't fail the error handler
  5164. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  5165. # state can flip from idle to active in the window between the
  5166. # pre-dispatch check above and this publish (the FTP upload takes
  5167. # seconds); start_print() then refuses to send project_file to the
  5168. # now-busy printer and returns False. Failing the item here would be
  5169. # wrong — the printer is fine, it is simply busy — so revert to
  5170. # pending and let a later tick dispatch it once the printer is idle,
  5171. # exactly like the pre-dispatch guard. Only a start_print() False on
  5172. # an idle/unknown printer is a genuine command failure.
  5173. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  5174. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  5175. logger.info(
  5176. "Queue item %s: printer %s became busy (state=%s) before the start "
  5177. "command was sent — deferring, reverting item to pending (#2598)",
  5178. item.id,
  5179. item.printer_id,
  5180. post_dispatch_state,
  5181. )
  5182. item.status = "pending"
  5183. item.started_at = None
  5184. await db.commit()
  5185. return
  5186. # Print command failed - revert status
  5187. item.status = "failed"
  5188. item.error_message = "Failed to send print command to printer"
  5189. item.completed_at = datetime.now(timezone.utc)
  5190. await db.commit()
  5191. logger.error(
  5192. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  5193. f"printer_manager.start_print() returned False. "
  5194. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  5195. f"Check printer status and backend logs for details."
  5196. )
  5197. # Send failure notification
  5198. await notification_service.on_queue_job_failed(
  5199. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  5200. printer_id=printer.id,
  5201. printer_name=printer.name,
  5202. reason="Failed to send print command to printer - check printer connection and status",
  5203. db=db,
  5204. )
  5205. try:
  5206. await ws_manager.send_queue_item_failed(
  5207. user_id=toast_uid,
  5208. queue_item_id=item.id,
  5209. printer_id=item.printer_id,
  5210. reason="start_command_failed",
  5211. )
  5212. except Exception:
  5213. pass
  5214. await self._power_off_if_needed(db, item)
  5215. @staticmethod
  5216. async def _watchdog_print_start(
  5217. queue_item_id: int,
  5218. printer_id: int,
  5219. pre_state: str,
  5220. pre_subtask_id: str | None = None,
  5221. pre_gcode_file: str | None = None,
  5222. timeout: float = 90.0,
  5223. phase_b_timeout: float = 180.0,
  5224. poll_interval: float = 3.0,
  5225. created_by_id: int | None = None,
  5226. ) -> None:
  5227. """Revert a queue item if the printer never acknowledges the start command.
  5228. Bambuddy optimistically marks the queue item as "printing" right after the
  5229. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  5230. Phase A (up to ``timeout``): wait for either an active-state transition
  5231. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  5232. primary signal; subtask_id advance handles the H2D case where state can
  5233. sit at FINISH for ~50 s after the printer accepted ``project_file``
  5234. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  5235. was lost on a half-broken session (#887/#936) — revert and force
  5236. reconnect (the #967 recovery path).
  5237. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  5238. alone): keep watching for the active-state transition. subtask_id alone
  5239. proves the file landed but not that the printer started — and a printer
  5240. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  5241. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  5242. used to leave the queue item stuck in 'printing' forever because the
  5243. old watchdog returned success as soon as subtask_id advanced. If Phase
  5244. B times out, revert the queue item so the user can retry without
  5245. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  5246. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  5247. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  5248. transitions that also don't emit an early subtask_id tick.
  5249. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  5250. refuses to verify our commands will never start this job or any other,
  5251. so waiting out the full 270 s and re-uploading the 3MF twice more only
  5252. burns an upload slot the rest of the farm is queued behind — that path
  5253. is for a printer that might still come good, which this one cannot
  5254. (#2732). It fails the item on the spot with the actual reason instead.
  5255. """
  5256. last_status = None
  5257. landed_on_subtask = False
  5258. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  5259. # every push carrying an `hms` key, so the fault can come and go between
  5260. # 3-second polls. Seeing it once inside the dispatch window is enough.
  5261. command_rejected = False
  5262. # Latched for the same reason as command_rejected: drying can finish, or
  5263. # be stopped by the user, part-way through the dispatch window. Seeing it
  5264. # once is what matters — it is the state the printer was in when it
  5265. # declined to start (#2758).
  5266. drying_ams_ids: list[int] = []
  5267. deadline = time.monotonic() + timeout
  5268. while time.monotonic() < deadline:
  5269. await asyncio.sleep(poll_interval)
  5270. status = printer_manager.get_status(printer_id)
  5271. if not status:
  5272. # Printer disconnected — don't mess with the DB. Drop the
  5273. # in-memory dispatch hold too so a fresh dispatch can retry
  5274. # once the printer comes back; the hard timeout would
  5275. # otherwise hold the printer unnecessarily.
  5276. scheduler._release_dispatch_hold(printer_id)
  5277. return
  5278. last_status = status
  5279. if status.state in _ACTIVE_PRINT_STATES:
  5280. # Printer is actively processing the job — release the
  5281. # post-dispatch hold so the next pending item for this printer
  5282. # can be evaluated normally. We do NOT accept arbitrary state
  5283. # transitions: a printer going FINISH -> IDLE (user dismissed
  5284. # the post-print prompt without accepting our project_file)
  5285. # would otherwise look like "command landed" and leave the
  5286. # queue item stuck in 'printing' forever (#1370).
  5287. scheduler._release_dispatch_hold(printer_id)
  5288. try:
  5289. await ws_manager.send_queue_item_acked(
  5290. user_id=created_by_id,
  5291. queue_item_id=queue_item_id,
  5292. printer_id=printer_id,
  5293. )
  5294. except Exception:
  5295. pass
  5296. return
  5297. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  5298. # Checked only after the active-state exit above: a stale HMS left
  5299. # over from an earlier job must never abort a print that is visibly
  5300. # running. An actually-refused command leaves the printer idle, so
  5301. # this ordering costs the detection nothing.
  5302. if _mqtt_commands_rejected(status):
  5303. command_rejected = True
  5304. break
  5305. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  5306. # Phase A exit — printer accepted the file (subtask_id flipped
  5307. # to our submission id). Don't return yet: the printer may
  5308. # have accepted the command but never actually start (e.g.
  5309. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  5310. # B watches for the active-state transition.
  5311. landed_on_subtask = True
  5312. break
  5313. if landed_on_subtask and not command_rejected:
  5314. phase_b_deadline = time.monotonic() + phase_b_timeout
  5315. while time.monotonic() < phase_b_deadline:
  5316. await asyncio.sleep(poll_interval)
  5317. status = printer_manager.get_status(printer_id)
  5318. if not status:
  5319. scheduler._release_dispatch_hold(printer_id)
  5320. return
  5321. last_status = status
  5322. if status.state in _ACTIVE_PRINT_STATES:
  5323. scheduler._release_dispatch_hold(printer_id)
  5324. try:
  5325. await ws_manager.send_queue_item_acked(
  5326. user_id=created_by_id,
  5327. queue_item_id=queue_item_id,
  5328. printer_id=printer_id,
  5329. )
  5330. except Exception:
  5331. pass
  5332. return
  5333. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  5334. # Same ordering rule as Phase A: a running print wins over a
  5335. # lingering HMS.
  5336. if _mqtt_commands_rejected(status):
  5337. command_rejected = True
  5338. break
  5339. # No active-state transition. Revert the item so the scheduler can retry.
  5340. # Drop the in-memory hold so the retry isn't blocked by it.
  5341. scheduler._release_dispatch_hold(printer_id)
  5342. # Logged on every failed dispatch window, not just the last one, so a
  5343. # support bundle shows the correlation from the first attempt rather than
  5344. # only after the retry budget is spent (#2758).
  5345. if drying_ams_ids:
  5346. logger.info(
  5347. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  5348. queue_item_id,
  5349. printer_id,
  5350. ", ".join(str(i) for i in drying_ams_ids),
  5351. )
  5352. # Four outcomes from the revert attempt, each routed differently:
  5353. # "reverted": row flipped from printing -> pending, run recovery
  5354. # "gave_up": same, but the retry budget is spent — row failed
  5355. # rather than pending, so it stops going round again
  5356. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  5357. # on_print_complete or user). Skip recovery entirely
  5358. # — the print clearly landed somewhere even if the
  5359. # watchdog didn't see the active-state transition.
  5360. # "revert_failed": SQLite contention exhausted retries. Still run
  5361. # recovery so the MQTT session gets a fresh client_id
  5362. # on the half-broken-session path.
  5363. #
  5364. # The retry budget (#2555): reverting to 'pending' hands the item straight
  5365. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  5366. # the watchdog again. For a printer that is genuinely wedged that loop never
  5367. # ends — the reporter had one printer "since this morning still not launch"
  5368. # — and each lap also consumes an upload slot that the other printers in the
  5369. # farm are waiting on. Retrying is right; retrying forever is not.
  5370. async def _do_revert(db):
  5371. item = await db.get(PrintQueueItem, queue_item_id)
  5372. if not item or item.status != "printing":
  5373. return "already_moved_on"
  5374. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  5375. item.started_at = None
  5376. # Charge the attempt to the candidate that was actually dispatched, so
  5377. # a cross-model item (#671) reaches for its other file next lap instead
  5378. # of retrying the printer that just failed to start. Matched by file
  5379. # because that is what the resolver copied onto the row.
  5380. if item.library_file_id is not None:
  5381. await db.execute(
  5382. update(PrintQueueVariant)
  5383. .where(PrintQueueVariant.queue_item_id == item.id)
  5384. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  5385. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  5386. )
  5387. if command_rejected:
  5388. # No retry budget for this one: the printer refused to verify the
  5389. # command, and re-uploading the same 3MF to the same printer will
  5390. # be refused the same way. Fail now with the fix rather than after
  5391. # three laps of a message about SD cards (#2732).
  5392. item.status = "failed"
  5393. item.error_message = (
  5394. "The printer rejected the print command: MQTT command verification failed "
  5395. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  5396. "then start the job again."
  5397. )
  5398. item.completed_at = datetime.now(timezone.utc)
  5399. await db.commit()
  5400. return "command_rejected"
  5401. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  5402. item.status = "failed"
  5403. if drying_ams_ids:
  5404. # #2758: the generic message below sent the reporter looking
  5405. # at the SD card while the actual obstacle — AMS units in a
  5406. # drying cycle — was on screen the whole time. Name what we
  5407. # observed and let the user judge it; Bambuddy does not stop
  5408. # the cycle itself, because on this hardware drying can run
  5409. # alongside a print and stopping it may not be the fix.
  5410. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  5411. item.error_message = (
  5412. f"The printer accepted the file but never started printing, after "
  5413. f"{item.dispatch_attempts} attempts. {units} "
  5414. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  5415. f"some printers refuse to begin a print while an AMS is in a drying "
  5416. f"cycle, and an AMS drying without its external power supply can also "
  5417. f"leave too little power for the start-of-print calibration. Stop the "
  5418. f"drying, or connect the AMS power supply, and start the job again."
  5419. )
  5420. else:
  5421. item.error_message = (
  5422. f"The printer accepted the file but never started printing, after "
  5423. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  5424. f"prompt or error, confirm its SD card is readable, and start the job again."
  5425. )
  5426. item.completed_at = datetime.now(timezone.utc)
  5427. await release_budget_reservation(
  5428. db,
  5429. source_type="print_queue",
  5430. source_id=item.id,
  5431. status="released",
  5432. )
  5433. await db.commit()
  5434. return "gave_up"
  5435. item.status = "pending"
  5436. await db.commit()
  5437. return "reverted"
  5438. try:
  5439. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  5440. except Exception as e:
  5441. logger.warning(
  5442. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  5443. "scheduler may keep treating this item as in-flight",
  5444. queue_item_id,
  5445. printer_id,
  5446. e,
  5447. )
  5448. revert_outcome = "revert_failed"
  5449. if revert_outcome == "already_moved_on":
  5450. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  5451. # other path) already moved the item past 'printing', don't run the
  5452. # MQTT session-recovery logic below — a forced reconnect on a healthy
  5453. # session breaks ongoing prints on the same printer.
  5454. return
  5455. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  5456. if revert_outcome == "command_rejected":
  5457. logger.error(
  5458. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  5459. "failed) — the print command was rejected, not lost. Failing the item "
  5460. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  5461. queue_item_id,
  5462. printer_id,
  5463. HMS_MQTT_VERIFY_FAILED,
  5464. )
  5465. await scheduler._notify_dispatch_gave_up(
  5466. queue_item_id,
  5467. printer_id,
  5468. created_by_id,
  5469. reason="Printer rejected the print command (MQTT command verification failed)",
  5470. )
  5471. # Same reasoning as the landed_on_subtask path below: the file is on
  5472. # the printer and a forced reconnect would only add 0500_4003 to a
  5473. # problem that has nothing to do with the MQTT session (#1150).
  5474. return
  5475. if revert_outcome == "gave_up":
  5476. logger.error(
  5477. "Queue item %s: printer %d never started the print after %d dispatch "
  5478. "attempts (last one waited %.0fs) — marking the item failed instead of "
  5479. "re-uploading it again (#2555)",
  5480. queue_item_id,
  5481. printer_id,
  5482. DISPATCH_MAX_ATTEMPTS,
  5483. total_timeout,
  5484. )
  5485. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  5486. elif revert_outcome == "reverted":
  5487. if landed_on_subtask:
  5488. logger.warning(
  5489. "Queue item %s: printer %d accepted project_file (subtask_id "
  5490. "advanced) but never transitioned to an active state within "
  5491. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  5492. "for retry (#1678)",
  5493. queue_item_id,
  5494. printer_id,
  5495. total_timeout,
  5496. )
  5497. else:
  5498. logger.warning(
  5499. "Queue item %s: printer %d did not respond to print command within "
  5500. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  5501. "for retry (#967)",
  5502. queue_item_id,
  5503. printer_id,
  5504. timeout,
  5505. pre_state,
  5506. pre_subtask_id,
  5507. )
  5508. # Phase B was entered iff subtask_id advanced, which means the
  5509. # project_file landed on the printer. A forced reconnect at this point
  5510. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  5511. # skip the recovery entirely.
  5512. if landed_on_subtask:
  5513. return
  5514. # Phase A timeout path: if the printer's gcode_file changed since
  5515. # pre-dispatch, the project_file command landed and the printer is
  5516. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  5517. # If gcode_file is unchanged, the publish was silently swallowed
  5518. # (#887/#936) and force_reconnect recovery is what we want.
  5519. client = printer_manager.get_client(printer_id)
  5520. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  5521. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  5522. if publish_landed:
  5523. logger.warning(
  5524. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  5525. "received the command and is parsing slowly. Skipping forced "
  5526. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  5527. queue_item_id,
  5528. current_gcode_file,
  5529. pre_gcode_file,
  5530. )
  5531. elif client and hasattr(client, "force_reconnect_stale_session"):
  5532. client.force_reconnect_stale_session(
  5533. f"queue print command unacknowledged after {timeout:.0f}s "
  5534. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  5535. )
  5536. # Global scheduler instance
  5537. scheduler = PrintScheduler()