print_scheduler.py 317 KB

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