print_scheduler.py 351 KB

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