print_scheduler.py 354 KB

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