print_scheduler.py 385 KB

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