main.py 576 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import re
  8. import secrets
  9. import time
  10. from contextlib import asynccontextmanager
  11. from datetime import datetime, timedelta, timezone
  12. from logging.handlers import RotatingFileHandler
  13. from pathlib import Path, PurePosixPath
  14. from urllib.parse import urlparse
  15. from fastapi import FastAPI
  16. from fastapi.encoders import jsonable_encoder
  17. from fastapi.exceptions import RequestValidationError
  18. from fastapi.responses import FileResponse, JSONResponse
  19. from fastapi.staticfiles import StaticFiles
  20. from sqlalchemy import delete, inspect as sa_inspect, or_, select, text, update
  21. from sqlalchemy.exc import IntegrityError
  22. from sqlalchemy.orm.exc import StaleDataError
  23. from backend.app.api.routes import (
  24. ams_history,
  25. announcements,
  26. api_keys,
  27. archive_purge,
  28. archives,
  29. auth,
  30. bug_report,
  31. camera,
  32. camwall,
  33. cloud,
  34. connected_apps,
  35. discovery,
  36. external_links,
  37. filaments,
  38. finance,
  39. firmware,
  40. github_backup,
  41. groups,
  42. ha_sensors,
  43. inventory,
  44. kprofiles,
  45. labels,
  46. library,
  47. library_tags,
  48. library_trash,
  49. library_variants,
  50. local_backup,
  51. local_presets,
  52. location_ha_sensors,
  53. maintenance,
  54. makerworld,
  55. manyfold,
  56. metrics,
  57. mfa,
  58. notification_templates,
  59. notifications,
  60. obico,
  61. orca_cloud,
  62. overlay_branding,
  63. pending_uploads,
  64. pipeline_runs,
  65. print_log,
  66. print_queue,
  67. printer_locations,
  68. printer_sensor_history,
  69. printers,
  70. projects,
  71. scheduled_dryings,
  72. settings as settings_routes,
  73. slice_jobs,
  74. slicer_pipelines,
  75. slicer_presets,
  76. smart_plugs,
  77. sponsor_prompt,
  78. spoolbuddy,
  79. spoolman,
  80. spoolman_inventory,
  81. support,
  82. system,
  83. updates,
  84. user_notifications,
  85. users,
  86. virtual_printers,
  87. webhook,
  88. websocket,
  89. )
  90. from backend.app.api.routes.maintenance import (
  91. _get_printer_maintenance_internal,
  92. ensure_default_types,
  93. maintenance_alert_values,
  94. )
  95. from backend.app.api.routes.support import init_debug_logging
  96. from backend.app.core.config import APP_VERSION, settings as app_settings
  97. from backend.app.core.database import async_session, engine, init_db
  98. from backend.app.core.static_assets import AssetStaticFiles
  99. from backend.app.core.tasks import spawn_background_task
  100. from backend.app.core.websocket import ws_manager
  101. from backend.app.services import kprofile_drift, print_dispatch_context, slot_unlink_grace
  102. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  103. from backend.app.services.archive_cost_estimate import (
  104. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  105. )
  106. from backend.app.services.archive_purge import archive_purge_service
  107. from backend.app.services.bambu_ftp import (
  108. RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  109. FileNotOnPrinterError,
  110. cache_3mf_download,
  111. clear_3mf_cache,
  112. download_file_async,
  113. download_file_try_paths_async,
  114. ftps_handshake_blocked,
  115. get_cached_3mf,
  116. get_ftp_retry_settings,
  117. normalize_3mf_name,
  118. with_ftp_retry,
  119. )
  120. from backend.app.services.bambu_mqtt import PrinterState
  121. from backend.app.services.camera_light import camera_light
  122. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  123. from backend.app.services.github_backup import github_backup_service
  124. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  125. from backend.app.services.library_trash import library_trash_service
  126. from backend.app.services.local_backup import local_backup_service
  127. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  128. from backend.app.services.mqtt_relay import mqtt_relay
  129. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  130. from backend.app.services.notification_service import notification_service
  131. from backend.app.services.notify_live_activities import notify_live_activities
  132. from backend.app.services.notify_widgets import notify_widgets
  133. from backend.app.services.obico_detection import obico_detection_service
  134. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  135. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  136. from backend.app.services.print_scheduler import scheduler as print_scheduler
  137. from backend.app.services.print_storage import (
  138. REASON_FTP_TRANSFER_FAILED,
  139. REASON_FTPS_COOLOFF,
  140. external_storage_present,
  141. ftp_probe_paths,
  142. print_file_reachable_over_ftp,
  143. )
  144. from backend.app.services.printer_manager import (
  145. init_printer_connections,
  146. parse_plate_id,
  147. printer_manager,
  148. printer_state_to_dict,
  149. resolve_plate_id,
  150. )
  151. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  152. from backend.app.services.slot_nozzle import (
  153. nozzle_diameter_for_extruder,
  154. nozzle_flow_for_extruder,
  155. )
  156. from backend.app.services.smart_plug_manager import smart_plug_manager
  157. from backend.app.services.spool_assignment_notifications import (
  158. notify_missing_spool_assignments_on_print_start,
  159. )
  160. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  161. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  162. from backend.app.services.spoolman_tracking import (
  163. cleanup_tracking as _cleanup_spoolman_tracking,
  164. release_archived_slot_rows as _release_archived_spoolman_slots,
  165. report_usage as _report_spoolman_usage,
  166. store_print_data as _store_spoolman_print_data,
  167. )
  168. from backend.app.services.telegram_reactions import telegram_reaction_poller
  169. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  170. from backend.app.utils.ams_humidity import ams_humidity_percent
  171. from backend.app.utils.filament_types import printer_filament_type
  172. from backend.app.utils.fts_routing import extruder_for_inlet
  173. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  174. from backend.app.utils.print_jobs import is_internal_printer_job
  175. # =============================================================================
  176. # Dependency Check - runs before other imports to give helpful error messages
  177. # =============================================================================
  178. def _start_error_server(missing_packages: list):
  179. """Start a minimal HTTP server to display dependency errors in browser."""
  180. import os
  181. import signal
  182. from http.server import BaseHTTPRequestHandler, HTTPServer
  183. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  184. html = f"""<!DOCTYPE html>
  185. <html>
  186. <head>
  187. <title>Bambuddy - Setup Required</title>
  188. <style>
  189. body {{
  190. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  191. background: #0f172a; color: #e2e8f0;
  192. display: flex; justify-content: center; align-items: center;
  193. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  194. }}
  195. .container {{
  196. background: #1e293b; border-radius: 12px; padding: 40px;
  197. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  198. }}
  199. h1 {{ color: #f87171; margin-bottom: 10px; }}
  200. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  201. .packages {{
  202. background: #0f172a; border-radius: 8px; padding: 20px;
  203. margin: 20px 0; text-align: left;
  204. }}
  205. .packages ul {{ margin: 0; padding-left: 20px; }}
  206. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  207. .command {{
  208. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  209. margin: 15px 0; font-family: monospace; color: #4ade80;
  210. text-align: left; overflow-x: auto;
  211. }}
  212. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  213. </style>
  214. </head>
  215. <body>
  216. <div class="container">
  217. <h1>Setup Required</h1>
  218. <h2>Missing Python packages</h2>
  219. <div class="packages"><ul>{packages_html}</ul></div>
  220. <p>To fix, run this command on your server:</p>
  221. <div class="command">pip install -r requirements.lock</div>
  222. <p>Or if using a virtual environment:</p>
  223. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  224. <p class="note">After installing, restart Bambuddy:<br>
  225. <code>sudo systemctl restart bambuddy</code></p>
  226. </div>
  227. </body>
  228. </html>"""
  229. class ErrorHandler(BaseHTTPRequestHandler):
  230. def do_GET(self):
  231. self.send_response(503)
  232. self.send_header("Content-type", "text/html")
  233. self.end_headers()
  234. self.wfile.write(html.encode())
  235. def log_message(self, format, *args):
  236. print(f"[Error Server] {args[0]}")
  237. port = int(os.environ.get("PORT", 8000))
  238. print(f"\nStarting error server on http://0.0.0.0:{port}")
  239. print("Visit this URL in your browser to see the error details.\n")
  240. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  241. def shutdown(signum, frame):
  242. print("\nShutting down error server...")
  243. raise SystemExit(0)
  244. signal.signal(signal.SIGTERM, shutdown)
  245. signal.signal(signal.SIGINT, shutdown)
  246. server.serve_forever()
  247. def check_dependencies():
  248. """Check that all required packages are installed."""
  249. missing = []
  250. # Map of import name -> package name (for pip install)
  251. required = {
  252. "jwt": "PyJWT",
  253. "fastapi": "fastapi",
  254. "uvicorn": "uvicorn",
  255. "sqlalchemy": "sqlalchemy",
  256. "aiosqlite": "aiosqlite",
  257. "pydantic": "pydantic",
  258. "paho.mqtt": "paho-mqtt",
  259. }
  260. for module, package in required.items():
  261. try:
  262. __import__(module)
  263. except ImportError:
  264. missing.append(package)
  265. if missing:
  266. print("\n" + "=" * 60)
  267. print("ERROR: Missing required Python packages!")
  268. print("=" * 60)
  269. print(f"\nMissing packages: {', '.join(missing)}")
  270. print("\nTo fix, run:")
  271. print(" pip install -r requirements.lock")
  272. print("\nOr if using a virtual environment:")
  273. print(" ./venv/bin/pip install -r requirements.lock")
  274. print("=" * 60 + "\n")
  275. _start_error_server(missing)
  276. check_dependencies()
  277. # =============================================================================
  278. # Import settings first for logging configuration
  279. # Configure logging based on settings
  280. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  281. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  282. log_level = getattr(logging, log_level_str, logging.INFO)
  283. # Trace ID column ([-] when no request scope is active — startup, MQTT
  284. # callbacks, scheduled tasks not chained from a request — so the column
  285. # stays visually aligned and missing values are obvious in grep). See
  286. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  287. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  288. # Create root logger
  289. root_logger = logging.getLogger()
  290. root_logger.setLevel(log_level)
  291. # Trace-ID injection: this filter populates record.trace_id from the
  292. # per-request ContextVar so the format string above can reference it.
  293. # Attached to each HANDLER (not the root logger) because Python's
  294. # logging semantics only invoke a logger's filters on records that
  295. # *originated* at that logger — records propagated up from child
  296. # loggers (every named logger in the app) never trigger root's filter.
  297. # Putting it on the handlers means every record any handler emits gets
  298. # trace_id injected just before the formatter runs, regardless of which
  299. # logger created the record. Without this, the formatter raises
  300. # KeyError on every child-logger record and the record is silently
  301. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  302. # partially" bug we hit. See backend/app/core/trace.py for the
  303. # ContextVar the filter reads.
  304. from backend.app.core.logging_filters import RefusedHeaderRedactFilter
  305. from backend.app.core.response_redaction import RefusedHeaderResponseMask
  306. from backend.app.core.trace import TraceIDFilter
  307. _trace_id_filter = TraceIDFilter()
  308. # Console handler - always enabled
  309. console_handler = logging.StreamHandler()
  310. console_handler.setLevel(log_level)
  311. console_handler.setFormatter(logging.Formatter(log_format))
  312. console_handler.addFilter(_trace_id_filter)
  313. # A refused header's value (often a token) masked before the line is written.
  314. _refused_header_filter = RefusedHeaderRedactFilter()
  315. console_handler.addFilter(_refused_header_filter)
  316. root_logger.addHandler(console_handler)
  317. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  318. """Send uvicorn's own loggers to bambuddy.log as well.
  319. Neither reaches the root handler: uvicorn.access has propagate=False, and
  320. uvicorn.error propagates only to "uvicorn", which has propagate=False.
  321. uvicorn.access is the record of which endpoint changed server state;
  322. uvicorn.error is where an unhandled route error is logged with its
  323. traceback ("Exception in ASGI application").
  324. """
  325. for name in ("uvicorn.access", "uvicorn.error"):
  326. logging.getLogger(name).addHandler(handler)
  327. # File handler - only in production or if explicitly enabled
  328. if app_settings.log_to_file:
  329. log_file = app_settings.log_dir / "bambuddy.log"
  330. file_handler = RotatingFileHandler(
  331. log_file,
  332. maxBytes=app_settings.log_max_bytes,
  333. backupCount=app_settings.log_backup_count,
  334. encoding="utf-8",
  335. )
  336. file_handler.setLevel(log_level)
  337. file_handler.setFormatter(logging.Formatter(log_format))
  338. file_handler.addFilter(_trace_id_filter)
  339. file_handler.addFilter(_refused_header_filter)
  340. root_logger.addHandler(file_handler)
  341. logging.info("Logging to file: %s", log_file)
  342. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  343. # access logger with propagate=False by default, so without this attach
  344. # there is no on-disk record of which endpoint triggered a server-state
  345. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  346. # for exactly this reason. Filtered to write methods only
  347. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  348. # frontend don't churn the rotation window faster than it's useful.
  349. from backend.app.core.logging_filters import (
  350. CancelledPoolNoiseFilter,
  351. WriteRequestsOnlyFilter,
  352. )
  353. _attach_file_handler_to_uvicorn(file_handler)
  354. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  355. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  356. # Uvicorn's access logger has propagate=False (its own default), so the
  357. # root-attached TraceIDFilter never sees these records. Attach a
  358. # second instance directly so HTTP access lines carry the same trace
  359. # ID column as the application logs they correlate with.
  360. uvicorn_access_logger.addFilter(TraceIDFilter())
  361. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  362. # BaseHTTPMiddleware cancelling the inner task scope on client
  363. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  364. # underlying transaction leak; this filter only suppresses the residual
  365. # log records that pre-existing pools still emit during their cleanup.
  366. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  367. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  368. # handler (console included), whether or not file logging is on.
  369. from backend.app.core.logging_filters import ( # noqa: E402
  370. QueryTokenRedactFilter,
  371. ShutdownCancelledRequestFilter,
  372. )
  373. # First, so the traceback of a stream cancelled at shutdown is dropped before
  374. # the filters below render it.
  375. logging.getLogger("uvicorn.error").addFilter(ShutdownCancelledRequestFilter())
  376. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  377. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  378. logging.getLogger(_uvicorn_logger).addFilter(_refused_header_filter)
  379. # These stay at WARNING even in debug mode: at INFO/DEBUG httpx/httpcore log
  380. # full request URLs, and some carry credentials (bot tokens, webhook URLs, API
  381. # keys in the query). Same as the runtime log-level toggle in support.py.
  382. logging.getLogger("httpcore").setLevel(logging.WARNING)
  383. logging.getLogger("httpx").setLevel(logging.WARNING)
  384. # aiosqlite logs every statement with its parameters at DEBUG.
  385. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  386. # Reduce noise from third-party libraries in production
  387. if not app_settings.debug:
  388. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  389. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  390. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  391. # Track active prints: {(printer_id, filename): archive_id}
  392. _active_prints: dict[tuple[int, str], int] = {}
  393. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  394. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  395. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  396. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  397. # instead of running its own grab-now chain when present, so the finish photo
  398. # captures the better-framed pre-bed-drop moment without us having to force
  399. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  400. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  401. #
  402. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  403. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  404. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  405. # bank and the others are not — so the consumer can't tell them apart and
  406. # must not rotate again.
  407. _stage22_finish_frames: dict[int, bytes] = {}
  408. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  409. # `finally` block (whether it captured a frame or not). The consumer in
  410. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  411. # so the FINISH-state fallback path — where moment and completion are dispatched
  412. # back-to-back — doesn't race past the producer with an empty pop, and the
  413. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  414. # grab (Bambu printers allow only one RTSP client at a time).
  415. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  416. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  417. # layer-change and on print-progress advances (#2547) while the model is still
  418. # printing, then consumed by the FINISH-state finish-photo path when the
  419. # dispatcher recorded that it injected End G-code into this print. Bambu
  420. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  421. # plate-swap) has run, so a live grab there would capture the swapped/empty
  422. # plate.
  423. #
  424. # The load-bearing property: both drivers are print telemetry that stops before
  425. # the End G-code executes — no further layer_num increases, and mc_percent
  426. # freezes — so the last banked frame is always the finished print before the
  427. # swap. Anything added as a third driver must hold that same property.
  428. _inprint_frame_bank: dict[int, bytes] = {}
  429. # Monotonic timestamp of the last banked frame per printer — throttles banking
  430. # so tall prints don't add a camera grab on every layer.
  431. _inprint_frame_bank_ts: dict[int, float] = {}
  432. # Minimum seconds between banked frames, except the final object layer which
  433. # always refreshes for the best framing.
  434. _INPRINT_BANK_MIN_INTERVAL = 25.0
  435. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  436. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  437. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  438. # the first connected status update for that connection; transitions back
  439. # to False whenever we observe `state.connected = False` so the next
  440. # reconnect re-arms reconciliation. Keyed by printer_id.
  441. _printer_reconciled_since_connect: dict[int, bool] = {}
  442. # Same edge, same keying, for priming the printer's calibration table exactly
  443. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  444. # is otherwise filled only when someone opens the Profiles page or Configure
  445. # Slot, when a GitHub backup runs, or when the printer happens to answer
  446. # somebody else's query on the report topic. Until then the AMS slot card has
  447. # no K value to show on the printers whose trays carry none of their own
  448. # (#2854 — H2-series report cali_idx and nothing more).
  449. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  450. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  451. # {(printer_id, filename): archive_id}
  452. _expected_prints: dict[tuple[int, str], int] = {}
  453. # Archives of the running prints Bambuddy dispatched itself: adopted from an
  454. # expected print, or found with Bambuddy's dispatch marker. _active_prints holds
  455. # every print on_print_start archived, those started from Bambu Studio, Handy or
  456. # the printer's screen included, so it is no proof of ownership on its own.
  457. _owned_print_archive_ids: set[int] = set()
  458. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  459. # Used by usage tracker to map 3MF slots to physical AMS trays
  460. _print_ams_mappings: dict[int, list[int]] = {}
  461. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  462. _print_cost_center_ids: dict[int, int] = {}
  463. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  464. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  465. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  466. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  467. # for the queue path. Cleared on print completion or TTL eviction.
  468. _print_plate_ids: dict[int, int] = {}
  469. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  470. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  471. _last_progress_milestone: dict[int, int] = {}
  472. # Track whether first layer complete notification has been sent for current print
  473. _first_layer_notified: dict[int, bool] = {}
  474. # Track whether we already sent a kill-switch stop for the current unauthorized print
  475. _unauthorized_print_kill_sent: set[int] = set()
  476. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  477. # lookup briefly so an unknown active print does not query the database on
  478. # every status frame. A short TTL keeps settings changes responsive.
  479. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  480. _kill_switch_setting_cache: tuple[bool, float] | None = None
  481. # Provider notification started when the kill switch stops a print. The later
  482. # MQTT print-complete callback awaits this task and only sends its regular
  483. # provider notification when the immediate attempt failed.
  484. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  485. # HMS faults already notified, with when each was last seen:
  486. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  487. # fault that flickers beside a held notice was forgotten on every gap and
  488. # notified on every return (#3226). The window is long because the measured
  489. # gaps reach 64 s.
  490. _notified_hms_errors: dict[int, dict[str, float]] = {}
  491. _HMS_CLEAR_GRACE_SECONDS = 600.0
  492. # The print state each printer was last seen in, and the faults recorded before
  493. # it last changed, which are forgotten as soon as they are gone (see
  494. # _take_new_hms_faults).
  495. _hms_print_state: dict[int, str] = {}
  496. _hms_forget_when_gone: dict[int, set[str]] = {}
  497. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  498. # Used for snapshot-diff detection at print completion
  499. _timelapse_baselines: dict[int, set[str]] = {}
  500. # Track printers waiting for bed to cool after print completion.
  501. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  502. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  503. _bed_cool_waiters: dict[int, dict] = {}
  504. # Track printers where the user explicitly stopped the print from the queue UI.
  505. # When on_print_complete fires with status "failed" for these printers we treat it
  506. # as "cancelled" (stopped by user) so the correct notification email is sent.
  507. _user_stopped_printers: set[int] = set()
  508. # Printers whose running print the kill switch stopped. Their completion is a
  509. # cancel with the reason "killSwitch", not the "failed" the printer reports.
  510. _kill_switch_stopped: set[int] = set()
  511. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  512. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  513. # holds the previous observation so we only fire on the True → False edge (a
  514. # False → False repeat doesn't notify; an initial False at startup doesn't
  515. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  516. # holds the per-printer pending asyncio task that fires the notification
  517. # after a debounce window — cancelled if the printer reconnects before the
  518. # window elapses, so transient MQTT blips don't flood the user.
  519. _printer_last_connected: dict[int, bool] = {}
  520. # Printers whose relay offline event went out, so the reconnect publishes the
  521. # matching online event and a blip shorter than the debounce publishes neither.
  522. _printer_offline_published: set[int] = set()
  523. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  524. # Debounce: a printer must stay offline this long before we notify. Sized
  525. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  526. # so a single stale-trigger cooldown isn't enough to fire — only a real
  527. # offline that survives one reconnect attempt notifies.
  528. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  529. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  530. # when status="failed" to label the print's failure_reason in archives.
  531. #
  532. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  533. # which is wrong on two counts:
  534. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  535. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  536. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  537. # the public wiki) as part of its user-cancel sequence. Matching on the module
  538. # alone caused user-cancellations to be archived as "Layer shift" failures.
  539. # We now match by full short code only — anything not in this map leaves
  540. # failure_reason=None rather than guessing.
  541. # Values are the canonical camelCase failure-reason keys, NOT display labels
  542. # (issue #2974). The vocabulary is enforced on writes by
  543. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  544. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  545. # Statistics breakdown. Storing a label here instead put a second spelling of
  546. # the same cause into one column: the Failure Analysis widget groups on the raw
  547. # value, so a print the backend classified and an identical one a user
  548. # classified counted as two different reasons, and the label form could never
  549. # be translated because there was no key for ``t()`` to resolve.
  550. _HMS_FAILURE_REASONS: dict[str, str] = {
  551. # Layer shift / step loss
  552. "0300_4057": "layerShift",
  553. "0300_4068": "layerShift",
  554. "0300_800C": "layerShift",
  555. # Filament runout (printer-side & per-AMS-slot)
  556. "0300_8004": "filamentRunout",
  557. "0700_8011": "filamentRunout",
  558. "0701_8011": "filamentRunout",
  559. "0702_8011": "filamentRunout",
  560. "0703_8011": "filamentRunout",
  561. "0704_8011": "filamentRunout",
  562. "0705_8011": "filamentRunout",
  563. "0706_8011": "filamentRunout",
  564. "0707_8011": "filamentRunout",
  565. "07FF_8011": "filamentRunout",
  566. # Clogged nozzle / extruder
  567. "0300_4006": "cloggedNozzle",
  568. "0300_8016": "cloggedNozzle",
  569. "0300_801C": "cloggedNozzle",
  570. "0700_8003": "cloggedNozzle",
  571. "0700_8007": "cloggedNozzle",
  572. "0700_8013": "cloggedNozzle",
  573. "0701_8003": "cloggedNozzle",
  574. "0701_8007": "cloggedNozzle",
  575. "0701_8013": "cloggedNozzle",
  576. "0702_8003": "cloggedNozzle",
  577. # AI print monitoring — spaghetti / the model coming off the plate.
  578. # `spaghettiDetached` is a key the archive editor already offers for this
  579. # failure mode, not a new one, so a derived reason opens the dropdown on
  580. # that option rather than blank — and survives the next save, which clears
  581. # any value the editor does not recognise.
  582. #
  583. # A module-0x0C row is safe here despite the warning above: that warning is
  584. # about matching on the module alone, and 0C00_8042 is a full short code
  585. # with a documented meaning ("The AI print monitor has detected a spaghetti
  586. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  587. # cannot collide.
  588. #
  589. # 0300_8003's own text ends "before continuing your print", but on an X2D
  590. # it arrives with the print already paused, offering only
  591. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  592. #
  593. # Two neighbours are left out on purpose, so this does not get re-derived:
  594. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  595. # reads as a warning about a print that is still running, not a halt.
  596. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  597. # the waste chute. That is not the print failing.
  598. #
  599. # That line is drawn from the text, not from `severity`, because severity
  600. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  601. # module/error word with no level in it, and bambu_mqtt.py gives every
  602. # print_error entry a flat severity=3. Matching on the short code alone is
  603. # the right shape for derive_failure_reason, not an omission.
  604. "0300_8003": "spaghettiDetached",
  605. "0C00_8042": "spaghettiDetached",
  606. }
  607. def _hms_short_code(attr: int, code: int | str) -> str:
  608. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  609. if isinstance(code, str):
  610. code_int = int(code.replace("0x", ""), 16) if code else 0
  611. else:
  612. code_int = int(code or 0)
  613. attr_int = int(attr or 0)
  614. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  615. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  616. """Derive the failure_reason key for an archived print.
  617. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  618. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  619. no HMS code matches (don't guess — null is honest). The keys are the
  620. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  621. translated at render time.
  622. """
  623. if status in ("aborted", "cancelled"):
  624. return "userCancelled"
  625. if status != "failed":
  626. return None
  627. for err in hms_errors or []:
  628. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  629. if short_code in _HMS_FAILURE_REASONS:
  630. return _HMS_FAILURE_REASONS[short_code]
  631. return None
  632. # Track created_by_id for expected prints so the user email can be sent even when
  633. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  634. # {(printer_id, filename): created_by_id}
  635. _expected_print_creators: dict[tuple[int, str], int] = {}
  636. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  637. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  638. # updates for the same printer in quick succession (~30 ms apart, observed in
  639. # the wild on H2D + dual AMS).
  640. #
  641. # Without this serialisation, two concurrent on_ams_change callbacks each read
  642. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  643. # the second commit hits
  644. # IntegrityError: duplicate key value violates unique constraint
  645. # "spool_assignment_printer_id_ams_id_tray_id_key"
  646. # SQLite's WAL serial-write semantics had been silently swallowing the race
  647. # until optional Postgres support landed (asyncpg allows true concurrent
  648. # transactions and surfaces the constraint violation).
  649. #
  650. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  651. # assign) are inside the lock. The Spoolman sync block further down stays
  652. # concurrent because it's network-bound and idempotent.
  653. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  654. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  655. """Return the per-printer assignment lock, creating it on first use."""
  656. lock = _ams_assignment_locks.get(printer_id)
  657. if lock is None:
  658. lock = asyncio.Lock()
  659. _ams_assignment_locks[printer_id] = lock
  660. return lock
  661. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  662. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  663. # tag tuple changes for the slot. Cleared when the slot is reported empty
  664. # so remove + reinsert reliably re-prompts the UI.
  665. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  666. async def _broadcast_unknown_tag(
  667. *,
  668. printer_id: int,
  669. ams_id: int,
  670. tray_id: int,
  671. tag_uid: str,
  672. tray_uuid: str,
  673. tray_type: str | None = None,
  674. tray_color: str | None = None,
  675. tray_sub_brands: str | None = None,
  676. tray_count: int | None = None,
  677. ) -> None:
  678. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  679. _logger = logging.getLogger(__name__)
  680. slot_key = (ams_id, tray_id)
  681. tag_key = (tag_uid or "", tray_uuid or "")
  682. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  683. if per_printer.get(slot_key) == tag_key:
  684. _logger.debug(
  685. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  686. printer_id,
  687. ams_id,
  688. tray_id,
  689. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  690. )
  691. return
  692. _logger.info(
  693. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  694. printer_id,
  695. ams_id,
  696. tray_id,
  697. tray_type,
  698. tray_color,
  699. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  700. )
  701. # Broadcast first; only commit the dedup if the WS write succeeds.
  702. # If broadcast raises, the next MQTT push retries instead of being
  703. # permanently silenced by a poisoned dedup entry.
  704. await ws_manager.broadcast(
  705. {
  706. "type": "unknown_tag",
  707. "printer_id": printer_id,
  708. "ams_id": ams_id,
  709. "tray_id": tray_id,
  710. "tag_uid": tag_uid,
  711. "tray_uuid": tray_uuid,
  712. "tray_type": tray_type,
  713. "tray_color": tray_color,
  714. "tray_sub_brands": tray_sub_brands,
  715. "tray_count": tray_count,
  716. }
  717. )
  718. per_printer[slot_key] = tag_key
  719. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  720. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  721. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  722. if per_printer is None:
  723. return
  724. per_printer.pop((ams_id, tray_id), None)
  725. # TTL for expected-print entries: evict registrations older than this to prevent
  726. # unbounded growth when a print is registered but never starts (e.g. printer
  727. # disconnect, app restart, print started from the printer panel).
  728. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  729. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  730. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  731. # Cleanup loop interval
  732. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  733. _expected_prints_cleanup_task: asyncio.Task | None = None
  734. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  735. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  736. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  737. possible_keys: list[tuple[int, str]] = []
  738. filename = (state.gcode_file or state.current_print or "").strip()
  739. subtask_name = (state.subtask_name or "").strip()
  740. if subtask_name:
  741. possible_keys.append((printer_id, subtask_name))
  742. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  743. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  744. if filename:
  745. base_name = filename.rsplit("/", 1)[-1]
  746. if base_name.endswith(".gcode.3mf"):
  747. root_name = base_name[: -len(".gcode.3mf")]
  748. possible_keys.append((printer_id, root_name))
  749. possible_keys.append((printer_id, base_name))
  750. possible_keys.append((printer_id, f"{root_name}.gcode"))
  751. possible_keys.append((printer_id, f"{root_name}.3mf"))
  752. elif base_name.endswith(".3mf"):
  753. root_name = base_name[: -len(".3mf")]
  754. possible_keys.append((printer_id, root_name))
  755. possible_keys.append((printer_id, base_name))
  756. elif base_name.endswith(".gcode"):
  757. root_name = base_name[: -len(".gcode")]
  758. possible_keys.append((printer_id, root_name))
  759. possible_keys.append((printer_id, f"{root_name}.3mf"))
  760. possible_keys.append((printer_id, base_name))
  761. else:
  762. possible_keys.append((printer_id, base_name))
  763. possible_keys.append((printer_id, f"{base_name}.3mf"))
  764. return possible_keys
  765. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  766. """The id of who started the print, unless that user has been deleted since.
  767. Deleting a user forgets them in printer_manager, but a print that ended a
  768. moment before still holds them.
  769. """
  770. if not print_user or print_user.get("user_id") is None:
  771. return None
  772. from backend.app.models.user import User
  773. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  774. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  775. """Check the cheap, process-local print ownership signals."""
  776. if printer_manager.get_current_print_user(printer_id):
  777. return True
  778. return any(
  779. key in _expected_prints or _active_prints.get(key) in _owned_print_archive_ids
  780. for key in _build_status_print_keys(printer_id, state)
  781. )
  782. def _bind_active_print(
  783. printer_id: int,
  784. archive_id: int,
  785. archive_filename: str | None,
  786. filename: str | None = None,
  787. subtask_name: str | None = None,
  788. ) -> None:
  789. """Track a running print under every name its completion may report.
  790. One set for every path that binds a print (new archive, expected print,
  791. restart resume, fallback): the archive's file name, the name the printer
  792. reported, and the subtask with and without ``.3mf``. Paths that registered
  793. fewer names lost the bound archive at completion, and with it the plate
  794. restore's height (#3240), whenever MQTT reported a name they had left out.
  795. """
  796. for name in {archive_filename, filename, f"{subtask_name}.3mf" if subtask_name else None, subtask_name}:
  797. if name:
  798. _active_prints[(printer_id, name)] = archive_id
  799. def _mark_owned_if_dispatched(archive) -> None:
  800. """Remember a running print's archive as Bambuddy's when it carries a
  801. dispatch marker Bambuddy writes itself: ``billing_run_id`` (minted per
  802. dispatch in the scheduler) or ``created_by_id`` (from the queue item)."""
  803. if archive.billing_run_id is not None or archive.created_by_id is not None:
  804. _owned_print_archive_ids.add(archive.id)
  805. async def _is_printer_kill_switch_enabled_cached() -> bool:
  806. """Return the kill-switch setting without querying on every MQTT frame."""
  807. global _kill_switch_setting_cache
  808. now = time.monotonic()
  809. if _kill_switch_setting_cache is not None:
  810. enabled, expires_at = _kill_switch_setting_cache
  811. if now < expires_at:
  812. return enabled
  813. async with async_session() as db:
  814. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  815. enabled = await is_printer_kill_switch_enabled(db)
  816. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  817. return enabled
  818. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  819. """Resolve whether the current print was started by Bambuddy.
  820. ``None`` means identity is not yet safe to decide. The kill switch must
  821. defer in that case: stopping a print is irreversible, and the first status
  822. frames after a restart may arrive before all subtask fields are populated.
  823. """
  824. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  825. return True
  826. # The printer's built-in calibration runs (Bambuddy's Calibrate, the
  827. # printer's screen) play gcode from its read-only system partition, where no
  828. # user file can be. Only that path counts: a calibration *name* proves
  829. # nothing, since Bambu Studio's pressure-advance print reports a user-style
  830. # path, and any print can be given that name.
  831. if str(getattr(state, "gcode_file", "") or "").startswith("/usr/"):
  832. return True
  833. # A1, A1 Mini, P1 and A2L report the same calibration as a bare file name,
  834. # which nothing distinguishes from a user's file given that name, so it is
  835. # not exempt: with the kill switch on, calibrate on those printers with the
  836. # switch off.
  837. possible_keys = _build_status_print_keys(printer_id, state)
  838. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  839. # is on disk. subtask_id is minted per print and pins the answer to the job
  840. # actually running, rather than to an unrelated one that reuses a filename.
  841. raw_subtask_id = getattr(state, "subtask_id", None)
  842. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  843. if subtask_id == "":
  844. # Not reported yet: the first frames after a restart can lack it.
  845. return None
  846. from backend.app.models.archive import PrintArchive
  847. if subtask_id == "0":
  848. # A print started outside the cloud from Bambu Studio, Handy or the
  849. # printer's screen reports "0", so there is no id to match: one of
  850. # Bambuddy's printing archives on this printer under the name the
  851. # printer reports, compared as the printer echoes names (spaces become
  852. # underscores). Nothing reported to compare yet: wait.
  853. reported = {_normalise_subtask_name(name) for _pid, name in possible_keys} - {""}
  854. if not reported:
  855. return None
  856. dispatched = await db.execute(
  857. select(PrintArchive)
  858. .where(
  859. PrintArchive.printer_id == printer_id,
  860. PrintArchive.status == "printing",
  861. or_(PrintArchive.billing_run_id.is_not(None), PrintArchive.created_by_id.is_not(None)),
  862. # An archive with a real id of its own is a print that reported
  863. # one: a "0" print is not it, even under the same name (one whose
  864. # completion was missed would otherwise cover it).
  865. or_(PrintArchive.subtask_id.is_(None), PrintArchive.subtask_id.in_(("", "0"))),
  866. )
  867. .order_by(PrintArchive.created_at.desc())
  868. )
  869. archive = next((a for a in dispatched.scalars() if _archive_name_forms(a) & reported), None)
  870. else:
  871. result = await db.execute(
  872. select(PrintArchive)
  873. .where(
  874. PrintArchive.printer_id == printer_id,
  875. PrintArchive.status == "printing",
  876. PrintArchive.subtask_id == subtask_id,
  877. )
  878. .order_by(PrintArchive.created_at.desc())
  879. .limit(1)
  880. )
  881. archive = result.scalar_one_or_none()
  882. # An archive row on its own proves nothing: `on_print_start` archives every
  883. # print it observes, including ones started from Bambu Studio or Handy, and
  884. # stamps them with the same status and subtask_id. Authorizing on its mere
  885. # existence would disable the kill switch the moment the 3MF finishes
  886. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  887. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  888. # (carried over from the queue item that started it).
  889. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  890. # Rehydrate the fast in-memory path for subsequent status frames. Include
  891. # both the archive filename and every normalized key reported by MQTT.
  892. _owned_print_archive_ids.add(archive.id)
  893. _active_prints[(printer_id, archive.filename)] = archive.id
  894. for key in possible_keys:
  895. _active_prints[key] = archive.id
  896. return True
  897. # No dispatch marker. Before calling this someone else's print, check whether
  898. # Bambuddy has a job of its own running on this printer: a library-file
  899. # dispatch has no archive at send time, and an archive created seconds later
  900. # by `on_print_start` carries neither marker. The queue row, which the
  901. # scheduler commits to status="printing" before the MQTT send, is the one
  902. # durable record every Bambuddy print has. It cannot be tied to this
  903. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  904. # print is irreversible, and refusing to act costs nothing but a log line.
  905. from backend.app.models.print_queue import PrintQueueItem
  906. dispatched_here = await db.scalar(
  907. select(PrintQueueItem.id)
  908. .where(
  909. PrintQueueItem.printer_id == printer_id,
  910. PrintQueueItem.status == "printing",
  911. )
  912. .limit(1)
  913. )
  914. if dispatched_here is not None:
  915. return None
  916. return False
  917. async def _send_kill_switch_provider_notification(
  918. printer_id: int,
  919. printer_name: str,
  920. data: dict,
  921. ) -> bool:
  922. """Send the immediate print-stopped provider notification.
  923. Returning a success flag lets the normal MQTT completion path retry when
  924. this early notification could not be delivered.
  925. """
  926. logger = logging.getLogger(__name__)
  927. try:
  928. async with async_session() as db:
  929. await notification_service.on_print_complete(
  930. printer_id,
  931. printer_name,
  932. "stopped",
  933. data,
  934. db,
  935. )
  936. return True
  937. except Exception as e:
  938. logger.warning(
  939. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  940. printer_id,
  941. e,
  942. )
  943. return False
  944. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  945. """Wait for an immediate kill-switch notification, if one was scheduled."""
  946. if task is None:
  947. return False
  948. try:
  949. return await task
  950. except Exception as e:
  951. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  952. return False
  953. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  954. """Capture the smart plug lifetime counter on the archive at print start.
  955. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  956. tracking survives a backend restart mid-print. The print-end handler reads
  957. this value back from the DB and computes the delta against the current
  958. plug counter.
  959. """
  960. _logger = logging.getLogger(__name__)
  961. try:
  962. candidates = await energy_plug_candidates(db, printer_id)
  963. if not candidates:
  964. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  965. return False
  966. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  967. if selected is None:
  968. # Naming the plugs matters here: with several linked to one printer
  969. # this is the difference between "the meter is offline" and "you
  970. # linked only accessories" (#2859).
  971. _logger.warning(
  972. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  973. printer_id,
  974. archive.id,
  975. ", ".join(plug.name for plug in candidates),
  976. )
  977. return False
  978. plug, energy = selected
  979. archive.energy_start_kwh = float(energy["total"])
  980. # With the plug's snapshots, what lets the cost follow the price over
  981. # the print rather than take the price at its end (#1251). A price that
  982. # can't be had must not cost the print its energy reading.
  983. archive.energy_start_at = utcnow_naive()
  984. archive.energy_start_plug_id = plug.id
  985. try:
  986. from backend.app.services.energy_price import current_price
  987. archive.energy_start_price = await current_price(db)
  988. except Exception as e:
  989. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  990. archive.energy_start_price = None
  991. await db.commit()
  992. _logger.info(
  993. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  994. f" ({context})" if context else "",
  995. archive.id,
  996. plug.name,
  997. energy["total"],
  998. )
  999. return True
  1000. except Exception as e:
  1001. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  1002. return False
  1003. def forget_print_creator(user_id: int) -> None:
  1004. """The print-start emails of a deleted user's jobs go to nobody, not to
  1005. whoever is given the id next (SQLite reuses it)."""
  1006. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  1007. del _expected_print_creators[key]
  1008. async def forget_printer(printer_id: int) -> None:
  1009. """Drop what is kept for a deleted printer's id, here and in the services.
  1010. SQLite used to give the id to the next printer created, which inherited it
  1011. all: the running print's owner (its prints passed the kill switch and were
  1012. billed to that user), the plate-clear gate, pending and suppressed
  1013. notifications, the camera feed, the plate references. Ids are no longer
  1014. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  1015. stay. Called after the delete is committed, and again by work that was in
  1016. flight and wrote state back.
  1017. Every printer-keyed map of this module is listed here or, with the reason,
  1018. in tests/unit/test_forget_printer.py.
  1019. """
  1020. from backend.app.api.routes import camera
  1021. from backend.app.services import (
  1022. bambu_ftp,
  1023. kprofile_drift,
  1024. layer_timelapse,
  1025. plate_detection,
  1026. print_dispatch_context,
  1027. usage_tracker,
  1028. )
  1029. from backend.app.services.notify_live_activities import notify_live_activities
  1030. from backend.app.services.obico_detection import obico_detection_service
  1031. from backend.app.services.printer_file_cache import printer_file_cache
  1032. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  1033. archive_ids = set()
  1034. for tracked in (_active_prints, _expected_prints):
  1035. for key in [key for key in tracked if key[0] == printer_id]:
  1036. archive_ids.add(tracked.pop(key))
  1037. for archive_id in archive_ids:
  1038. _owned_print_archive_ids.discard(archive_id)
  1039. _print_ams_mappings.pop(archive_id, None)
  1040. _print_cost_center_ids.pop(archive_id, None)
  1041. _print_plate_ids.pop(archive_id, None)
  1042. for tracked in (_expected_print_creators, _expected_print_registered_at):
  1043. for key in [key for key in tracked if key[0] == printer_id]:
  1044. del tracked[key]
  1045. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  1046. _ams_index_only_logged.discard(key)
  1047. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  1048. del _ams_alarm_cooldown[key]
  1049. # Pending work that would act on the id: an offline notice, a 3MF retry.
  1050. # A kill-switch notice is about a stop that happened and is left to finish.
  1051. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  1052. task = tasks.pop(printer_id, None)
  1053. if task is not None:
  1054. task.cancel()
  1055. for keyed in (
  1056. _stage22_finish_frames,
  1057. _stage22_finish_in_flight,
  1058. _inprint_frame_bank,
  1059. _inprint_frame_bank_ts,
  1060. _printer_reconciled_since_connect,
  1061. _printer_kprofiles_primed_since_connect,
  1062. _last_progress_milestone,
  1063. _first_layer_notified,
  1064. _kill_switch_notification_tasks,
  1065. _notified_hms_errors,
  1066. _hms_print_state,
  1067. _hms_forget_when_gone,
  1068. _timelapse_baselines,
  1069. _bed_cool_waiters,
  1070. _printer_last_connected,
  1071. _unknown_tag_last_broadcast,
  1072. _last_status_broadcast,
  1073. _connection_watchdog_last_attempt,
  1074. ):
  1075. keyed.pop(printer_id, None)
  1076. for marked in (
  1077. _unauthorized_print_kill_sent,
  1078. _user_stopped_printers,
  1079. _kill_switch_stopped,
  1080. _printer_offline_published,
  1081. _nozzle_count_updated,
  1082. ):
  1083. marked.discard(printer_id)
  1084. printer_manager.forget_printer(printer_id)
  1085. printer_file_cache.forget_printer(printer_id)
  1086. print_dispatch_context.clear(printer_id)
  1087. kprofile_drift.forget_printer(printer_id, deleted=True)
  1088. layer_timelapse.cancel_session(printer_id)
  1089. usage_tracker.forget_printer(printer_id)
  1090. obico_detection_service.forget_printer(printer_id)
  1091. bambu_ftp.clear_3mf_cache(printer_id)
  1092. await camera.forget_printer(printer_id)
  1093. printers.clear_cover_cache(printer_id)
  1094. print_scheduler.forget_printer(printer_id)
  1095. notify_live_activities.forget_printer(printer_id)
  1096. plate_detection.remove_printer_references(printer_id)
  1097. def register_expected_print(
  1098. printer_id: int,
  1099. filename: str,
  1100. archive_id: int,
  1101. ams_mapping: list[int] | None = None,
  1102. created_by_id: int | None = None,
  1103. cost_center_id: int | None = None,
  1104. plate_id: int | None = None,
  1105. ):
  1106. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1107. # Store with multiple filename variations to catch different naming patterns
  1108. _expected_prints[(printer_id, filename)] = archive_id
  1109. # Also store without .3mf extension if present
  1110. if filename.endswith(".3mf"):
  1111. base = filename[:-4]
  1112. _expected_prints[(printer_id, base)] = archive_id
  1113. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1114. # Store AMS mapping for usage tracking at print completion, and plate_id for
  1115. # a single-plate dispatch from a multi-plate 3MF — without it, the direct-Print
  1116. # path attributes the whole file's filament total to the spool instead of just
  1117. # the printed plate (#1697). They describe this dispatch: one that has none
  1118. # drops what an earlier dispatch of the archive left (sent, never started),
  1119. # unless a plate of the archive is printing now and still needs them.
  1120. archive_printing = archive_id in set(_active_prints.values())
  1121. if ams_mapping is not None:
  1122. _print_ams_mappings[archive_id] = ams_mapping
  1123. elif not archive_printing:
  1124. _print_ams_mappings.pop(archive_id, None)
  1125. if cost_center_id is not None:
  1126. _print_cost_center_ids[archive_id] = cost_center_id
  1127. elif not archive_printing:
  1128. _print_cost_center_ids.pop(archive_id, None)
  1129. if plate_id is not None:
  1130. _print_plate_ids[archive_id] = plate_id
  1131. elif not archive_printing:
  1132. _print_plate_ids.pop(archive_id, None)
  1133. # Store created_by_id so the user start email can be sent even when the archive
  1134. # itself has no created_by_id (e.g. library-file-based queue prints)
  1135. if created_by_id is not None:
  1136. _expected_print_creators[(printer_id, filename)] = created_by_id
  1137. if filename.endswith(".3mf"):
  1138. base = filename[:-4]
  1139. _expected_print_creators[(printer_id, base)] = created_by_id
  1140. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1141. # Record registration time for TTL-based eviction
  1142. _registered_at = time.monotonic()
  1143. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1144. if filename.endswith(".3mf"):
  1145. base = filename[:-4]
  1146. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1147. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1148. logging.getLogger(__name__).info(
  1149. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1150. )
  1151. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1152. """Undo :func:`register_expected_print` when the print never went out.
  1153. Registration has to happen *before* the MQTT print command, because the
  1154. printer can report the print before the line after the send executes. So
  1155. every path that registers and then fails to send — a cancel winning the
  1156. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1157. between — leaves an expectation for a print that will never arrive.
  1158. The TTL sweep evicts those after two hours, which is far longer than it
  1159. takes a user to react to a failed dispatch by pressing print again: that
  1160. reprint would be folded into the *old* archive and take the stale
  1161. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1162. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1163. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1164. are keyed by archive, not by file, so they may only be dropped once no
  1165. live key still points at that archive.
  1166. """
  1167. keys = [(printer_id, filename)]
  1168. if filename.endswith(".3mf"):
  1169. base = filename[:-4]
  1170. keys.append((printer_id, base))
  1171. keys.append((printer_id, f"{base}.gcode"))
  1172. removed = False
  1173. for key in keys:
  1174. if _expected_prints.pop(key, None) is not None:
  1175. removed = True
  1176. _expected_print_creators.pop(key, None)
  1177. _expected_print_registered_at.pop(key, None)
  1178. # Still needed by another expected print of the archive, or a plate of it
  1179. # that is printing, as in the sweep.
  1180. if archive_id not in set(_expected_prints.values()) | set(_active_prints.values()):
  1181. _print_ams_mappings.pop(archive_id, None)
  1182. _print_cost_center_ids.pop(archive_id, None)
  1183. _print_plate_ids.pop(archive_id, None)
  1184. if removed:
  1185. logging.getLogger(__name__).info(
  1186. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1187. printer_id,
  1188. filename,
  1189. archive_id,
  1190. )
  1191. def _compute_run_filament_grams(
  1192. status: str,
  1193. archive_filament_used_grams: float | None,
  1194. progress: float | int | None,
  1195. usage_results: list[dict] | None,
  1196. ) -> float | None:
  1197. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1198. Priority for every status:
  1199. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1200. weight delta — same source that drives "Total Consumed" on the
  1201. Inventory page, so Stats and Inventory totals stay aligned).
  1202. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1203. back to the canonical "this print used X" value).
  1204. 3. For partial statuses: ``estimate * progress%``.
  1205. 4. ``None`` if nothing is known.
  1206. """
  1207. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1208. if tracked_grams > 0:
  1209. return round(tracked_grams, 1)
  1210. if status == "completed":
  1211. return archive_filament_used_grams
  1212. if archive_filament_used_grams:
  1213. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1214. if scale > 0:
  1215. return round(archive_filament_used_grams * scale, 1)
  1216. return None
  1217. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  1218. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1219. stored_ams_mapping = data.get("ams_mapping")
  1220. if not stored_ams_mapping and archive_id:
  1221. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  1222. return stored_ams_mapping
  1223. def _get_start_plate_id(archive_id: int | None) -> int | None:
  1224. """Resolve plate_id for print start without consuming stored direct-Print state.
  1225. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1226. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1227. read it back at print-start without popping (the entry is popped on print
  1228. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1229. """
  1230. if archive_id is None:
  1231. return None
  1232. return _print_plate_ids.get(archive_id)
  1233. def _partial_progress_scale(progress: int | float | None) -> float:
  1234. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1235. Used by every site that multiplies a "would-have-used" slicer estimate
  1236. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1237. so the three sites in ``_background_notifications`` (and the per-plate
  1238. override helper) can't drift apart on the coercion shape.
  1239. """
  1240. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1241. def _scope_notification_archive_data_to_plate(
  1242. archive_data: dict,
  1243. archive_file_path: str | None,
  1244. plate_id: int | None,
  1245. print_status: str,
  1246. progress: int | float | None,
  1247. base_dir: Path,
  1248. ) -> dict:
  1249. """Override summed-across-plates totals in ``archive_data`` with the values
  1250. for ``plate_id`` so the completion notification reports what was actually
  1251. printed, not the whole project (#1785).
  1252. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1253. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1254. the archive card's "whole project" headline, wrong for the completion
  1255. notification of a single-plate print. The queue UI already re-reads the
  1256. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1257. notification payload (filament grams, time estimate, per-slot breakdown).
  1258. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1259. no per-plate values — in every fail case the original ``archive_data`` is
  1260. returned unchanged so the notification still sends.
  1261. """
  1262. if plate_id is None or not archive_file_path:
  1263. return archive_data
  1264. from backend.app.utils.threemf_tools import (
  1265. extract_filament_usage_from_3mf,
  1266. extract_print_time_from_3mf,
  1267. )
  1268. archive_path = base_dir / archive_file_path
  1269. if not archive_path.exists():
  1270. return archive_data
  1271. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1272. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1273. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1274. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1275. if plate_time:
  1276. archive_data["print_time_seconds"] = plate_time
  1277. # Gate both the grams headline AND the per-slot breakdown on the same
  1278. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1279. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1280. # to the project-level grams the archive columns already provide rather
  1281. # than ship a project-level headline next to an all-zero per-plate
  1282. # breakdown.
  1283. if plate_grams > 0:
  1284. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1285. archive_data["filament_slots"] = [
  1286. {
  1287. "slot_id": s.get("slot_id"),
  1288. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1289. "type": s.get("type", ""),
  1290. "color": s.get("color", ""),
  1291. }
  1292. for s in plate_slots
  1293. ]
  1294. return archive_data
  1295. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1296. """Best-effort filament metadata from the MQTT print-start snapshot.
  1297. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1298. file during print, see #1533) so the fallback PrintArchive still has
  1299. enough filament info to support the inventory views and AMS-expansion
  1300. planning the operator opens it for. Returns a dict with optional
  1301. ``filament_type`` and ``filament_color`` keys in the same
  1302. comma-separated format the 3MF extractor produces, so the rest of the
  1303. codebase treats the fallback archive identically to a normal one.
  1304. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1305. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1306. entries). When supplied, only the slots actually consumed by this
  1307. print contribute. Without it the function falls back to every loaded
  1308. AMS slot — less accurate but still useful.
  1309. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1310. that the unit tests pass directly, AND the on_print_start callback
  1311. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1312. bambu_mqtt service hands to main.py at runtime. The original
  1313. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1314. handled the inner shape and silently returned ``{}`` for every real
  1315. print start, leaving fallback archives' filament fields NULL — the
  1316. exact regression the fix was meant to close. Reported with a log
  1317. proving the AMS state was right there at
  1318. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1319. """
  1320. result: dict[str, str] = {}
  1321. # Look at the on_print_start wrapper first, then the inner shape.
  1322. raw_data = (data or {}).get("raw_data")
  1323. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1324. if not isinstance(ams_root, dict):
  1325. ams_root = (data or {}).get("ams") or {}
  1326. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1327. if not isinstance(ams_units, list) or not ams_units:
  1328. return result
  1329. from backend.app.services.print_scheduler import _global_tray_id
  1330. # Map global tray id → (type, color), addressed as the print's ams_mapping
  1331. # is: unit * 4 + tray, or the bare unit id for an AMS-HT (from 128).
  1332. loaded: dict[int, tuple[str, str]] = {}
  1333. for unit in ams_units:
  1334. if not isinstance(unit, dict):
  1335. continue
  1336. try:
  1337. unit_id = int(unit.get("id", 0))
  1338. except (TypeError, ValueError):
  1339. continue
  1340. for tray in unit.get("tray") or []:
  1341. if not isinstance(tray, dict):
  1342. continue
  1343. try:
  1344. tray_id = int(tray.get("id", 0))
  1345. except (TypeError, ValueError):
  1346. continue
  1347. ttype = (tray.get("tray_type") or "").strip()
  1348. # RRGGBBAA from the printer, stored as the 3MF path stores it:
  1349. # "#RRGGBB" (the Archives page's swatches and colour filter).
  1350. hex_color = (tray.get("tray_color") or "").strip().upper()[:6]
  1351. tcolor = f"#{hex_color}" if re.fullmatch(r"[0-9A-F]{6}", hex_color) else ""
  1352. if not ttype:
  1353. continue # Empty / unloaded slot.
  1354. loaded[_global_tray_id(unit_id, tray_id)] = (ttype, tcolor)
  1355. if not loaded:
  1356. return result
  1357. if ams_mapping:
  1358. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1359. filaments = [loaded[g] for g in used_ids if g in loaded]
  1360. if not filaments:
  1361. return result # Mapping points entirely at slots we have no data for.
  1362. else:
  1363. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1364. types_joined = ",".join(f[0] for f in filaments)
  1365. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1366. # Column limits per backend/app/models/archive.py: filament_type=50,
  1367. # filament_color=200.
  1368. if types_joined:
  1369. result["filament_type"] = types_joined[:50]
  1370. if colors_joined:
  1371. result["filament_color"] = colors_joined[:200]
  1372. return result
  1373. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1374. """Start a layer-timelapse session for *archive_id* when the printer has
  1375. an external camera configured. Returns True if a session was started.
  1376. Three call sites in on_print_start (expected-archive promotion, fallback
  1377. archive creation, fresh-archive creation) used to inline this same
  1378. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1379. on the first pass). Centralising the conditional + call here makes the
  1380. contract testable in isolation and keeps the three sites locked in step.
  1381. """
  1382. if not (printer.external_camera_enabled and printer.external_camera_url):
  1383. return False
  1384. from backend.app.services.layer_timelapse import start_session
  1385. start_session(
  1386. printer_id,
  1387. archive_id,
  1388. printer.external_camera_url,
  1389. printer.external_camera_type or "mjpeg",
  1390. snapshot_url=printer.external_camera_snapshot_url,
  1391. rotation=getattr(printer, "camera_rotation", 0),
  1392. )
  1393. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1394. return True
  1395. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1396. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1397. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1398. — since #2926 — the description the parser already resolved, which is preferred
  1399. when present so the queue's failure reason reads the same as the status
  1400. response. The short code still produces the bracketed label, and still
  1401. resolves the sentence for a caller whose entries predate the field. An entry
  1402. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1403. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1404. label when no description is on file. Returns None for an empty list so
  1405. callers can leave error_message unset.
  1406. """
  1407. if not hms_errors:
  1408. return None
  1409. from backend.app.services.hms_errors import get_error_description
  1410. parts: list[str] = []
  1411. for err in hms_errors:
  1412. try:
  1413. # `_hms_short_code` rather than a local derivation: this one used to
  1414. # format the error without masking it to 16 bits, so an `hms[]` entry
  1415. # whose code carries an alert-level group produced a five-digit label
  1416. # like "0500_3000A" — not a code the user can look up, and never a
  1417. # catalogue key, so the sentence was lost with it.
  1418. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1419. except (TypeError, ValueError):
  1420. continue
  1421. description = err.get("description") or get_error_description(short_code)
  1422. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1423. # groups and is not a code anyone can look up; its full code in the
  1424. # printer screen's four groups is (#2728).
  1425. full_code = str(err.get("full_code") or "")
  1426. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1427. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1428. return "; ".join(parts) if parts else None
  1429. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1430. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1431. print completes successfully. Gated to status=='completed': failed, cancelled
  1432. and aborted prints do not count as usage. Caller is responsible for committing
  1433. the session. No-op when the queue item has no linked library file (e.g. reprints
  1434. from an archive). See #1008."""
  1435. if queue_status != "completed" or item.library_file_id is None:
  1436. return
  1437. from backend.app.models.library import LibraryFile
  1438. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1439. if lib_file is None:
  1440. return
  1441. lib_file.print_count = (lib_file.print_count or 0) + 1
  1442. lib_file.last_printed_at = datetime.now(timezone.utc)
  1443. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1444. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1445. When on_print_complete fires with status 'failed' for a printer in this set we
  1446. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1447. rather than a 'print failed' notification.
  1448. """
  1449. _user_stopped_printers.add(printer_id)
  1450. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1451. _last_status_broadcast: dict[int, str] = {}
  1452. # Track printers where we've updated nozzle_count
  1453. _nozzle_count_updated: set[int] = set()
  1454. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1455. """Wait the debounce window then fire `on_printer_offline` if the printer
  1456. is still offline.
  1457. Scheduled by `on_printer_status_change` on the connected → disconnected
  1458. edge (#1752). Cancelled by the same handler if the printer reconnects
  1459. before the window elapses, so a single MQTT blip + recovery doesn't
  1460. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1461. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1462. route through the same status-change callback, so this covers both.
  1463. """
  1464. logger = logging.getLogger(__name__)
  1465. try:
  1466. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1467. still_offline = not printer_manager.is_connected(printer_id)
  1468. logger.info(
  1469. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1470. printer_id,
  1471. still_offline,
  1472. )
  1473. if not still_offline:
  1474. return
  1475. async with async_session() as db:
  1476. from backend.app.models.printer import Printer
  1477. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1478. printer = result.scalar_one_or_none()
  1479. if not printer:
  1480. logger.warning(
  1481. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1482. printer_id,
  1483. )
  1484. return
  1485. # Recorded only when the relay can publish it, so the reconnect's
  1486. # online event always has an offline before it.
  1487. if mqtt_relay.enabled and mqtt_relay.connected:
  1488. _printer_offline_published.add(printer_id)
  1489. try:
  1490. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1491. except Exception as e:
  1492. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1493. logger.info(
  1494. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1495. printer_id,
  1496. printer.name,
  1497. )
  1498. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1499. except asyncio.CancelledError:
  1500. raise
  1501. except Exception as e:
  1502. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1503. finally:
  1504. _printer_offline_notify_tasks.pop(printer_id, None)
  1505. def _hms_notify_key(error) -> str:
  1506. """What identifies a fault for notification de-duplication.
  1507. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1508. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1509. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1510. and -0006 together) shared a key and only the first was ever notified. An
  1511. entry without a full code falls back to attr and code together.
  1512. """
  1513. full_code = getattr(error, "full_code", "") or ""
  1514. if full_code:
  1515. return full_code.upper()
  1516. return f"{error.attr:08X}:{error.code}"
  1517. def _hms_fault_counts(error) -> bool:
  1518. """Whether a fault counts as a problem: the same rule the frontend's
  1519. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1520. It counts when Bambu publishes text for it or it offers action buttons, and
  1521. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1522. no actions does not count: those are things like "the top cover is open" or
  1523. "the chamber is hot, fan speed increased", which a printer can hold through
  1524. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1525. it always has; those are prompts such as "unable to start drying" (#2728).
  1526. """
  1527. if error.severity < 1:
  1528. return False
  1529. has_actions = bool(getattr(error, "actions", None))
  1530. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1531. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1532. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1533. """The new faults that count (see ``_hms_fault_counts``).
  1534. These go to the MQTT relay; the caller also needs a description before it
  1535. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1536. used to read ``severity >= 2`` when severity held the part byte; on the real
  1537. level that would drop the task-stopping errors (#2728).
  1538. """
  1539. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1540. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1541. """The faults on this printer not notified yet, and record them as notified.
  1542. Tracking is updated before anything is sent, so concurrent status callbacks
  1543. cannot notify the same fault twice. A notified fault is forgotten once it
  1544. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1545. and on is notified once (#3226), while one that clears and comes back much
  1546. later is notified again.
  1547. When ``print_state`` changes (a print resumed, started or finished), every
  1548. fault recorded so far is forgotten the first time it is gone, without the
  1549. wait: a runout fixed before resuming must be notified if it happens again a
  1550. few minutes later, while the printer sits paused. Not only the faults gone
  1551. at the change itself, because the update that flips the state can still
  1552. carry the old fault (a ``print_error`` entry stays until a payload brings
  1553. ``hms``).
  1554. """
  1555. now = time.time()
  1556. current = {_hms_notify_key(e) for e in errors}
  1557. seen = _notified_hms_errors.setdefault(printer_id, {})
  1558. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1559. if print_state is not None:
  1560. print_state = print_state.upper()
  1561. if _hms_print_state.get(printer_id, print_state) != print_state:
  1562. forget_when_gone.update(seen)
  1563. _hms_print_state[printer_id] = print_state
  1564. for key, last_seen in list(seen.items()):
  1565. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1566. del seen[key]
  1567. forget_when_gone.discard(key)
  1568. new = current - seen.keys()
  1569. for key in current:
  1570. seen[key] = now
  1571. if not seen:
  1572. _notified_hms_errors.pop(printer_id, None)
  1573. if not forget_when_gone:
  1574. _hms_forget_when_gone.pop(printer_id, None)
  1575. return _hms_errors_to_notify(errors, new)
  1576. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1577. # "Printing", -1 and 255 are "no stage" (#3211).
  1578. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1579. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1580. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1581. Records it as notified. Called only for a printing state with progress above 0.
  1582. Progress before the first layer is not progress through the print (#3211).
  1583. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1584. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1585. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1586. 75% notification together with Print Started, and since 75 was then on
  1587. record, 25 and 50 could never fire. So nothing counts while the printer
  1588. reports a layer count but has not started layer 1.
  1589. Without a layer count -- a print whose first frame carried no
  1590. ``total_layer_num``, until the pushall that asks for it is answered
  1591. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1592. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1593. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1594. reports neither keeps the old behaviour rather than never notifying.
  1595. """
  1596. if (state.layer_num or 0) < 1:
  1597. if (state.total_layers or 0) > 0:
  1598. return None
  1599. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1600. return None
  1601. progress = state.progress or 0
  1602. current_milestone = 0
  1603. if progress >= 75:
  1604. current_milestone = 75
  1605. elif progress >= 50:
  1606. current_milestone = 50
  1607. elif progress >= 25:
  1608. current_milestone = 25
  1609. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1610. _last_progress_milestone[printer_id] = current_milestone
  1611. return current_milestone
  1612. return None
  1613. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1614. """Handle printer status changes - broadcast via WebSocket."""
  1615. try:
  1616. notify_live_activities.observe(printer_id, state)
  1617. except Exception:
  1618. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1619. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1620. # transitions disconnected → connected — which covers both Bambuddy
  1621. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1622. # `reconcile_stale_active_prints` exactly once for this connection so
  1623. # any archive still in `status="printing"` that can't actually be
  1624. # running anymore (printer IDLE / different subtask / empty subtask)
  1625. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1626. # finished during a disconnect window + a smart-plug power cycle
  1627. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1628. # next boot. Reconciliation runs concurrently — it must not block the
  1629. # WebSocket dedup / broadcast logic below, and the connected edge is
  1630. # marked True BEFORE the await so concurrent status updates inside
  1631. # the same connection don't re-trigger reconciliation.
  1632. #
  1633. # Wait for a real push_status before reconciling (#1679): MQTT
  1634. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1635. # the connection, BEFORE `_request_push_all` round-trips. At that
  1636. # instant the `PrinterState` is still on construction defaults — most
  1637. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1638. # If reconcile spawns here, every in-flight archive falls through to
  1639. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1640. # creates a duplicate archive on the real PRINT COMPLETE and
  1641. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1642. # keeps the #1542 mechanism intact: once the first real push_status
  1643. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1644. # fires again with the flag still False — reconcile then runs against
  1645. # actual evidence.
  1646. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1647. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1648. _printer_reconciled_since_connect[printer_id] = True
  1649. spawn_background_task(
  1650. reconcile_stale_active_prints(printer_id),
  1651. name=f"reconcile-stale-prints-{printer_id}",
  1652. )
  1653. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1654. # Re-arm so the next reconnect triggers reconciliation again.
  1655. _printer_reconciled_since_connect[printer_id] = False
  1656. # Same edge, for the calibration table the AMS card reads its K values from.
  1657. #
  1658. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1659. # tables to ask for. A `state_known` gate alone is not enough: the first
  1660. # real push_status is what makes the state known, and the nozzle fields do
  1661. # not always arrive in it. Latching there would spend this connection's one
  1662. # attempt on a printer that could not yet say what was fitted.
  1663. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1664. if (
  1665. state.connected
  1666. and state_known
  1667. and nozzle_known
  1668. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1669. ):
  1670. _printer_kprofiles_primed_since_connect[printer_id] = True
  1671. spawn_background_task(
  1672. prime_kprofile_table(printer_id),
  1673. name=f"prime-kprofiles-{printer_id}",
  1674. )
  1675. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1676. _printer_kprofiles_primed_since_connect[printer_id] = False
  1677. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1678. # else in the AMS report changing -- a power cycle does it to every slot --
  1679. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1680. # while the printer is idle; needs_check is cheap and throttled per slot.
  1681. # Guarded: nothing here may stop the status broadcast below.
  1682. try:
  1683. if not state.connected:
  1684. kprofile_drift.forget_printer(printer_id)
  1685. elif kprofile_drift.needs_check(printer_id, state):
  1686. spawn_background_task(
  1687. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1688. name=f"reapply-kprofiles-{printer_id}",
  1689. )
  1690. except Exception:
  1691. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1692. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1693. # connected → disconnected. The "back online" channel is already covered
  1694. # by the print-failure notification (firmware reports gcode_state=FAILED
  1695. # on reconnect of an interrupted print), so there is no online
  1696. # notification. The MQTT relay gets both: offline after the debounce, and
  1697. # online on the reconnect that follows a published offline.
  1698. prev_connected = _printer_last_connected.get(printer_id)
  1699. _printer_last_connected[printer_id] = state.connected
  1700. if prev_connected is True and not state.connected:
  1701. existing = _printer_offline_notify_tasks.get(printer_id)
  1702. if existing is None or existing.done():
  1703. logging.getLogger(__name__).info(
  1704. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1705. printer_id,
  1706. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1707. )
  1708. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1709. _maybe_notify_printer_offline(printer_id),
  1710. name=f"printer-offline-notify-{printer_id}",
  1711. )
  1712. elif state.connected:
  1713. # Kept until the relay can actually send online: with its broker down
  1714. # now, the next status update after the reconnect sends it.
  1715. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1716. _printer_offline_published.discard(printer_id)
  1717. printer_info = printer_manager.get_printer(printer_id)
  1718. if printer_info:
  1719. try:
  1720. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1721. except Exception as e:
  1722. logging.getLogger(__name__).warning(
  1723. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1724. )
  1725. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1726. if pending is not None and not pending.done():
  1727. logging.getLogger(__name__).info(
  1728. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1729. printer_id,
  1730. )
  1731. pending.cancel()
  1732. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1733. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1734. temps = state.temperatures or {}
  1735. nozzle_temp = round(temps.get("nozzle", 0))
  1736. bed_temp = round(temps.get("bed", 0))
  1737. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1738. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1739. # Auto-detect dual-nozzle printers from MQTT temperature data
  1740. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1741. _nozzle_count_updated.add(printer_id)
  1742. # Update nozzle_count in database
  1743. async with async_session() as db:
  1744. from backend.app.models.printer import Printer
  1745. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1746. printer = result.scalar_one_or_none()
  1747. if printer and printer.nozzle_count != 2:
  1748. printer.nozzle_count = 2
  1749. await db.commit()
  1750. logging.getLogger(__name__).info(
  1751. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1752. )
  1753. # Include target temps for heating phase detection
  1754. bed_target = round(temps.get("bed_target", 0))
  1755. nozzle_target = round(temps.get("nozzle_target", 0))
  1756. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1757. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1758. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1759. #
  1760. # dry_countdown_stalled rides along because it is the one drying signal the
  1761. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1762. # dry_time stopped moving, so on the frame that flips it every other member
  1763. # of this key is identical and the push would be deduplicated away. Mid-print
  1764. # a temperature would eventually break the tie, but a parked command on an
  1765. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1766. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1767. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1768. ams_dry_key = (
  1769. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1770. if state.raw_data
  1771. else ()
  1772. )
  1773. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1774. #
  1775. # The filament identity fields are here because Configure Slot writes
  1776. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1777. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1778. # matched, this function returned before broadcasting, and the card kept
  1779. # showing the old filament until the 30s fallback poll or a page reload —
  1780. # even though the configure route asks the printer for a fresh pushall and
  1781. # that push does carry the new values. Reset always worked, because it
  1782. # clears tray_type.
  1783. #
  1784. # These fields only change when someone configures a slot or swaps a spool,
  1785. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1786. ams_tray_key = (
  1787. tuple(
  1788. (
  1789. t.get("id"),
  1790. t.get("tray_type", ""),
  1791. t.get("state"),
  1792. t.get("tray_color", ""),
  1793. t.get("tray_info_idx", ""),
  1794. t.get("tray_sub_brands", ""),
  1795. t.get("cali_idx"),
  1796. )
  1797. for a in (state.raw_data.get("ams") or [])
  1798. for t in a.get("tray", [])
  1799. )
  1800. if state.raw_data
  1801. else ()
  1802. )
  1803. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1804. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1805. # in the AMS change-hash (tray fields only, and widening that would fire
  1806. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1807. # screen changed no key at all and the card's inlet badges sat stale until a
  1808. # reload. Like the filament-backup flag, these only move when someone
  1809. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1810. fts_key = (
  1811. state.fila_switch.installed if state.fila_switch else False,
  1812. tuple(sorted(state.ams_switch_inlet.items())),
  1813. # Which hotend holds which slot. Unlike the two above this does move
  1814. # mid-print, on every filament change — but only between discrete slots,
  1815. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1816. # it live: it decides which hotend the Load dialog may offer and whether
  1817. # Unload has anything to act on.
  1818. tuple(
  1819. sorted(
  1820. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1821. # Sort on the extruder id alone: the other members are nullable
  1822. # and comparing None with an int raises.
  1823. key=lambda entry: entry[0],
  1824. )
  1825. ),
  1826. )
  1827. status_key = (
  1828. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1829. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1830. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1831. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1832. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1833. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1834. )
  1835. # Fields that change only when the machine does (a nozzle swap, a firmware
  1836. # update, developer mode) or once per print (its AMS mapping): no traffic,
  1837. # but on an idle printer nothing else moves the key when they change.
  1838. machine_key = (
  1839. tuple((n.nozzle_type, n.nozzle_diameter) for n in (state.nozzles or [])),
  1840. state.firmware_version,
  1841. state.developer_mode,
  1842. tuple(state.print_ams_mapping) if isinstance(state.print_ams_mapping, list) else None,
  1843. )
  1844. status_key = f"{status_key}:{machine_key}"
  1845. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1846. if not is_active_print:
  1847. _unauthorized_print_kill_sent.discard(printer_id)
  1848. elif printer_id in _unauthorized_print_kill_sent:
  1849. # stop_print() was already sent for this print; avoid all further
  1850. # ownership and settings work until the printer leaves an active state.
  1851. pass
  1852. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1853. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1854. _unauthorized_print_kill_sent.discard(printer_id)
  1855. else:
  1856. kill_switch_enabled = False
  1857. authorization: bool | None = None
  1858. status_logger = logging.getLogger(__name__)
  1859. try:
  1860. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1861. if kill_switch_enabled:
  1862. async with async_session() as db:
  1863. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1864. except Exception as e:
  1865. # Fail safe: a database/reconciliation error must never turn into an
  1866. # irreversible stop of a print whose ownership is still unknown.
  1867. authorization = None
  1868. status_logger.warning(
  1869. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1870. )
  1871. if not kill_switch_enabled or authorization is True:
  1872. _unauthorized_print_kill_sent.discard(printer_id)
  1873. elif authorization is None:
  1874. _unauthorized_print_kill_sent.discard(printer_id)
  1875. status_logger.debug(
  1876. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1877. printer_id,
  1878. )
  1879. else:
  1880. try:
  1881. stopped = printer_manager.stop_print(printer_id)
  1882. if stopped:
  1883. _unauthorized_print_kill_sent.add(printer_id)
  1884. _kill_switch_stopped.add(printer_id)
  1885. printer_info = printer_manager.get_printer(printer_id)
  1886. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1887. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1888. notification_data = {
  1889. "status": "stopped",
  1890. "filename": state.gcode_file or state.current_print or "",
  1891. "subtask_name": state.subtask_name or "",
  1892. "progress": state.progress,
  1893. "reason": "unauthorized_print",
  1894. }
  1895. status_logger.warning(
  1896. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1897. printer_id,
  1898. state.state,
  1899. )
  1900. try:
  1901. await ws_manager.broadcast(
  1902. {
  1903. "type": "kill_switch_triggered",
  1904. "printer_id": printer_id,
  1905. "printer_name": printer_name,
  1906. "filename": filename,
  1907. "reason": "unauthorized_print",
  1908. }
  1909. )
  1910. except Exception as e:
  1911. status_logger.warning(
  1912. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1913. )
  1914. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1915. if previous_task is not None and not previous_task.done():
  1916. previous_task.cancel()
  1917. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1918. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1919. name=f"kill-switch-notification-{printer_id}",
  1920. )
  1921. else:
  1922. status_logger.warning(
  1923. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1924. printer_id,
  1925. state.state,
  1926. )
  1927. except Exception as e:
  1928. status_logger.warning(
  1929. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1930. )
  1931. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1932. try:
  1933. printer_info = printer_manager.get_printer(printer_id)
  1934. if printer_info:
  1935. await mqtt_relay.on_printer_status(
  1936. printer_id,
  1937. state,
  1938. printer_info.name,
  1939. printer_info.serial_number,
  1940. printer_manager.is_awaiting_plate_clear(printer_id),
  1941. )
  1942. except Exception:
  1943. pass # Don't fail status callback if MQTT fails
  1944. if _last_status_broadcast.get(printer_id) == status_key:
  1945. return # No change, skip WebSocket broadcast
  1946. _last_status_broadcast[printer_id] = status_key
  1947. # Check for progress milestone notifications (25%, 50%, 75%)
  1948. progress = state.progress or 0
  1949. is_printing = state.state in ("RUNNING", "PRINTING")
  1950. if is_printing and progress > 0:
  1951. current_milestone = _progress_milestone_to_notify(printer_id, state)
  1952. if current_milestone is not None:
  1953. try:
  1954. from backend.app.models.printer import Printer
  1955. # Read the printer in a short session and release the connection
  1956. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1957. # pinned a pooled connection per milestone, per printer (issue #2572).
  1958. async with async_session() as db:
  1959. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1960. printer = result.scalar_one_or_none()
  1961. printer_name = printer.name if printer else f"Printer {printer_id}"
  1962. filename = state.subtask_name or state.gcode_file or "Unknown"
  1963. # remaining_time is in minutes, convert to seconds for notification
  1964. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1965. # Capture camera snapshot for notification image attachment (no DB held).
  1966. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1967. # Notification send needs a session (provider/template lookups).
  1968. async with async_session() as db:
  1969. await notification_service.on_print_progress(
  1970. printer_id,
  1971. printer_name,
  1972. filename,
  1973. current_milestone,
  1974. db,
  1975. remaining_time_seconds,
  1976. image_data=image_data,
  1977. )
  1978. except Exception as e:
  1979. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1980. elif progress < 5:
  1981. # Reset milestone tracking when print restarts or new print begins
  1982. _last_progress_milestone[printer_id] = 0
  1983. _first_layer_notified[printer_id] = False
  1984. # HMS error codes that should not trigger notifications even though they
  1985. # have known descriptions (e.g. user-initiated actions, not real errors).
  1986. _HMS_NOTIFICATION_SUPPRESS = {
  1987. "0500_400E", # Printing was cancelled (user action, not an error)
  1988. }
  1989. # Check for new HMS errors and send notifications
  1990. current_hms_errors = getattr(state, "hms_errors", []) or []
  1991. if current_hms_errors:
  1992. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  1993. if new_errors:
  1994. try:
  1995. from backend.app.models.printer import Printer
  1996. # Read the printer in a short session and release the connection
  1997. # BEFORE the ~15s camera snapshot below (issue #2572).
  1998. async with async_session() as db:
  1999. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2000. printer = result.scalar_one_or_none()
  2001. printer_name = printer.name if printer else f"Printer {printer_id}"
  2002. # Format error details for notification
  2003. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  2004. module_names = {
  2005. 0x03: "Print/Task",
  2006. 0x05: "Nozzle/Extruder",
  2007. 0x07: "AMS/Filament",
  2008. 0x0C: "Motion Controller",
  2009. 0x12: "Chamber",
  2010. }
  2011. # Capture camera snapshot once for all error notifications (no DB held).
  2012. error_image_data = await _capture_snapshot_for_notification(
  2013. printer_id, printer, logging.getLogger(__name__)
  2014. )
  2015. # Notification sends need a session (provider/template lookups).
  2016. async with async_session() as db:
  2017. sent_count = 0
  2018. for error in new_errors:
  2019. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  2020. # Build short code like "0700_8010"
  2021. # Mask to 16 bits to handle printers that send larger values
  2022. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  2023. error_code_masked = error_code_int & 0xFFFF
  2024. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  2025. # Only notify for errors Bambu publishes text for — printers
  2026. # send undocumented codes that aren't real errors, and Bambu
  2027. # lists some with empty text. Resolved at parse time (#2926);
  2028. # short_code is still needed for the suppression set below.
  2029. description = error.description
  2030. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  2031. continue
  2032. error_type = f"{module_name} Error"
  2033. error_detail = description
  2034. await notification_service.on_printer_error(
  2035. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  2036. )
  2037. sent_count += 1
  2038. if sent_count:
  2039. logging.getLogger(__name__).info(
  2040. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  2041. )
  2042. # Also publish to MQTT relay (no DB): every new fault that
  2043. # counts, with or without text, the same set the UI counts.
  2044. printer_info = printer_manager.get_printer(printer_id)
  2045. if printer_info:
  2046. errors_data = [
  2047. {
  2048. "code": e.code,
  2049. "attr": e.attr,
  2050. "module": e.module,
  2051. "severity": e.severity,
  2052. }
  2053. for e in new_errors
  2054. ]
  2055. await mqtt_relay.on_printer_error(
  2056. printer_id, printer_info.name, printer_info.serial_number, errors_data
  2057. )
  2058. except Exception as e:
  2059. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  2060. else:
  2061. # No HMS errors: nothing to send, but faults gone long enough (or gone
  2062. # across a print state change) are forgotten. Some codes, e.g. chamber
  2063. # temperature regulation during PETG prints, toggle every few seconds.
  2064. _take_new_hms_faults(printer_id, [], state.state)
  2065. await ws_manager.send_printer_status(
  2066. printer_id,
  2067. printer_state_to_dict(
  2068. state,
  2069. printer_id,
  2070. printer_manager.get_model(printer_id),
  2071. printer_manager.get_drying_targets(printer_id),
  2072. ),
  2073. )
  2074. def _is_bambu_uuid(tray_uuid: str) -> bool:
  2075. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  2076. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  2077. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  2078. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  2079. K-profiles are per-nozzle and the printer's calibration table is numbered
  2080. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  2081. switch's other inlet therefore silently invalidates every configured slot in
  2082. it: the index stays put and now resolves against the other nozzle's table.
  2083. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  2084. and 0.020 on the right kept the left profile after the move, and a manual
  2085. RFID re-read only re-asserted the same wrong one.
  2086. Configuring a slot is a deliberate preparation step, so this re-selects
  2087. rather than re-configures: only the calibration binding moves, and only for
  2088. slots whose spool already has a stored profile for the new nozzle. A slot
  2089. Bambuddy knows nothing about is left exactly as the operator left it.
  2090. """
  2091. logger = logging.getLogger(__name__)
  2092. target_extruder = extruder_for_inlet(inlet)
  2093. if target_extruder is None:
  2094. return
  2095. client = printer_manager.get_client(printer_id)
  2096. state = printer_manager.get_status(printer_id)
  2097. if not client or not state or not state.raw_data:
  2098. return
  2099. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  2100. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  2101. # the nozzle width, which changes both the K profile to select and the
  2102. # preset the slot should carry.
  2103. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  2104. ams_raw = state.raw_data.get("ams")
  2105. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2106. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  2107. if not unit:
  2108. return
  2109. try:
  2110. async with async_session() as db:
  2111. for tray in unit.get("tray", []):
  2112. tray_id = int(tray.get("id", -1))
  2113. if tray_id < 0 or not tray.get("tray_type"):
  2114. continue
  2115. current_idx = tray.get("cali_idx")
  2116. profile = await find_slot_kprofile_for_extruder(
  2117. db,
  2118. printer_id,
  2119. ams_id,
  2120. tray_id,
  2121. target_extruder,
  2122. nozzle_diameter,
  2123. printer_manager.get_model(printer_id),
  2124. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2125. )
  2126. if profile is None or profile.cali_idx is None:
  2127. continue
  2128. if current_idx == profile.cali_idx:
  2129. continue # Already on the right one.
  2130. logger.info(
  2131. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2132. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2133. printer_id,
  2134. ams_id,
  2135. tray_id,
  2136. inlet,
  2137. target_extruder,
  2138. profile.name,
  2139. current_idx,
  2140. profile.cali_idx,
  2141. profile.k_value,
  2142. )
  2143. client.extrusion_cali_sel(
  2144. ams_id=ams_id,
  2145. tray_id=tray_id,
  2146. cali_idx=profile.cali_idx,
  2147. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2148. nozzle_diameter=nozzle_diameter,
  2149. )
  2150. except Exception as e:
  2151. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2152. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2153. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2154. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2155. from the delayed re-check -- which is why it takes the AMS data and print
  2156. state as arguments instead of reading them from the push (#3186).
  2157. """
  2158. logger = logging.getLogger(__name__)
  2159. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2160. # Auto-unlink spool assignments with stale fingerprints. Under the
  2161. # per-printer assignment lock since #3186: the held-removal re-check runs
  2162. # this outside any MQTT push, so it can now overlap one.
  2163. try:
  2164. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2165. from sqlalchemy.orm import selectinload
  2166. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2167. from backend.app.models.spool import Spool as _Spool
  2168. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2169. from backend.app.services.ams_slot_presence import spool_present
  2170. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2171. # Built-in assignments only. Since #2812 they survive a switch to
  2172. # Spoolman mode rather than being deleted by it, and this pass ends
  2173. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2174. # time as the AMS contents changed under the other mode, undoing the
  2175. # preservation more slowly but just as completely.
  2176. assignments = []
  2177. if not await spoolman_owns_assignments(db):
  2178. result = await db.execute(
  2179. select(SA)
  2180. .where(SA.printer_id == printer_id)
  2181. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2182. )
  2183. assignments = result.scalars().all()
  2184. # ``printing_now`` (top of this function) keeps a runout from
  2185. # unlinking the spool that fed the print — the next idle-time pass
  2186. # unlinks it if the user really did take it out.
  2187. stale = []
  2188. # Removals this pass is holding rather than unlinking (#3186).
  2189. held: set[tuple] = set()
  2190. for assignment in assignments:
  2191. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2192. if assignment.ams_id == 255:
  2193. ps = printer_manager.get_status(printer_id)
  2194. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2195. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2196. current_tray = None
  2197. for vt in vt_tray_raw:
  2198. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2199. current_tray = vt
  2200. break
  2201. if not current_tray:
  2202. # vt_tray data may not have arrived yet — keep assignment
  2203. continue
  2204. else:
  2205. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2206. if not current_tray:
  2207. if printing_now:
  2208. logger.info(
  2209. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2210. assignment.spool_id,
  2211. assignment.ams_id,
  2212. assignment.tray_id,
  2213. )
  2214. continue
  2215. # A whole AMS unit can drop out of one push and come back in
  2216. # the next; only a slot that stays gone is a removal (#3186).
  2217. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2218. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2219. held.add(hold_key)
  2220. logger.info(
  2221. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2222. "unlinking if it is still gone in %ds",
  2223. assignment.spool_id,
  2224. assignment.ams_id,
  2225. assignment.tray_id,
  2226. int(slot_unlink_grace.GRACE_SECONDS),
  2227. )
  2228. continue
  2229. logger.info(
  2230. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2231. assignment.spool_id,
  2232. assignment.ams_id,
  2233. assignment.tray_id,
  2234. )
  2235. stale.append(assignment) # Slot empty
  2236. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2237. # A Bambu Lab spool is in this slot — check if it's the same spool
  2238. # that's currently assigned. If yes, keep the assignment (avoids
  2239. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2240. # the printer's filament preset on every startup).
  2241. tray_uuid = current_tray.get("tray_uuid", "")
  2242. tag_uid = current_tray.get("tag_uid", "")
  2243. spool = assignment.spool
  2244. spool_matches = False
  2245. if spool:
  2246. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2247. spool.tag_uid
  2248. and tag_uid
  2249. and tag_uid != "0000000000000000"
  2250. and spool.tag_uid.upper() == tag_uid.upper()
  2251. ):
  2252. spool_matches = True
  2253. if spool_matches:
  2254. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2255. cur_color = current_tray.get("tray_color", "")
  2256. cur_type = current_tray.get("tray_type", "")
  2257. fp_color = assignment.fingerprint_color or ""
  2258. fp_type = assignment.fingerprint_type or ""
  2259. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2260. assignment.fingerprint_color = cur_color
  2261. assignment.fingerprint_type = cur_type
  2262. logger.debug(
  2263. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2264. assignment.spool_id,
  2265. assignment.ams_id,
  2266. assignment.tray_id,
  2267. )
  2268. continue
  2269. # Different BL spool or unrecognized — unlink so auto-assign can match
  2270. logger.info(
  2271. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2272. assignment.spool_id,
  2273. assignment.ams_id,
  2274. assignment.tray_id,
  2275. tray_uuid,
  2276. )
  2277. stale.append(assignment)
  2278. else:
  2279. cur_color = current_tray.get("tray_color", "")
  2280. cur_type = current_tray.get("tray_type", "")
  2281. cur_state = current_tray.get("state")
  2282. fp_color = assignment.fingerprint_color or ""
  2283. fp_type = assignment.fingerprint_type or ""
  2284. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2285. # the slot was empty when the user pre-assigned via SpoolBuddy
  2286. # (the firmware drops ams_filament_setting on empty slots, so
  2287. # MQTT was deferred). The moment any filament gets inserted
  2288. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2289. # reconfigured spool — fire the deferred configuration.
  2290. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2291. # extruder" code) OR, on firmwares that don't use the state
  2292. # enum meaningfully, a non-empty tray_type when state is
  2293. # NOT one of the firmware's explicit empty signals (9, 10).
  2294. # state-only was wrong for firmwares that never set 11 — A1
  2295. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2296. # always report state=3 — so the replay never fired for them
  2297. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2298. # explicit "empty" signals authoritative over any stale
  2299. # tray_type that might survive the relay's auto-clearing.
  2300. #
  2301. # tray_exist_bits comes first because that guard cannot tell
  2302. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2303. # writes state=9 when the bit is 0 and leaves it there when the
  2304. # bit returns. A non-RFID spool inserted into a pre-assigned
  2305. # slot brings no tray_type with it, so the stale 9 made this
  2306. # expression false forever and the deferred config never fired
  2307. # — the deadlock #1322 removed from the assign path, still in
  2308. # place here (#3084, #3100).
  2309. loaded = spool_present(current_tray) is True or (
  2310. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2311. )
  2312. if not fp_type.strip() and loaded and assignment.spool:
  2313. try:
  2314. from backend.app.api.routes.inventory import (
  2315. apply_spool_to_slot_via_mqtt,
  2316. )
  2317. await apply_spool_to_slot_via_mqtt(
  2318. db=db,
  2319. current_user=None,
  2320. spool=assignment.spool,
  2321. printer_id=printer_id,
  2322. ams_id=assignment.ams_id,
  2323. tray_id=assignment.tray_id,
  2324. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2325. current_tray_type=cur_type,
  2326. current_tray_sub_brands=current_tray.get("tray_sub_brands", ""),
  2327. )
  2328. logger.info(
  2329. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2330. assignment.spool_id,
  2331. printer_id,
  2332. assignment.ams_id,
  2333. assignment.tray_id,
  2334. )
  2335. except Exception:
  2336. logger.exception(
  2337. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2338. assignment.spool_id,
  2339. printer_id,
  2340. assignment.ams_id,
  2341. assignment.tray_id,
  2342. )
  2343. assignment.fingerprint_color = cur_color
  2344. assignment.fingerprint_type = cur_type
  2345. continue
  2346. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2347. # Blank tray data mid-print is a runout, not a swap: the
  2348. # firmware clears colour and type when it unloads a spool
  2349. # it just emptied. Unlinking here would erase the record
  2350. # of which spool fed the print so far.
  2351. if printing_now and not cur_color.strip() and not cur_type.strip():
  2352. logger.info(
  2353. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2354. "(runout?)",
  2355. assignment.spool_id,
  2356. assignment.ams_id,
  2357. assignment.tray_id,
  2358. )
  2359. continue
  2360. # Same reasoning off the print, on firmware's own say-so:
  2361. # a blank tray report from a slot whose tray_exist_bits
  2362. # bit is set describes a spool the AMS cannot identify —
  2363. # a non-RFID one, or one whose slot was reset — not a
  2364. # spool that was taken out. Deleting the assignment there
  2365. # threw away the identity the user had supplied, which is
  2366. # the only place it existed (#3100). A slot the bit calls
  2367. # empty, or one that carries no bit at all, still unlinks.
  2368. #
  2369. # Unless the slot was reported empty first: a removal
  2370. # already held means a spool came out and another went
  2371. # in, so the blank report keeps the hold running below
  2372. # rather than cancelling it (#3186).
  2373. if (
  2374. spool_present(current_tray) is True
  2375. and not cur_color.strip()
  2376. and not cur_type.strip()
  2377. and not slot_unlink_grace.is_held(
  2378. printer_id,
  2379. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2380. )
  2381. ):
  2382. logger.info(
  2383. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2384. "tray reports no filament data yet",
  2385. assignment.spool_id,
  2386. assignment.ams_id,
  2387. assignment.tray_id,
  2388. )
  2389. continue
  2390. # A blank report the presence bit does not vouch for is
  2391. # still only one push. An idle X1C cleared a whole AMS
  2392. # unit's bits, colour and type for a moment and lost
  2393. # four saved assignments that way (#3186); unlink only
  2394. # if the slot is still blank after the grace period.
  2395. if not cur_color.strip() and not cur_type.strip():
  2396. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2397. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2398. held.add(hold_key)
  2399. logger.info(
  2400. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2401. "unlinking if it is still blank in %ds",
  2402. assignment.spool_id,
  2403. assignment.ams_id,
  2404. assignment.tray_id,
  2405. int(slot_unlink_grace.GRACE_SECONDS),
  2406. )
  2407. continue
  2408. # Fingerprint mismatch — but check if tray now matches the
  2409. # assigned spool (e.g. auto-configure changed the tray).
  2410. # Both sides are reduced to the type the slot can carry
  2411. # before comparing: the assign path writes that rather
  2412. # than the spool's raw material (#2902), so a spool whose
  2413. # material is a product line — "PLA+", "HTPLA" — reports
  2414. # back as "PLA" and would otherwise fail this check and
  2415. # be auto-unlinked from the slot it was just assigned to.
  2416. # Reducing the printer's side too keeps slots configured
  2417. # by an older Bambuddy, still reporting "PLA+", matching.
  2418. spool = assignment.spool
  2419. if spool:
  2420. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2421. # Two ways the assign path can have arrived at the
  2422. # slot's type, so both count as "we wrote this".
  2423. # The material column is one; the spool's preset is
  2424. # the other, and it outranks the material when the
  2425. # spool has one -- a spool whose material says PLA
  2426. # and whose preset is "Bambu PLA Aero" puts
  2427. # PLA-AERO in the slot (#2902). Read from the stored
  2428. # preset name rather than resolving the preset,
  2429. # because this runs on every AMS push and a cloud
  2430. # lookup here would be both slow and unavailable on
  2431. # the unauthenticated replay path.
  2432. spool_types = {printer_filament_type(spool.material).upper()}
  2433. if spool.slicer_filament_name:
  2434. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2435. # An imported local preset stores its type outright,
  2436. # which is what the assign path used -- and the name
  2437. # above may be unset. One keyed read, and only on a
  2438. # mismatch, which is rare.
  2439. #
  2440. # slicer_filament is free text up to fifty characters,
  2441. # so the digits have to be checked against the range
  2442. # of the integer primary key they are about to be
  2443. # compared with. Postgres raises on an out-of-range
  2444. # integer rather than simply not matching, and that
  2445. # would poison this session and abandon the rest of
  2446. # the cleanup pass.
  2447. lp_ref = (spool.slicer_filament or "").strip()
  2448. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2449. from backend.app.models.local_preset import LocalPreset as _LP
  2450. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2451. if lp_type:
  2452. spool_types.add(printer_filament_type(lp_type).upper())
  2453. if (
  2454. _colors_similar(cur_color, spool_color)
  2455. and printer_filament_type(cur_type).upper() in spool_types
  2456. ):
  2457. logger.info(
  2458. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2459. assignment.spool_id,
  2460. assignment.ams_id,
  2461. assignment.tray_id,
  2462. )
  2463. assignment.fingerprint_color = cur_color
  2464. assignment.fingerprint_type = cur_type
  2465. continue
  2466. logger.info(
  2467. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2468. assignment.spool_id,
  2469. assignment.ams_id,
  2470. assignment.tray_id,
  2471. cur_color,
  2472. cur_type,
  2473. fp_color,
  2474. fp_type,
  2475. spool.rgba if spool else "?",
  2476. spool.material if spool else "?",
  2477. )
  2478. stale.append(assignment) # Spool changed
  2479. slot_unlink_grace.settle(printer_id, "inventory", held)
  2480. # Snapshot slots before delete — ORM attribute access after the
  2481. # commit would refresh against a deleted row.
  2482. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2483. for a in stale:
  2484. await db.delete(a)
  2485. if stale:
  2486. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2487. # Commit any changes (stale deletions and/or fingerprint updates)
  2488. await db.commit()
  2489. # Tell open browsers the assignment is gone (#2575). Only the manual
  2490. # REST assign/unassign endpoints broadcast this event; without it the
  2491. # frontend's spool-assignments cache keeps rendering the unlinked
  2492. # spool on the slot until an unrelated refetch — which reads exactly
  2493. # like "the fix didn't work" (reporter verified: a browser refresh
  2494. # after the swap showed the correct state all along).
  2495. for ams_id, tray_id in unlinked_slots:
  2496. await ws_manager.broadcast(
  2497. {
  2498. "type": "spool_assignment_changed",
  2499. "printer_id": printer_id,
  2500. "ams_id": ams_id,
  2501. "tray_id": tray_id,
  2502. }
  2503. )
  2504. except Exception as e:
  2505. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2506. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2507. """Delete Spoolman slot rows whose held removal has run its grace period.
  2508. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2509. talks to Spoolman for every tray; this only needs the local rows, so it
  2510. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2511. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2512. not in a slot the presence bit calls occupied -- and nothing else.
  2513. """
  2514. logger = logging.getLogger(__name__)
  2515. try:
  2516. async with async_session() as db:
  2517. from backend.app.api.routes.settings import get_setting
  2518. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2519. from backend.app.services.ams_slot_presence import spool_present
  2520. enabled = await get_setting(db, "spoolman_enabled")
  2521. if not enabled or enabled.lower() != "true":
  2522. return
  2523. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2524. if sync_mode and sync_mode != "auto":
  2525. return
  2526. trays: dict[tuple[int, int], dict] = {}
  2527. for ams_unit in ams_data or []:
  2528. if not isinstance(ams_unit, dict):
  2529. continue
  2530. for tray in ams_unit.get("tray", []):
  2531. if isinstance(tray, dict):
  2532. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2533. rows = (
  2534. (
  2535. await db.execute(
  2536. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2537. )
  2538. )
  2539. .scalars()
  2540. .all()
  2541. )
  2542. held: set[tuple] = set()
  2543. expired: list[tuple[int, int]] = []
  2544. for row in rows:
  2545. tray = trays.get((row.ams_id, row.tray_id))
  2546. if tray is None or printing_now:
  2547. continue
  2548. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2549. continue
  2550. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2551. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2552. continue
  2553. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2554. expired.append((row.ams_id, row.tray_id))
  2555. else:
  2556. held.add(hold_key)
  2557. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2558. if not expired:
  2559. return
  2560. # A statement rather than ORM deletes, like the sync pass: the two
  2561. # can overlap, and a row the other already removed must not fail
  2562. # this commit.
  2563. for ams_id, tray_id in expired:
  2564. await db.execute(
  2565. delete(SpoolmanSlotAssignment).where(
  2566. SpoolmanSlotAssignment.printer_id == printer_id,
  2567. SpoolmanSlotAssignment.ams_id == ams_id,
  2568. SpoolmanSlotAssignment.tray_id == tray_id,
  2569. )
  2570. )
  2571. await db.commit()
  2572. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2573. for ams_id, tray_id in expired:
  2574. await ws_manager.broadcast(
  2575. {
  2576. "type": "spool_assignment_changed",
  2577. "printer_id": printer_id,
  2578. "ams_id": ams_id,
  2579. "tray_id": tray_id,
  2580. }
  2581. )
  2582. except Exception as e:
  2583. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2584. async def _recheck_held_unlinks(printer_id: int) -> None:
  2585. """Re-run just the slot cleanup against the printer's current AMS state.
  2586. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2587. passes otherwise run only when the AMS hash changes, and a slot that went
  2588. empty and stayed empty may never change it again.
  2589. """
  2590. status = printer_manager.get_status(printer_id)
  2591. # A disconnected printer's state is its last report, not a new one: acting
  2592. # on it would "confirm" a removal nobody has seen for the whole grace
  2593. # period. Leave the holds; the first push after reconnecting decides.
  2594. if status is None or not status.connected:
  2595. return
  2596. ams_raw = status.raw_data.get("ams")
  2597. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2598. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2599. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2600. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2601. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2602. async def on_ams_change(printer_id: int, ams_data: list):
  2603. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2604. logger = logging.getLogger(__name__)
  2605. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  2606. # on_print_complete may pop _active_sessions during our awaits (#880).
  2607. from backend.app.services.usage_tracker import _active_sessions
  2608. _print_active = printer_id in _active_sessions
  2609. # A slot that reports empty while a print is running is a filament runout,
  2610. # not a spool swap: the spool is still physically in the AMS, just
  2611. # consumed. Dropping either inventory backend's slot link there loses the
  2612. # only record of which spool fed the print, so the completion path can't
  2613. # charge the runout segment to anything. Both cleanup passes below consult
  2614. # this; computed once, up front, so neither depends on the other having run.
  2615. _unlink_state = printer_manager.get_status(printer_id)
  2616. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2617. # The session alone is not enough: a restart that finds a stale persisted
  2618. # session registers none for the print that is running.
  2619. _print_active = _print_active or printing_now
  2620. # MQTT relay - publish AMS change
  2621. try:
  2622. printer_info = printer_manager.get_printer(printer_id)
  2623. if printer_info:
  2624. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2625. except Exception:
  2626. pass # Don't fail AMS callback if MQTT fails
  2627. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2628. # This ensures frontend gets immediate updates when AMS slots are configured
  2629. try:
  2630. state = printer_manager.get_status(printer_id)
  2631. if state:
  2632. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2633. await ws_manager.send_printer_status(
  2634. printer_id,
  2635. printer_state_to_dict(
  2636. state,
  2637. printer_id,
  2638. printer_manager.get_model(printer_id),
  2639. printer_manager.get_drying_targets(printer_id),
  2640. ),
  2641. )
  2642. except Exception as e:
  2643. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2644. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2645. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2646. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  2647. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2648. # "no existing assignment" for the same (printer, ams, tray) and race to
  2649. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2650. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2651. # bug stayed latent there. See _ams_assignment_locks comment for details.
  2652. try:
  2653. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2654. from sqlalchemy.orm import selectinload
  2655. from backend.app.api.routes.settings import get_setting
  2656. from backend.app.models.spool import Spool
  2657. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2658. from backend.app.services.spool_tag_matcher import (
  2659. auto_assign_spool,
  2660. create_spool_from_tray,
  2661. find_matching_untagged_spool,
  2662. get_spool_by_tag,
  2663. is_bambu_tag,
  2664. is_valid_tag,
  2665. link_tag_to_inventory_spool,
  2666. tag_belongs_to_archived_spool,
  2667. )
  2668. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2669. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2670. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2671. if not _spoolman_on or _spoolman_on.lower() != "true":
  2672. for ams_unit in ams_data:
  2673. if not isinstance(ams_unit, dict):
  2674. continue
  2675. ams_id = int(ams_unit.get("id", 0))
  2676. for tray in ams_unit.get("tray", []):
  2677. if not isinstance(tray, dict):
  2678. continue
  2679. tray_id = int(tray.get("id", 0))
  2680. tag_uid = tray.get("tag_uid", "")
  2681. tray_uuid = tray.get("tray_uuid", "")
  2682. tray_info_idx = tray.get("tray_info_idx", "")
  2683. if not tray.get("tray_type"):
  2684. # Slot reported empty — drop any cached unknown-tag
  2685. # broadcast so reinserting the same spool re-prompts.
  2686. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2687. continue # Empty slot
  2688. # Check if assignment already exists for this slot
  2689. existing = await db.execute(
  2690. select(SA)
  2691. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2692. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2693. )
  2694. existing_assignment = existing.scalar_one_or_none()
  2695. if existing_assignment:
  2696. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2697. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2698. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2699. # Skip during active prints: the usage tracker handles deduction
  2700. # precisely via 3MF data on print completion. Without this guard the
  2701. # AMS remain% SET and the usage tracker ADD both fire from the same
  2702. # MQTT message, doubling the deduction (#880).
  2703. if _print_active:
  2704. continue
  2705. remain_raw = tray.get("remain")
  2706. if (
  2707. remain_raw is not None
  2708. and existing_assignment.spool
  2709. and not existing_assignment.spool.weight_locked
  2710. ):
  2711. try:
  2712. remain_val = int(remain_raw)
  2713. except (TypeError, ValueError):
  2714. remain_val = -1
  2715. if 1 <= remain_val <= 100:
  2716. lw = existing_assignment.spool.label_weight or 1000
  2717. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2718. current_used = existing_assignment.spool.weight_used or 0
  2719. if new_used > current_used + 1:
  2720. logger.info(
  2721. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2722. existing_assignment.spool_id,
  2723. current_used,
  2724. new_used,
  2725. remain_val,
  2726. )
  2727. existing_assignment.spool.weight_used = new_used
  2728. await db.commit()
  2729. # A K-profile the slot lost (the default K after a reset or
  2730. # power cycle) is put back by kprofile_drift on the next idle
  2731. # push; a different real profile was picked on purpose and
  2732. # stays (#3219, item 44).
  2733. continue
  2734. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2735. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2736. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2737. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  2738. # An archived spool still in the AMS: the slot
  2739. # stays free rather than adopting its tag.
  2740. continue
  2741. if not spool:
  2742. # Try matching an untagged inventory spool (same material/color)
  2743. spool = await find_matching_untagged_spool(db, tray)
  2744. if spool:
  2745. await link_tag_to_inventory_spool(db, spool, tray)
  2746. elif _auto_add_unknown:
  2747. spool = await create_spool_from_tray(db, tray)
  2748. else:
  2749. # Auto-add disabled: surface the slot so the
  2750. # user can add it manually via the UI.
  2751. await _broadcast_unknown_tag(
  2752. printer_id=printer_id,
  2753. ams_id=ams_id,
  2754. tray_id=tray_id,
  2755. tag_uid=tag_uid,
  2756. tray_uuid=tray_uuid,
  2757. tray_type=tray.get("tray_type"),
  2758. tray_color=tray.get("tray_color"),
  2759. tray_sub_brands=tray.get("tray_sub_brands"),
  2760. tray_count=len(ams_unit.get("tray", [])),
  2761. )
  2762. continue
  2763. # Slot matched (existing tag, untagged inventory
  2764. # match, or freshly auto-created spool) — drop any
  2765. # stale dedup so a future tag swap re-prompts.
  2766. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2767. await auto_assign_spool(
  2768. printer_id,
  2769. ams_id,
  2770. tray_id,
  2771. spool,
  2772. printer_manager,
  2773. db,
  2774. tray_info_idx=tray_info_idx,
  2775. )
  2776. await db.commit()
  2777. await ws_manager.broadcast(
  2778. {
  2779. "type": "spool_auto_assigned",
  2780. "printer_id": printer_id,
  2781. "ams_id": ams_id,
  2782. "tray_id": tray_id,
  2783. "spool_id": spool.id,
  2784. }
  2785. )
  2786. logger.info(
  2787. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2788. spool.id,
  2789. printer_id,
  2790. ams_id,
  2791. tray_id,
  2792. )
  2793. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  2794. db, tag_uid, tray_uuid
  2795. ):
  2796. # Non-BL spool with some tag — let user choose (not
  2797. # an archived one's, whose slot stays free)
  2798. await _broadcast_unknown_tag(
  2799. printer_id=printer_id,
  2800. ams_id=ams_id,
  2801. tray_id=tray_id,
  2802. tag_uid=tag_uid,
  2803. tray_uuid=tray_uuid,
  2804. tray_type=tray.get("tray_type"),
  2805. tray_color=tray.get("tray_color"),
  2806. tray_sub_brands=tray.get("tray_sub_brands"),
  2807. tray_count=len(ams_unit.get("tray", [])),
  2808. )
  2809. # No-tag slots (generic non-RFID filament) are left alone:
  2810. # nothing to identify, prompting "+ Add" would just create
  2811. # ghost spools with empty tags on every confirm.
  2812. except Exception as e:
  2813. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2814. try:
  2815. async with async_session() as db:
  2816. from backend.app.api.routes.settings import get_setting
  2817. from backend.app.models.printer import Printer
  2818. # Check if Spoolman is enabled
  2819. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2820. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2821. return
  2822. # Check sync mode
  2823. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2824. if sync_mode and sync_mode != "auto":
  2825. return # Only sync on auto mode
  2826. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2827. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2828. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2829. # always owned by per-print tracking, never by AMS auto-sync. The
  2830. # setting is still read by the settings UI for backwards compat but
  2831. # has no effect on the sync path here.
  2832. # Get Spoolman URL
  2833. spoolman_url = await get_setting(db, "spoolman_url")
  2834. if not spoolman_url:
  2835. return
  2836. # Get or create Spoolman client
  2837. client = await get_spoolman_client()
  2838. if not client:
  2839. try:
  2840. client = await init_spoolman_client(spoolman_url)
  2841. except ValueError as exc:
  2842. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2843. return
  2844. # Check if Spoolman is reachable
  2845. if not await client.health_check():
  2846. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2847. return
  2848. # Get printer name for location
  2849. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2850. printer = result.scalar_one_or_none()
  2851. printer_name = printer.name if printer else f"Printer {printer_id}"
  2852. # OPTIMIZATION: Fetch all spools once before processing trays
  2853. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2854. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2855. try:
  2856. cached_spools = await client.get_spools()
  2857. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2858. except Exception as e:
  2859. logger.error(
  2860. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2861. printer_id,
  2862. e,
  2863. )
  2864. return
  2865. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2866. from sqlalchemy.orm import selectinload
  2867. from backend.app.models.spool_assignment import SpoolAssignment
  2868. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2869. from backend.app.services.ams_slot_presence import spool_present
  2870. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2871. # Built-in remaining weight, used by sync_ams_tray only when the
  2872. # firmware reports an unusable remain%/tray_weight for a slot.
  2873. #
  2874. # Left empty since #2812. This block runs in Spoolman mode only,
  2875. # and until then the built-in table was emptied on the switch, so
  2876. # there was never anything here to read and the fallback was inert.
  2877. # Preserving those rows makes it live again, and it is keyed by slot
  2878. # rather than by spool: after a mode switch the tray may well hold
  2879. # different filament, and ``create_spool`` writes ``remaining_weight``
  2880. # unconditionally, so a stale figure would be seeded into a brand new
  2881. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2882. # intent survives for whoever revisits the cross-mode fallback.
  2883. inventory_weights: dict[tuple[int, int], float] = {}
  2884. if not await spoolman_owns_assignments(db):
  2885. try:
  2886. assign_result = await db.execute(
  2887. select(SpoolAssignment)
  2888. .options(selectinload(SpoolAssignment.spool))
  2889. .where(SpoolAssignment.printer_id == printer_id)
  2890. )
  2891. for assignment in assign_result.scalars().all():
  2892. spool = assignment.spool
  2893. if spool and spool.label_weight > 0:
  2894. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2895. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2896. except Exception as e:
  2897. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2898. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2899. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2900. try:
  2901. slot_result = await db.execute(
  2902. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2903. )
  2904. for slot in slot_result.scalars().all():
  2905. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2906. except Exception as e:
  2907. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2908. # Sync each AMS tray and collect slot changes for DB persistence
  2909. synced = 0
  2910. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2911. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2912. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  2913. for ams_unit in ams_data:
  2914. if not isinstance(ams_unit, dict):
  2915. continue
  2916. ams_id = int(ams_unit.get("id", 0))
  2917. trays = ams_unit.get("tray", [])
  2918. for tray_data in trays:
  2919. if not isinstance(tray_data, dict):
  2920. continue
  2921. tray_id_raw = int(tray_data.get("id", 0))
  2922. tray = client.parse_ams_tray(ams_id, tray_data)
  2923. if not tray:
  2924. # Empty tray slot — record for local assignment cleanup
  2925. # and drop any cached unknown-tag broadcast so a
  2926. # reinserted spool re-prompts.
  2927. #
  2928. # Not during a running print: a slot that empties there
  2929. # is a filament runout, and the spool is still in the
  2930. # AMS. `spoolman_slot_assignments` is how a tag-less
  2931. # spool assigned through the Bambuddy UI is resolved at
  2932. # completion (#1459), so deleting the row mid-print
  2933. # loses the runout segment's usage — the same failure
  2934. # the internal inventory's auto-unlink had.
  2935. #
  2936. # Nor when firmware's presence bit says the slot is
  2937. # occupied. parse_ams_tray calls a tray with no type or
  2938. # no colour empty, and a spool the AMS cannot read has
  2939. # neither until something configures it — so a tag-less
  2940. # spool assigned through the UI had its row deleted by
  2941. # the first idle push after it was inserted. Same
  2942. # deletion as the internal inventory's in #3100, same
  2943. # answer, so the two modes stay in step.
  2944. #
  2945. # And only once the slot has stayed empty for the grace
  2946. # period -- the internal inventory's #3186 answer, for
  2947. # the same one-push blank.
  2948. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  2949. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  2950. if not printing_now and (
  2951. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  2952. ):
  2953. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2954. empty_slots.append((ams_id, tray_id_raw))
  2955. else:
  2956. spoolman_held.add(hold_key)
  2957. logger.info(
  2958. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  2959. "unlinking if it is still empty in %ds",
  2960. ams_id,
  2961. tray_id_raw,
  2962. linked_spool,
  2963. int(slot_unlink_grace.GRACE_SECONDS),
  2964. )
  2965. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2966. continue
  2967. spool_tag = (
  2968. tray.tray_uuid
  2969. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2970. else tray.tag_uid
  2971. )
  2972. # Provide the hint only when no RFID is available
  2973. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2974. try:
  2975. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2976. result = await client.sync_ams_tray(
  2977. tray,
  2978. printer_name,
  2979. db,
  2980. # Per-print tracking is the only weight writer (#1119).
  2981. # AMS auto-sync still maintains spool metadata / slot
  2982. # assignments but no longer touches remaining_weight.
  2983. disable_weight_sync=True,
  2984. cached_spools=cached_spools,
  2985. inventory_remaining=inv_remaining,
  2986. spoolman_spool_id_hint=hint,
  2987. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2988. )
  2989. if result is None and spool_tag and not auto_add_unknown_rfid:
  2990. # Spoolman skipped auto-create per user setting — surface
  2991. # the slot so the UI can offer "+ Add to inventory".
  2992. await _broadcast_unknown_tag(
  2993. printer_id=printer_id,
  2994. ams_id=ams_id,
  2995. tray_id=tray.tray_id,
  2996. tag_uid=tray.tag_uid or "",
  2997. tray_uuid=tray.tray_uuid or "",
  2998. tray_type=tray.tray_type,
  2999. tray_color=tray.tray_color,
  3000. tray_sub_brands=tray.tray_sub_brands,
  3001. tray_count=len(trays),
  3002. )
  3003. elif result:
  3004. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  3005. if result:
  3006. synced += 1
  3007. if result.get("id"):
  3008. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  3009. # If a new spool was created, add it to the cache
  3010. # so subsequent trays can find it if they reference the same tag
  3011. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  3012. if not spool_exists:
  3013. cached_spools.append(result)
  3014. logger.debug(
  3015. "[Printer %s] Added newly created spool %s to cache",
  3016. printer_id,
  3017. result["id"],
  3018. )
  3019. # Reconcile slot_preset_mappings (the same row internal
  3020. # mode keeps in sync via inventory + spool_tag_matcher).
  3021. # Without this the slot card surfaces the previous spool's
  3022. # preset name — same bug shape, different inventory mode.
  3023. from backend.app.services.slot_preset_writer import (
  3024. upsert_slot_preset_for_spoolman_spool,
  3025. )
  3026. await upsert_slot_preset_for_spoolman_spool(
  3027. db=db,
  3028. spoolman_spool=result,
  3029. tray_info_idx=tray.tray_info_idx or "",
  3030. tray_sub_brands=tray.tray_sub_brands or "",
  3031. tray_type=tray.tray_type or "",
  3032. printer_id=printer_id,
  3033. ams_id=ams_id,
  3034. tray_id=tray.tray_id,
  3035. )
  3036. except Exception as e:
  3037. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3038. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3039. if synced > 0:
  3040. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3041. # Persist slot assignment changes to the local table
  3042. if slot_changes or empty_slots:
  3043. try:
  3044. for ams_id, tray_id, spool_id in slot_changes:
  3045. await db.execute(
  3046. text(
  3047. "INSERT INTO spoolman_slot_assignments"
  3048. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  3049. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  3050. " ON CONFLICT(printer_id, ams_id, tray_id)"
  3051. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  3052. ),
  3053. {
  3054. "printer_id": printer_id,
  3055. "ams_id": ams_id,
  3056. "tray_id": tray_id,
  3057. "spool_id": spool_id,
  3058. },
  3059. )
  3060. for ams_id, tray_id in empty_slots:
  3061. await db.execute(
  3062. delete(SpoolmanSlotAssignment).where(
  3063. SpoolmanSlotAssignment.printer_id == printer_id,
  3064. SpoolmanSlotAssignment.ams_id == ams_id,
  3065. SpoolmanSlotAssignment.tray_id == tray_id,
  3066. )
  3067. )
  3068. await db.commit()
  3069. except Exception as e:
  3070. await db.rollback()
  3071. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3072. else:
  3073. # Tell open browsers the slot changed. This loop rewrites
  3074. # slot_preset_mappings via upsert_slot_preset_for_spoolman_spool
  3075. # above, and the AMS slot card reads that row ahead of the
  3076. # live tray_info_idx -- so with no event the card keeps
  3077. # showing the previous spool's preset name. Internal mode
  3078. # raises spool_auto_assigned for the same reason; this loop
  3079. # broadcast nothing at all, which made Spoolman mode the
  3080. # worse half of the same bug. On the else branch so a
  3081. # failed commit stays silent and a broadcast failure cannot
  3082. # roll back rows that are already committed.
  3083. for ams_id, tray_id, *_ in (*slot_changes, *empty_slots):
  3084. await ws_manager.broadcast(
  3085. {
  3086. "type": "spool_assignment_changed",
  3087. "printer_id": printer_id,
  3088. "ams_id": ams_id,
  3089. "tray_id": tray_id,
  3090. }
  3091. )
  3092. except Exception as e:
  3093. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3094. # Largest finish photo attached to a notification; a bigger one is still linked.
  3095. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3096. async def _finish_photo_for_notification(
  3097. db, archive, archive_id: int, filename: str
  3098. ) -> tuple[str | None, bytes | None]:
  3099. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3100. With authentication off the link is the archive's own photo route, as it
  3101. always was: it opens without a login and doesn't expire. With
  3102. authentication on that route needs a media token, which nothing tapping a
  3103. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3104. link only ever answered 401. The photo is then saved as a notification
  3105. photo as well (utils/notification_photos.py) and the link points there: an
  3106. unguessable name that opens this one photo and nothing else, for 3 days.
  3107. The link is relative when no External URL is set. Bytes over
  3108. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3109. ``(None, None)`` when the photo can't be found.
  3110. """
  3111. from backend.app.api.routes.settings import get_setting
  3112. from backend.app.core.auth import is_auth_enabled
  3113. from backend.app.utils.archive_paths import find_archive_photo
  3114. from backend.app.utils.notification_photos import save_notification_photo
  3115. log = logging.getLogger(__name__)
  3116. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3117. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3118. photo_bytes: bytes | None = None
  3119. try:
  3120. photo_path = find_archive_photo(archive, filename)
  3121. if photo_path is not None:
  3122. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3123. except Exception as e:
  3124. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3125. try:
  3126. auth_on = await is_auth_enabled(db)
  3127. except Exception:
  3128. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3129. if auth_on:
  3130. url = None
  3131. if photo_bytes:
  3132. try:
  3133. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3134. url = f"{base}/api/v1/notifications/photos/{name}"
  3135. except Exception as e:
  3136. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3137. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3138. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3139. return url, None
  3140. if photo_bytes:
  3141. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3142. return url, photo_bytes
  3143. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3144. """Capture a camera snapshot for notification image attachment.
  3145. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3146. Uses: external camera > buffered frame > fresh capture.
  3147. Turns the chamber light on for the picture when the printer asks for it
  3148. (#1655). ``light=False`` is for callers that capture all through a print,
  3149. where the light would flash with every frame.
  3150. """
  3151. if not printer:
  3152. return None
  3153. async with camera_light(printer if light else None):
  3154. return await _capture_snapshot_frame(printer_id, printer, logger)
  3155. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3156. """The capture behind ``_capture_snapshot_for_notification``."""
  3157. try:
  3158. from backend.app.api.routes.settings import get_setting
  3159. async with async_session() as db:
  3160. capture_enabled = await get_setting(db, "capture_finish_photo")
  3161. if capture_enabled is not None and capture_enabled.lower() != "true":
  3162. return None
  3163. # Try external camera first
  3164. if printer.external_camera_enabled and printer.external_camera_url:
  3165. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3166. from backend.app.api.routes.camera import live_frame_for_capture
  3167. from backend.app.services.external_camera import capture_frame
  3168. # An external camera allows one reader, so capturing while a viewer
  3169. # is attached fails (#2707). A None here falls through to the paths
  3170. # below exactly as a failed capture did.
  3171. defer, buffered = live_frame_for_capture(printer_id)
  3172. if defer:
  3173. frame_data = buffered
  3174. else:
  3175. frame_data = await capture_frame(
  3176. printer.external_camera_url,
  3177. printer.external_camera_type or "mjpeg",
  3178. snapshot_url=printer.external_camera_snapshot_url,
  3179. )
  3180. if frame_data and len(frame_data) <= 2_500_000:
  3181. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3182. return _apply_camera_rotation(frame_data, printer, logger)
  3183. # Try buffered frame from active stream
  3184. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3185. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3186. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3187. buffered_frame = get_buffered_frame(printer_id)
  3188. if (active_for_printer or active_chamber) and buffered_frame:
  3189. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3190. if len(buffered_frame) <= 2_500_000:
  3191. return _apply_camera_rotation(buffered_frame, printer, logger)
  3192. # Fresh capture from printer camera
  3193. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3194. from backend.app.services.camera import capture_camera_frame_bytes
  3195. frame_data = await capture_camera_frame_bytes(
  3196. printer.ip_address, printer.access_code, printer.model, timeout=15
  3197. )
  3198. if frame_data and len(frame_data) <= 2_500_000:
  3199. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3200. return _apply_camera_rotation(frame_data, printer, logger)
  3201. except Exception as e:
  3202. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3203. return None
  3204. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3205. """#1867: bank a recent in-print camera frame for the finish photo.
  3206. Called on every layer change and (#2547) on every print-progress advance.
  3207. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3208. path has a pre-End-G-code image for prints that end with a plate swap.
  3209. Both drivers are print telemetry that stops the instant printing ends: no
  3210. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3211. plate swap) executes. So the last banked frame is always the finished print,
  3212. never the swapped plate — that property is what the #1867 path relies on and
  3213. it must survive any change to the throttle below.
  3214. Layer changes alone were not enough: they stop when the *final* layer
  3215. begins, which on a three-minute last layer left the bank stale by the whole
  3216. length of that layer (#2547). Progress keeps ticking through it.
  3217. Best-effort: any failure just leaves the previous banked frame.
  3218. """
  3219. logger = logging.getLogger(__name__)
  3220. client = printer_manager.get_client(printer_id)
  3221. state = client.state if client else None
  3222. if not state or state.state != "RUNNING":
  3223. return
  3224. # Only during actual extrusion — firmware ticks layer_num during the
  3225. # pre-print calibration sequence, whose sub-stages are non-zero.
  3226. if state.mc_print_sub_stage not in (None, 0):
  3227. return
  3228. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3229. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3230. # now that progress advances also drive banking, that exemption would fire a
  3231. # camera grab on every percent tick of the last layer. Bambu printers accept
  3232. # one RTSP client at a time, so each grab contends with the live view.
  3233. now = time.monotonic()
  3234. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3235. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3236. return
  3237. total = state.total_layers or 0
  3238. try:
  3239. async with async_session() as db:
  3240. from backend.app.models.printer import Printer
  3241. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3242. printer = result.scalar_one_or_none()
  3243. if not printer:
  3244. return
  3245. # Reuses the notification snapshot path, which honours the
  3246. # `capture_finish_photo` setting (returns None when disabled) so we
  3247. # don't bank frames the user never asked for. Without the chamber light
  3248. # (#1655): this runs every 25 seconds for the whole print.
  3249. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3250. if frame:
  3251. _inprint_frame_bank[printer_id] = frame
  3252. _inprint_frame_bank_ts[printer_id] = now
  3253. logger.debug(
  3254. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3255. printer_id,
  3256. layer_num,
  3257. total,
  3258. len(frame),
  3259. )
  3260. except Exception as e:
  3261. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3262. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3263. """Apply camera rotation to snapshot image if configured."""
  3264. from backend.app.services.camera import apply_camera_rotation
  3265. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3266. async def _send_print_start_notification(
  3267. printer_id: int,
  3268. data: dict,
  3269. archive_data: dict | None = None,
  3270. logger=None,
  3271. ):
  3272. """Helper to send print start notification with optional archive data."""
  3273. if logger is None:
  3274. logger = logging.getLogger(__name__)
  3275. try:
  3276. async with async_session() as db:
  3277. from backend.app.models.printer import Printer
  3278. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3279. printer = result.scalar_one_or_none()
  3280. printer_name = printer.name if printer else f"Printer {printer_id}"
  3281. # Capture camera snapshot for notification image attachment
  3282. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3283. if image_data:
  3284. if archive_data is None:
  3285. archive_data = {}
  3286. archive_data["image_data"] = image_data
  3287. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3288. # Send user-specific email notification for print start
  3289. if archive_data and archive_data.get("created_by_id"):
  3290. await notification_service.send_user_print_email(
  3291. event_type="user_print_start",
  3292. created_by_id=archive_data["created_by_id"],
  3293. printer_name=printer_name,
  3294. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3295. db=db,
  3296. )
  3297. except Exception as e:
  3298. logger.warning("Notification on_print_start failed: %s", e)
  3299. async def _dispatch_user_print_email(
  3300. status: str,
  3301. created_by_id: int | None,
  3302. printer_name: str,
  3303. filename: str,
  3304. db,
  3305. image_data: bytes | None = None,
  3306. finish_photo_url: str | None = None,
  3307. ) -> None:
  3308. """Send a user-specific print-completion email based on print status.
  3309. Maps the normalised print status to the correct event type and delegates
  3310. to :meth:`NotificationService.send_user_print_email`. A single helper
  3311. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3312. "stopped"`` dispatch block at every call site.
  3313. Does nothing if *created_by_id* is ``None``.
  3314. """
  3315. if created_by_id is None:
  3316. return
  3317. if status == "completed":
  3318. event_type = "user_print_complete"
  3319. elif status == "failed":
  3320. event_type = "user_print_failed"
  3321. elif status in ("stopped", "aborted", "cancelled"):
  3322. event_type = "user_print_stopped"
  3323. else:
  3324. return
  3325. await notification_service.send_user_print_email(
  3326. event_type=event_type,
  3327. created_by_id=created_by_id,
  3328. printer_name=printer_name,
  3329. filename=filename,
  3330. db=db,
  3331. image_data=image_data,
  3332. finish_photo_url=finish_photo_url,
  3333. )
  3334. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3335. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3336. try:
  3337. from backend.app.services.archive import extract_printable_objects_from_archive
  3338. client = printer_manager.get_client(printer_id)
  3339. if not client:
  3340. return
  3341. # Extract with positions for UI overlay, scoped to the plate that
  3342. # is printing — resolve_plate_id is the same resolver /cover uses,
  3343. # so the object list can't disagree with the thumbnail it is drawn
  3344. # over (#2522).
  3345. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3346. app_settings.base_dir / archive.file_path,
  3347. plate_number=resolve_plate_id(client.state),
  3348. )
  3349. if printable_objects:
  3350. client.state.printable_objects = printable_objects
  3351. client.state.printable_objects_bbox_all = bbox_all
  3352. client.state.skipped_objects = []
  3353. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3354. except Exception as e:
  3355. logger.debug("Failed to extract printable objects from archive: %s", e)
  3356. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3357. """Put the skip-objects list back after a restart mid-print.
  3358. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3359. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3360. which the #1304 guard suppresses on the first RUNNING push after startup.
  3361. Everything else this hook restores (the archive, the usage-tracking session,
  3362. the timelapse baseline) was already handled; the object list was not, so a
  3363. restart mid-print took skip-objects away for the rest of that print.
  3364. Nothing recovered it either: the printer card gates its Skip button on the
  3365. object count, and the one endpoint that can rebuild the list is reachable
  3366. only from the modal that button opens.
  3367. Anchored on ``subtask_id``, which the firmware mints per print, so a
  3368. leftover ``status="printing"`` row from a completion we never saw cannot
  3369. hand this print someone else's objects. Without one, nothing is loaded
  3370. rather than guessed — the reload path on ``GET /print/objects`` covers that
  3371. case on demand.
  3372. """
  3373. client = printer_manager.get_client(printer_id)
  3374. if client is None or client.state.printable_objects:
  3375. return
  3376. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  3377. if subtask_id in ("", "0"):
  3378. return
  3379. from backend.app.models.archive import PrintArchive
  3380. archive = await db.scalar(
  3381. select(PrintArchive)
  3382. .where(
  3383. PrintArchive.printer_id == printer_id,
  3384. PrintArchive.status == "printing",
  3385. PrintArchive.subtask_id == subtask_id,
  3386. )
  3387. .order_by(PrintArchive.created_at.desc())
  3388. .limit(1)
  3389. )
  3390. if archive is not None:
  3391. _load_objects_from_archive(archive, printer_id, logger)
  3392. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3393. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3394. # past it; the second covers a handshake that failed again on the way back and
  3395. # armed a fresh one. Module-level so tests can shrink them.
  3396. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3397. # Retry ladder for the other temporary give-up: the file service answered and
  3398. # the transfer still did not finish, which at print start is usually the printer
  3399. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3400. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3401. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3402. # two cover a printer that stays busy well into the print.
  3403. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3404. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3405. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3406. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3407. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3408. # by view, so two views race), the cool-off retry task, and print completion.
  3409. # Without this they each read file_path == "" and each run a full copy, so the row
  3410. # ends up pointing at one timestamped directory while the others sit orphaned.
  3411. #
  3412. # Keyed by printer rather than archive because a printer runs one print at a time,
  3413. # which makes the two equally strong here — and it bounds the dict by printer
  3414. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3415. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3416. # resuming, so "no waiters" is not a question this API can answer.
  3417. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3418. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True) -> bool:
  3419. """Fill in a no-3MF archive from a 3MF that turned up later.
  3420. Returns True when the row was upgraded. Safe to call speculatively: it
  3421. verifies the archive still exists, is still a fallback, and that the file
  3422. is a readable 3MF before touching anything.
  3423. Serialised per printer — see ``_fallback_recovery_locks``.
  3424. """
  3425. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3426. async with lock:
  3427. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id, price=price)
  3428. async def _recover_fallback_archive_locked(
  3429. archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True
  3430. ) -> bool:
  3431. """The body of :func:`_recover_fallback_archive`, under its per-printer lock.
  3432. ``price`` is False when the print's end is being handled: the archive
  3433. still reads "printing" then, and its end prices it.
  3434. """
  3435. import zipfile
  3436. from backend.app.models.archive import PrintArchive
  3437. from backend.app.services.archive import ArchiveService
  3438. logger = logging.getLogger(__name__)
  3439. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3440. return False
  3441. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3442. # A truncated or half-written download is worse than no download: it
  3443. # would replace an honest empty archive with wrong metadata.
  3444. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3445. return False
  3446. async with async_session() as db:
  3447. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3448. if archive is None or archive.deleted_at is not None:
  3449. return False
  3450. if archive.file_path:
  3451. # Already recovered, or never was a fallback. Either way there is a
  3452. # real 3MF attached and overwriting it is not this function's job.
  3453. return False
  3454. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3455. service = ArchiveService(db)
  3456. recovered = await service.archive_print(
  3457. printer_id=printer_id,
  3458. source_file=source_3mf,
  3459. print_data={**print_data, "status": archive.status or "printing"},
  3460. subtask_id=archive.subtask_id,
  3461. update_archive_id=archive.id,
  3462. )
  3463. if recovered is None:
  3464. return False
  3465. logger.info(
  3466. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3467. archive_id,
  3468. source_3mf,
  3469. recovered.file_size,
  3470. )
  3471. if price and recovered.status == "printing":
  3472. # Print start priced it from the default rate, having no 3MF to
  3473. # estimate from; now it has one. An ended print is left alone: its
  3474. # end prices it. A print Bambuddy didn't dispatch has no start
  3475. # plate; the one the archive just read from the 3MF stands in.
  3476. _schedule_archive_cost_estimate(
  3477. printer_id,
  3478. recovered.id,
  3479. printer_manager,
  3480. ams_mapping=_get_start_ams_mapping(print_data, recovered.id),
  3481. plate_id=_get_start_plate_id(recovered.id) or recovered.plate_id,
  3482. session_factory=async_session,
  3483. )
  3484. # `archive_updated`, not `archive_created` — the row was already on the
  3485. # Archives page as an empty card and is now filled in, not new.
  3486. await ws_manager.send_archive_updated(
  3487. {
  3488. "id": recovered.id,
  3489. "printer_id": recovered.printer_id,
  3490. "filename": recovered.filename,
  3491. "print_name": recovered.print_name,
  3492. "status": recovered.status,
  3493. }
  3494. )
  3495. return True
  3496. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path, *, price: bool = True) -> bool:
  3497. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3498. Called from the paths that pull a 3MF for a print that is already under way
  3499. — chiefly the cover endpoint, which downloads the very file the archive flow
  3500. could not get and, before #2957, used it for a thumbnail and nothing else.
  3501. The bytes are already local, so this costs a parse and a row update.
  3502. No-op when the running print has a real archive, which is the common case.
  3503. """
  3504. from backend.app.models.archive import PrintArchive
  3505. logger = logging.getLogger(__name__)
  3506. # `_active_prints` is keyed on the raw names seen at print start — the
  3507. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3508. # Callers here arrive with whichever variant their own path produced, so
  3509. # match on the same normalization the download cache uses rather than on an
  3510. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3511. # endpoint find an archive registered under "Desktop_Goose".
  3512. wanted = normalize_3mf_name(name)
  3513. archive_id = None
  3514. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3515. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3516. archive_id = value
  3517. break
  3518. if archive_id is None:
  3519. return False
  3520. async with async_session() as db:
  3521. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3522. # Cheap pre-check so the common case (a normal archive) does no work.
  3523. if archive is None or archive.file_path or archive.deleted_at is not None:
  3524. return False
  3525. try:
  3526. return await _recover_fallback_archive(archive_id, path, printer_id, price=price)
  3527. except Exception as e:
  3528. # Recovery is opportunistic. A failure here must never take down the
  3529. # caller, which is usually just trying to render a thumbnail.
  3530. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3531. return False
  3532. def _schedule_fallback_3mf_retry(
  3533. printer_id: int,
  3534. archive_id: int,
  3535. filenames: list[str],
  3536. delays: tuple[float, ...] | None = None,
  3537. reason: str = REASON_FTPS_COOLOFF,
  3538. ) -> None:
  3539. """Re-attempt the 3MF download after a temporary give-up.
  3540. ``reason`` says which give-up this is, and picks the default ladder: an
  3541. FTPS cool-off has to be waited out, while a transfer that timed out under
  3542. contention is worth asking about again straight away (#3063). It is only
  3543. read for the ladder and the log line -- the retry itself is identical, since
  3544. in both cases the file is on the printer and the last attempt at it failed
  3545. for a reason that does not last.
  3546. """
  3547. logger = logging.getLogger(__name__)
  3548. if delays is None:
  3549. delays = (
  3550. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3551. if reason == REASON_FTP_TRANSFER_FAILED
  3552. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3553. )
  3554. async def _retry() -> None:
  3555. from backend.app.models.archive import PrintArchive
  3556. from backend.app.models.printer import Printer
  3557. for delay in delays:
  3558. await asyncio.sleep(delay)
  3559. async with async_session() as db:
  3560. archive = (
  3561. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3562. ).scalar_one_or_none()
  3563. if archive is None or archive.deleted_at is not None or archive.file_path:
  3564. return
  3565. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3566. if printer is None:
  3567. return
  3568. # Read the fields while the session is open rather than touching
  3569. # a detached instance minutes later, mid-download.
  3570. printer_ip = printer.ip_address
  3571. printer_code = printer.access_code
  3572. printer_model = printer.model
  3573. # Someone else may have fetched it in the meantime — the cover
  3574. # endpoint routinely does, and its copy is the same bytes.
  3575. for name in filenames:
  3576. cached = get_cached_3mf(printer_id, name)
  3577. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3578. return
  3579. if ftps_handshake_blocked(printer_ip):
  3580. logger.info(
  3581. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3582. printer_id,
  3583. archive_id,
  3584. )
  3585. continue
  3586. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3587. for candidate in filenames:
  3588. # Bare name only. These come from the print-start flow, which
  3589. # already strips the path, but the local temp write must not
  3590. # depend on that holding for every future caller — a name that
  3591. # is absolute or contains ".." would otherwise escape the data
  3592. # volume via the `/` operator.
  3593. name = Path(candidate).name
  3594. if not name or name in (".", ".."):
  3595. continue
  3596. if not name.endswith(".3mf"):
  3597. name = f"{name}.3mf"
  3598. temp_path = app_settings.archive_dir / "temp" / name
  3599. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3600. try:
  3601. hit = await download_file_try_paths_async(
  3602. printer_ip,
  3603. printer_code,
  3604. ftp_probe_paths(name),
  3605. temp_path,
  3606. socket_timeout=ftp_timeout,
  3607. printer_model=printer_model,
  3608. max_total_timeout=RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  3609. )
  3610. except Exception as e:
  3611. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3612. continue
  3613. if not hit:
  3614. continue
  3615. cache_3mf_download(printer_id, name, temp_path)
  3616. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3617. return
  3618. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3619. async def _guarded() -> None:
  3620. try:
  3621. await _retry()
  3622. except asyncio.CancelledError:
  3623. raise
  3624. except Exception as e:
  3625. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3626. finally:
  3627. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3628. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3629. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3630. if existing and not existing.done():
  3631. existing.cancel()
  3632. task = asyncio.create_task(_guarded())
  3633. _fallback_3mf_retry_tasks[printer_id] = task
  3634. logger.info(
  3635. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3636. archive_id,
  3637. reason,
  3638. printer_id,
  3639. ", ".join(f"{d:g}s" for d in delays),
  3640. )
  3641. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3642. """Whether an archive created here should ask for the print's outcome (#1898).
  3643. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3644. branches below: a queued job already has its archive and takes the
  3645. expected-print branch, where the queue item's own ``confirm_outcome``
  3646. decides. The queue is still consulted, because a restart mid-print empties
  3647. ``_expected_prints`` — without the check the setting could override a queue
  3648. item that deliberately has the flag off. Any failure answers "don't ask":
  3649. an unwanted prompt is worse than a missing one, and this must never be the
  3650. reason a print goes unarchived.
  3651. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3652. leaves one behind when a completion cannot be matched to it
  3653. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3654. only takes it back once the printer has sat connected and terminal for
  3655. minutes. Until then every screen-started print on that printer would
  3656. silently lose its prompt, so the row is held against ``observed_name`` by
  3657. the same comparison a completion uses: a positive disagreement means the row
  3658. is about some other run and this print is external after all.
  3659. """
  3660. logger = logging.getLogger(__name__)
  3661. try:
  3662. # A savepoint rather than a rollback of the caller's transaction on
  3663. # failure: a failed statement leaves the transaction unusable, but a
  3664. # full rollback also expires every object the caller has loaded (the
  3665. # printer, the archive it just created), and on an async session the
  3666. # next attribute read then raises instead of reloading. Everything here
  3667. # is a read, so undoing the savepoint loses nothing.
  3668. async with db.begin_nested():
  3669. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3670. except Exception as e:
  3671. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3672. return False
  3673. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3674. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3675. from backend.app.api.routes.settings import get_setting, setting_is_true
  3676. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3677. return False
  3678. from backend.app.models.print_queue import PrintQueueItem
  3679. dispatched_here = await db.scalar(
  3680. select(PrintQueueItem)
  3681. .where(
  3682. PrintQueueItem.printer_id == printer_id,
  3683. PrintQueueItem.status == "printing",
  3684. )
  3685. .limit(1)
  3686. )
  3687. if dispatched_here is None:
  3688. return True
  3689. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3690. observed = (observed_name or "").strip()
  3691. if not expected or not observed or _subtask_names_match(expected, observed):
  3692. logger.info(
  3693. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3694. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3695. printer_id,
  3696. dispatched_here.id,
  3697. )
  3698. return False
  3699. logger.info(
  3700. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3701. "%r; treating this as an externally started print.",
  3702. dispatched_here.id,
  3703. printer_id,
  3704. expected,
  3705. observed,
  3706. )
  3707. return True
  3708. async def _dispatch_outcome_confirmation_safely(
  3709. db,
  3710. printer_id: int,
  3711. printer_name: str,
  3712. data: dict,
  3713. archive_id: int,
  3714. archive_data: dict | None = None,
  3715. ) -> None:
  3716. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3717. The completion task sends the per-user print email on the same session
  3718. right after the prompt. A failed statement in the prompt leaves that
  3719. session needing a rollback, and without one the email step fails with
  3720. PendingRollbackError; the prompt is the optional part, so it must not be
  3721. the reason the email never goes out.
  3722. """
  3723. try:
  3724. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3725. except Exception as e:
  3726. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  3727. try:
  3728. await db.rollback()
  3729. except Exception:
  3730. pass
  3731. async def dispatch_outcome_confirmation(
  3732. db,
  3733. printer_id: int,
  3734. printer_name: str,
  3735. data: dict,
  3736. archive_id: int,
  3737. archive_data: dict | None = None,
  3738. ) -> bool:
  3739. """Emit the post-print outcome prompt for a completed archive (#1898).
  3740. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3741. queue item, or from ``confirm_outcome_external_prints`` for a print
  3742. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3743. question still open. Mints the per-archive capability token the one-tap
  3744. verdict links carry.
  3745. Lives here rather than inline in ``on_print_complete``'s notification task
  3746. because that task swallows every exception: extracted, the gate and the two
  3747. emissions can be driven by a test, which is the only thing standing between
  3748. a regression here and a farm that quietly stops asking.
  3749. Returns whether a prompt was sent.
  3750. """
  3751. logger = logging.getLogger(__name__)
  3752. from backend.app.models.archive import PrintArchive
  3753. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3754. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3755. return False
  3756. import secrets as _secrets
  3757. # A spent token stays on the row so the one-tap route can recognise it, so
  3758. # "has a token" no longer means "answerable". A prompt going out now needs a
  3759. # live one: mint a new token whenever the stored one is already spent, or
  3760. # every button in the new message would land on the already-answered page.
  3761. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  3762. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  3763. confirm_archive.confirm_token_used_at = None
  3764. await db.commit()
  3765. from backend.app.api.routes.settings import get_external_base_url, get_setting
  3766. base = await get_external_base_url(db)
  3767. if not await get_setting(db, "external_url"):
  3768. # Both the Telegram inline keyboard and the ntfy action buttons need an
  3769. # absolute URL, so an unconfigured install used to get a message body
  3770. # with two unusable relative paths and no buttons at all. The shared
  3771. # fallback at least produces tappable links; say which setting makes
  3772. # them resolve from a phone.
  3773. logger.warning(
  3774. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  3775. "Set Settings → External URL so they resolve away from this host.",
  3776. base,
  3777. )
  3778. token = confirm_archive.confirm_token
  3779. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  3780. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  3781. confirm_url = f"{base}/archives?confirm={archive_id}"
  3782. await ws_manager.send_print_confirm_request(
  3783. printer_id,
  3784. {
  3785. "archive_id": archive_id,
  3786. "print_name": confirm_archive.print_name or confirm_archive.filename,
  3787. },
  3788. )
  3789. await notification_service.on_print_confirm_request(
  3790. printer_id,
  3791. printer_name,
  3792. data,
  3793. db,
  3794. archive_data=archive_data,
  3795. good_url=good_url,
  3796. reject_url=reject_url,
  3797. confirm_url=confirm_url,
  3798. archive_id=archive_id,
  3799. )
  3800. return True
  3801. async def _printer_gone(db, printer_id: int) -> bool:
  3802. """Whether the printer was deleted. A column read: the session's loaded
  3803. Printer would otherwise answer for the database."""
  3804. from backend.app.models.printer import Printer
  3805. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  3806. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  3807. """Remove the archive just written if its printer was deleted meanwhile.
  3808. The delete route sweeps the printer's archives before it commits, so a row
  3809. committed after that sweep (the check before writing passed while the
  3810. delete was still uncommitted) is left for a printer that will never report
  3811. the print's end. A row the sweep reached is the route's: deleted with the
  3812. printer's archives, or detached (printer_id NULL) when the user kept them,
  3813. and then left as it is. Either way nothing is registered for it. Run after
  3814. the archive's commit, before anything is registered for it.
  3815. """
  3816. from backend.app.models.archive import PrintArchive
  3817. if not await _printer_gone(db, printer_id):
  3818. return False
  3819. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  3820. if owner == printer_id:
  3821. logging.getLogger(__name__).info(
  3822. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  3823. )
  3824. await ArchiveService(db).delete_archive(archive_id)
  3825. await forget_printer(printer_id)
  3826. return True
  3827. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  3828. """After an IntegrityError on a print start's archive write: whether it was
  3829. the printer being deleted, forgotten then (the caller returns).
  3830. PostgreSQL: the delete route locks the printer from its archive sweep to its
  3831. commit, so an archive written or adopted for it meanwhile (one that sets
  3832. printer_id) waits and the printer's foreign key then refuses it. That is
  3833. the printer being deleted, not an error; anything else is re-raised by the
  3834. caller.
  3835. """
  3836. await db.rollback()
  3837. if not await _printer_gone(db, printer_id):
  3838. return False
  3839. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  3840. await forget_printer(printer_id)
  3841. return True
  3842. async def _forget_if_printer_gone(printer_id: int) -> None:
  3843. """At the end of a print start: the slow steps after the last check (smart
  3844. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  3845. printer's delete and its forget_printer, and then wrote state back.
  3846. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  3847. SQLite; PostgreSQL refuses it.)
  3848. Its own session: those steps can leave the handler's needing a rollback (a
  3849. write to the archive the delete removed). Never raises: it runs inside the
  3850. fallback branch's try, whose except reports the archive as failed.
  3851. """
  3852. try:
  3853. async with async_session() as db:
  3854. gone = await _printer_gone(db, printer_id)
  3855. if gone:
  3856. await forget_printer(printer_id)
  3857. except Exception:
  3858. logging.getLogger(__name__).warning(
  3859. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  3860. )
  3861. async def _announce_plate_check_failed(printer_id: int, printer_name: str, reason: str) -> None:
  3862. """Tell the UI a plate check could not run. It does not block the print,
  3863. but an unchecked plate is not an empty one."""
  3864. try:
  3865. await ws_manager.broadcast(
  3866. {"type": "plate_check_failed", "printer_id": printer_id, "printer_name": printer_name, "reason": reason}
  3867. )
  3868. except Exception as e:
  3869. logging.getLogger(__name__).warning("[PLATE CHECK] Could not announce the failed check: %s", e)
  3870. def _expected_print_keys(printer_id: int, filename: str | None, subtask_name: str | None) -> list[tuple[int, str]]:
  3871. """The ``_expected_prints`` keys a print start may be registered under."""
  3872. keys: list[tuple[int, str]] = []
  3873. if subtask_name:
  3874. keys.append((printer_id, subtask_name))
  3875. keys.append((printer_id, f"{subtask_name}.3mf"))
  3876. keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3877. if filename:
  3878. fname = filename.split("/")[-1] if "/" in filename else filename
  3879. keys.append((printer_id, fname))
  3880. # Strip extensions to match
  3881. base = fname.replace(".gcode", "").replace(".3mf", "")
  3882. keys.append((printer_id, base))
  3883. keys.append((printer_id, f"{base}.3mf"))
  3884. return keys
  3885. async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, subtask_name: str | None) -> bool:
  3886. """Whether this print start is one Bambuddy sent to the printer."""
  3887. if any(key in _expected_prints for key in _expected_print_keys(printer_id, filename, subtask_name)):
  3888. return True
  3889. from backend.app.models.archive import PrintArchive
  3890. from backend.app.models.print_queue import PrintQueueItem
  3891. # The queue row the scheduler sets to printing before it sends -- but only
  3892. # when it was sent as this print: a row left printing by a run whose end
  3893. # was missed names another file.
  3894. dispatched_names = (
  3895. await db.execute(
  3896. select(PrintArchive.filename)
  3897. .join(PrintQueueItem, PrintQueueItem.archive_id == PrintArchive.id)
  3898. .where(PrintQueueItem.printer_id == printer_id, PrintQueueItem.status == "printing")
  3899. )
  3900. ).scalars()
  3901. observed = [name for name in (subtask_name, (filename or "").rsplit("/", 1)[-1]) if name]
  3902. return any(
  3903. _subtask_names_match(_subtask_name_from_filename(dispatched), _subtask_name_from_filename(seen))
  3904. for dispatched in dispatched_names
  3905. if dispatched
  3906. for seen in observed
  3907. )
  3908. async def on_print_start(printer_id: int, data: dict):
  3909. """Handle print start - archive the 3MF file immediately."""
  3910. logger = logging.getLogger(__name__)
  3911. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3912. try:
  3913. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  3914. except Exception:
  3915. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  3916. # Clear any stale user-stopped flag from previous print cycles
  3917. _user_stopped_printers.discard(printer_id)
  3918. _kill_switch_stopped.discard(printer_id)
  3919. # A new print starts its milestones from zero (#3211). The status path only
  3920. # resets on progress below 5 while not printing, which a printer that goes
  3921. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  3922. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  3923. # or on resume from pause, so it cannot repeat a milestone mid-print.
  3924. _last_progress_milestone[printer_id] = 0
  3925. _kill_switch_notification_tasks.pop(printer_id, None)
  3926. # #1721: drop any leftover pre-captured finish frame from a prior print
  3927. # so a never-consumed cache entry can't bleed into the new print's photo.
  3928. _stage22_finish_frames.pop(printer_id, None)
  3929. # #1867: same for the in-print frame bank — a queued print must not reuse
  3930. # the previous job's banked frame.
  3931. _inprint_frame_bank.pop(printer_id, None)
  3932. _inprint_frame_bank_ts.pop(printer_id, None)
  3933. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3934. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3935. # print's flag instead of inheriting it.
  3936. print_dispatch_context.adopt(printer_id)
  3937. # Cancel any active bed cooldown waiter for this printer
  3938. if _bed_cool_waiters.pop(printer_id, None):
  3939. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  3940. # Clear cached cover images so the new print's thumbnail is fetched fresh
  3941. from backend.app.api.routes.printers import clear_cover_cache
  3942. clear_cover_cache(printer_id)
  3943. await ws_manager.send_print_start(printer_id, data)
  3944. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  3945. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  3946. # MQTT relay - publish print start
  3947. try:
  3948. printer_info = printer_manager.get_printer(printer_id)
  3949. if printer_info:
  3950. await mqtt_relay.on_print_start(
  3951. printer_id,
  3952. printer_info.name,
  3953. printer_info.serial_number,
  3954. data.get("filename", ""),
  3955. data.get("subtask_name", ""),
  3956. )
  3957. except Exception:
  3958. pass # Don't fail print start callback if MQTT fails
  3959. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  3960. # and mapping, and the seeded tray-change log.
  3961. #
  3962. # Unconditional, for both inventory backends. This only *captures* — the
  3963. # writing is still split, with the internal tracker skipped at completion
  3964. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  3965. # carries its plate-scoped 3MF figures and stored mapping, but not the
  3966. # tray-change log, and that log is the only record of which spool fed
  3967. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  3968. # it on one side only would leave Spoolman users with the mid-print
  3969. # restart bug this fixes for everyone else.
  3970. try:
  3971. async with async_session() as db:
  3972. from backend.app.api.routes.settings import get_setting
  3973. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  3974. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3975. await usage_on_print_start(
  3976. printer_id,
  3977. data,
  3978. printer_manager,
  3979. db=db,
  3980. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  3981. )
  3982. except Exception as e:
  3983. logger.warning("Usage tracker on_print_start failed: %s", e)
  3984. # Track if notification was sent (to avoid sending twice)
  3985. notification_sent = False
  3986. # Smart plug automation: turn on plug when print starts
  3987. try:
  3988. async with async_session() as db:
  3989. await smart_plug_manager.on_print_start(printer_id, db)
  3990. except Exception as e:
  3991. logger.warning("Smart plug on_print_start failed: %s", e)
  3992. async with async_session() as db:
  3993. from backend.app.models.printer import Printer
  3994. from backend.app.services.bambu_ftp import list_files_async
  3995. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3996. printer = result.scalar_one_or_none()
  3997. # Plate detection check - pause if objects detected on build plate
  3998. logger.info(
  3999. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  4000. )
  4001. if printer and printer.plate_detection_enabled:
  4002. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  4003. # Release the pooled DB connection before the plate-detection camera
  4004. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  4005. # printer SELECT has run so far — nothing to persist — so this commit
  4006. # is a data-noop that ends the read transaction and returns the
  4007. # connection to the pool during the I/O (issue #2572). expire_on_commit
  4008. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  4009. # archive lookups below re-acquire a fresh connection on next execute.
  4010. await db.commit()
  4011. try:
  4012. from backend.app.services.plate_detection import check_plate_empty
  4013. # Build ROI tuple from printer settings if available
  4014. roi = None
  4015. if all(
  4016. [
  4017. printer.plate_detection_roi_x is not None,
  4018. printer.plate_detection_roi_y is not None,
  4019. printer.plate_detection_roi_w is not None,
  4020. printer.plate_detection_roi_h is not None,
  4021. ]
  4022. ):
  4023. roi = (
  4024. printer.plate_detection_roi_x,
  4025. printer.plate_detection_roi_y,
  4026. printer.plate_detection_roi_w,
  4027. printer.plate_detection_roi_h,
  4028. )
  4029. # Auto-turn on chamber light if it's off for better detection
  4030. light_was_off = False
  4031. client = printer_manager.get_client(printer_id)
  4032. if client and client.state:
  4033. light_was_off = not client.state.chamber_light
  4034. if light_was_off:
  4035. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  4036. client.set_chamber_light(True)
  4037. # Wait for light to physically turn on and camera to adjust exposure
  4038. await asyncio.sleep(2.5)
  4039. plate_photo_data = None
  4040. objects_detected = False
  4041. check_failure: str | None = None
  4042. try:
  4043. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  4044. plate_result = await check_plate_empty(
  4045. printer_id=printer_id,
  4046. ip_address=printer.ip_address,
  4047. access_code=printer.access_code,
  4048. model=printer.model,
  4049. include_debug_image=False,
  4050. external_camera_url=printer.external_camera_url,
  4051. external_camera_type=printer.external_camera_type,
  4052. use_external=printer.external_camera_enabled,
  4053. roi=roi,
  4054. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  4055. )
  4056. # No reference to compare against is a check that did not
  4057. # run either: say so rather than call the plate empty.
  4058. check_failure = getattr(plate_result, "failure_reason", None) or (
  4059. "not_calibrated" if plate_result.needs_calibration else None
  4060. )
  4061. objects_detected = not check_failure and not plate_result.is_empty
  4062. if objects_detected:
  4063. # Objects detected - pause the print!
  4064. logger.warning(
  4065. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  4066. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  4067. )
  4068. pause_client = printer_manager.get_client(printer_id)
  4069. if pause_client:
  4070. pause_client.pause_print()
  4071. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  4072. # Snapshot while the light's still on — restoring it first
  4073. # would leave the notification with a dark photo.
  4074. try:
  4075. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  4076. except Exception as snap_err:
  4077. logger.warning(
  4078. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  4079. )
  4080. finally:
  4081. # Restore chamber light to original state as soon as the
  4082. # camera is done with it, whatever happened above.
  4083. if light_was_off and client:
  4084. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  4085. try:
  4086. client.set_chamber_light(False)
  4087. except Exception as light_err:
  4088. logger.warning(
  4089. "[PLATE CHECK] Failed to restore chamber light for printer %s: %s",
  4090. printer_id,
  4091. light_err,
  4092. )
  4093. if objects_detected:
  4094. # Send notification about plate not empty
  4095. await ws_manager.broadcast(
  4096. {
  4097. "type": "plate_not_empty",
  4098. "printer_id": printer_id,
  4099. "printer_name": printer.name,
  4100. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  4101. }
  4102. )
  4103. # Also send push notification
  4104. try:
  4105. await notification_service.on_plate_not_empty(
  4106. printer_id=printer_id,
  4107. printer_name=printer.name,
  4108. db=db,
  4109. difference_percent=plate_result.difference_percent,
  4110. image_data=plate_photo_data,
  4111. )
  4112. except Exception as notif_err:
  4113. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4114. elif check_failure:
  4115. logger.warning(
  4116. "[PLATE CHECK] Plate check could not run for printer %s (%s): %s; proceeding with print",
  4117. printer_id,
  4118. check_failure,
  4119. plate_result.message,
  4120. )
  4121. await _announce_plate_check_failed(printer_id, printer.name, check_failure)
  4122. else:
  4123. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4124. except Exception as plate_err:
  4125. # Don't block print on plate detection errors
  4126. logger.warning(
  4127. "[PLATE CHECK] Plate check could not run for printer %s: %s; proceeding with print",
  4128. printer_id,
  4129. plate_err,
  4130. )
  4131. await _announce_plate_check_failed(printer_id, printer.name, "error")
  4132. if not printer:
  4133. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4134. if not notification_sent:
  4135. await _send_print_start_notification(printer_id, data, logger=logger)
  4136. return
  4137. # Skip the printer's own jobs — a calibration run is not a user's print.
  4138. # See is_internal_printer_job for what counts and why both fields are
  4139. # tested; the pressure-advance line reports as a subtask name with no
  4140. # /usr/ path, which the old prefix-only test here missed entirely.
  4141. #
  4142. # No notification either. The event describes the printer calibrating
  4143. # itself, so "Print started" is as wrong as the archive was, and the
  4144. # matching completion is suppressed in on_print_complete for the same
  4145. # reason. Checked before the auto-archive switches, whose "off" path
  4146. # still notifies.
  4147. # A /usr/ path is the printer's own file. A name alone is not proof: a
  4148. # print Bambuddy dispatched is never one, whatever it is called.
  4149. # Dispatched = an expected print, or, after a restart that lost those,
  4150. # a queue job printing on the printer.
  4151. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")) and (
  4152. (data.get("filename") or "").startswith("/usr/")
  4153. or not await _dispatched_by_bambuddy(db, printer_id, data.get("filename", ""), data.get("subtask_name", ""))
  4154. ):
  4155. logger.info(
  4156. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4157. data.get("filename", ""),
  4158. data.get("subtask_name", ""),
  4159. )
  4160. return
  4161. # The global switch is the master: off, no printer archives prints
  4162. # started outside Bambuddy; on, each printer's own switch decides.
  4163. from backend.app.api.routes.settings import get_setting
  4164. _global_auto_archive = await get_setting(db, "auto_archive")
  4165. archives_prints = printer.auto_archive and (
  4166. _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4167. )
  4168. if not archives_prints:
  4169. # auto-archive disabled — check if there's an expected print (dispatched
  4170. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4171. # If so, fall through to the expected-print handling below so the archive
  4172. # is tracked in _active_prints and usage tracking works at completion.
  4173. _fn = data.get("filename", "")
  4174. _sn = data.get("subtask_name", "")
  4175. _check_keys: list[tuple[int, str]] = []
  4176. if _sn:
  4177. _check_keys += [
  4178. (printer_id, _sn),
  4179. (printer_id, f"{_sn}.3mf"),
  4180. (printer_id, f"{_sn}.gcode.3mf"),
  4181. ]
  4182. if _fn:
  4183. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4184. _check_keys.append((printer_id, _base_fn))
  4185. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4186. _check_keys += [
  4187. (printer_id, _no_archive_base),
  4188. (printer_id, f"{_no_archive_base}.3mf"),
  4189. ]
  4190. _has_expected = any(k in _expected_prints for k in _check_keys)
  4191. if not _has_expected:
  4192. # No expected print — truly external print (started from slicer/touchscreen)
  4193. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4194. if not notification_sent:
  4195. _no_archive_creator: int | None = None
  4196. for _key in _check_keys:
  4197. _expected_prints.pop(_key, None)
  4198. _expected_print_registered_at.pop(_key, None)
  4199. popped_creator = _expected_print_creators.pop(_key, None)
  4200. if _no_archive_creator is None:
  4201. _no_archive_creator = popped_creator
  4202. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4203. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4204. return
  4205. else:
  4206. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4207. # Get the filename and subtask_name
  4208. filename = data.get("filename", "")
  4209. subtask_name = data.get("subtask_name", "")
  4210. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4211. # present, it lets us match an archive across a backend restart (#972):
  4212. # same id → same print → resume the existing row instead of cancelling
  4213. # it and recreating from scratch (which loses started_at). Treat "0"
  4214. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4215. raw_mqtt = data.get("raw_data") or {}
  4216. subtask_id = raw_mqtt.get("subtask_id")
  4217. if subtask_id is not None:
  4218. subtask_id = str(subtask_id).strip()
  4219. if subtask_id in ("", "0"):
  4220. subtask_id = None
  4221. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4222. if not filename and not subtask_name:
  4223. # Send notification without archive data (no filename)
  4224. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4225. if not notification_sent:
  4226. await _send_print_start_notification(printer_id, data, logger=logger)
  4227. return
  4228. # Check if this is an expected print from reprint/scheduled
  4229. expected_keys = _expected_print_keys(printer_id, filename, subtask_name)
  4230. expected_archive_id = None
  4231. for key in expected_keys:
  4232. expected_archive_id = _expected_prints.pop(key, None)
  4233. _expected_print_registered_at.pop(key, None)
  4234. if expected_archive_id:
  4235. # Clean up other possible keys for this print
  4236. for other_key in expected_keys:
  4237. _expected_prints.pop(other_key, None)
  4238. _expected_print_registered_at.pop(other_key, None)
  4239. break
  4240. if expected_archive_id:
  4241. # This is a reprint/scheduled print - use existing archive, don't create new one
  4242. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4243. # Bambuddy dispatched it: the kill switch's fast path keeps it as
  4244. # Bambuddy's once the expected entry is consumed here.
  4245. _owned_print_archive_ids.add(expected_archive_id)
  4246. from backend.app.models.archive import PrintArchive
  4247. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4248. archive = result.scalar_one_or_none()
  4249. # Deleted after this handler loaded it (the plate check waits
  4250. # seconds) but before the route forgot the expected print: the
  4251. # archive the route kept or deleted is left as the route left it.
  4252. if archive and await _printer_gone(db, printer_id):
  4253. logger.info(
  4254. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4255. )
  4256. await forget_printer(printer_id)
  4257. return
  4258. if archive:
  4259. # As it was before this adoption: put back if the printer turns
  4260. # out to have been deleted while it was adopted (below).
  4261. before_adoption = {
  4262. attr.columns[0].name: getattr(archive, attr.key)
  4263. for attr in sa_inspect(PrintArchive).column_attrs
  4264. if attr.key != "id"
  4265. }
  4266. # Update archive status to printing
  4267. archive.status = "printing"
  4268. archive.started_at = datetime.now(timezone.utc)
  4269. # The previous run's outcome is not this one's: a reprint that
  4270. # completes must not keep showing why the last one failed.
  4271. archive.failure_reason = None
  4272. archive.completed_at = None
  4273. # The previous run's answer is still on this row and the
  4274. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4275. # so without a reset the second run inherits the first run's
  4276. # verdict: no prompt at all, and a green "good" badge on a run
  4277. # nobody ever judged.
  4278. if archive.confirm_requested:
  4279. archive.user_verdict = None
  4280. archive.user_verdict_source = None
  4281. archive.user_verdict_at = None
  4282. archive.confirm_token = None
  4283. archive.confirm_token_used_at = None
  4284. # Reprint of an archive reuses the source row. Without resetting
  4285. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4286. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4287. # extracts the *original* print's last frame, which then ships in
  4288. # the completion notification (#1707). Clear the path so the
  4289. # scanner runs fresh; also unlink the old video file so reprints
  4290. # don't accumulate orphans in the archive directory. Photos list
  4291. # is left alone — accumulating one finish photo per run is fine.
  4292. # The print-start baseline (#2704) is stale for the same reason:
  4293. # it describes the printer before the previous run. The capture
  4294. # below overwrites it, but clear it here too so an early failure
  4295. # can't leave the scan diffing against the wrong snapshot.
  4296. #
  4297. # Unlinked only when it is the same plate printing again. Every
  4298. # plate of a Send All shares this archive, and the video on it
  4299. # can be the only copy of another plate's run -- the printer's
  4300. # was deleted once it attached (#3275). That one is left in the
  4301. # archive directory, which goes with the archive. A video whose
  4302. # plate is not on record (attached by hand, or before the
  4303. # column existed) is kept too where the 3MF has other plates,
  4304. # or cannot be read: nothing tells it apart from another plate's,
  4305. # and keeping costs one file where deleting can cost the only
  4306. # copy. On an archive with exactly one plate it is that plate's.
  4307. archive.timelapse_baseline = None
  4308. stale_timelapse_relpath = archive.timelapse_path
  4309. stale_timelapse_plate_id = archive.timelapse_plate_id
  4310. starting_plate_id = _print_plate_ids.get(expected_archive_id)
  4311. if stale_timelapse_relpath:
  4312. archive.timelapse_path = None
  4313. archive.timelapse_plate_id = None
  4314. stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
  4315. if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
  4316. from backend.app.services.archive import plate_indexes_in_3mf
  4317. plates = await asyncio.to_thread(
  4318. plate_indexes_in_3mf,
  4319. app_settings.base_dir / archive.file_path, # SEC-PATH-OK: stored relative archive path
  4320. )
  4321. stale_is_this_plates = len(plates) == 1
  4322. if stale_timelapse_relpath and not stale_is_this_plates:
  4323. logger.info(
  4324. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4325. stale_timelapse_relpath,
  4326. stale_timelapse_plate_id,
  4327. expected_archive_id,
  4328. starting_plate_id,
  4329. )
  4330. # The video is deleted once the adoption stands (below).
  4331. delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
  4332. # Persist a restart-stable id so a later restart resumes this
  4333. # archive by subtask_id instead of name-matching + duplicating
  4334. # it (#1485). The printer often hasn't echoed subtask_id back
  4335. # this soon after dispatch, so fall back to the id Bambuddy
  4336. # minted when it sent the print command. Scoped to this
  4337. # expected-print branch on purpose: an expected match means
  4338. # Bambuddy dispatched this exact print in this process, so the
  4339. # client's last-dispatch id genuinely belongs to it — using it
  4340. # for an externally-started print could mis-tag the archive.
  4341. effective_subtask_id = subtask_id
  4342. if not effective_subtask_id:
  4343. _client = printer_manager.get_client(printer_id)
  4344. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4345. if _dispatched:
  4346. effective_subtask_id = str(_dispatched).strip() or None
  4347. # Update on first-set OR on reprint (the queue dispatcher mints
  4348. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4349. # the rewrite for reprints leaves the archive holding the FIRST
  4350. # run's id; if MQTT then reconnects mid-print, the reconciler
  4351. # (#1542) compares the stale stored id against the printer's
  4352. # live id, sees a mismatch, and synthesises a bogus PRINT
  4353. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4354. # in #1807. Inequality check preserves the noop-on-stable-push
  4355. # behaviour the earlier `not archive.subtask_id` guard provided.
  4356. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4357. archive.subtask_id = effective_subtask_id
  4358. # #1403 follow-up: VP-queue archives are created with
  4359. # printer_id=None at queue-add time (we don't know which
  4360. # printer will run the job yet). When the print actually
  4361. # starts on a specific printer the expected-archive lookup
  4362. # used to skip this assignment, leaving printer_id=None
  4363. # forever — which then disables the "Scan for timelapse"
  4364. # button in ArchivesPage (gated on !archive.printer_id).
  4365. if archive.printer_id != printer_id:
  4366. archive.printer_id = printer_id
  4367. adopting_id = archive.id # a rollback expires the object
  4368. try:
  4369. await db.commit()
  4370. except (IntegrityError, StaleDataError):
  4371. # The archive stays unchanged, or is gone: "delete archives"
  4372. # removed the row under the adoption, which then matched no
  4373. # row (StaleDataError) rather than being refused.
  4374. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4375. return
  4376. raise
  4377. # The printer can be deleted between the check above and this
  4378. # commit (the route's transaction lasts seconds), and the commit
  4379. # then adopted the archive anyway: status, verdict and timelapse
  4380. # changed, and the deleted printer's id written on a row the
  4381. # route had detached or never touched. Undo the adoption.
  4382. if await _printer_gone(db, printer_id):
  4383. logger.info(
  4384. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4385. printer_id,
  4386. archive.id,
  4387. )
  4388. # Everything as before this adoption. The printer it had
  4389. # then stays, unless it was the deleted one: the route
  4390. # detached that row (kept) or deleted it (no row matches).
  4391. previous_printer = before_adoption["printer_id"]
  4392. await db.execute(
  4393. update(PrintArchive)
  4394. .where(PrintArchive.id == archive.id)
  4395. .values(
  4396. {
  4397. **before_adoption,
  4398. "printer_id": None if previous_printer == printer_id else previous_printer,
  4399. }
  4400. )
  4401. )
  4402. await db.commit()
  4403. await forget_printer(printer_id)
  4404. return
  4405. if delete_stale_video and stale_timelapse_relpath:
  4406. try:
  4407. stale_path = app_settings.base_dir / stale_timelapse_relpath
  4408. if stale_path.is_file():
  4409. stale_path.unlink()
  4410. logger.info(
  4411. "Deleted stale timelapse %s on reprint of archive %s",
  4412. stale_timelapse_relpath,
  4413. expected_archive_id,
  4414. )
  4415. except OSError as e:
  4416. logger.warning(
  4417. "Failed to delete stale timelapse %s on reprint: %s",
  4418. stale_timelapse_relpath,
  4419. e,
  4420. )
  4421. # Track as active print
  4422. _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
  4423. # Start timelapse session if external camera is enabled (#1353).
  4424. # Queue / VP-dispatched prints land here in the expected-archive
  4425. # branch and used to skip start_session entirely — frames were
  4426. # never captured and the post-print stitch silently returned None.
  4427. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4428. # Inject ams_mapping into usage tracker session — the session was created
  4429. # before expected-print promotion, so it may have ams_mapping=None when
  4430. # the MQTT request topic subscription failed (common on P1S/A1).
  4431. _stored_map = _print_ams_mappings.get(expected_archive_id)
  4432. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  4433. if _stored_map or _stored_plate_id is not None:
  4434. try:
  4435. from backend.app.services.usage_tracker import _active_sessions
  4436. _ut_session = _active_sessions.get(printer_id)
  4437. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4438. _ut_session.ams_mapping = _stored_map
  4439. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4440. # plate_id injection covers direct-Print of plate N of a multi-plate
  4441. # 3MF — queue prints already capture it via the on_print_start queue
  4442. # lookup, but direct-Print never goes through the queue (#1697).
  4443. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4444. _ut_session.plate_id = _stored_plate_id
  4445. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4446. except Exception:
  4447. pass
  4448. # Set up energy tracking (#941: persist start on archive row)
  4449. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4450. await ws_manager.send_archive_updated(
  4451. {
  4452. "id": archive.id,
  4453. "status": "printing",
  4454. }
  4455. )
  4456. # Send notification with archive data (reprint/scheduled)
  4457. if not notification_sent:
  4458. # Use archive's created_by_id; fall back to the creator registered via
  4459. # register_expected_print (handles library-file-based queue items where
  4460. # the freshly-created archive has no created_by_id yet).
  4461. # Pop ALL matching keys so no stale entries remain in the dict.
  4462. fallback_creator = None
  4463. for key in expected_keys:
  4464. popped = _expected_print_creators.pop(key, None)
  4465. if fallback_creator is None:
  4466. fallback_creator = popped
  4467. archive_data = {
  4468. "print_time_seconds": archive.print_time_seconds,
  4469. "created_by_id": archive.created_by_id or fallback_creator,
  4470. }
  4471. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4472. # Extract printable objects from the archived 3MF file
  4473. _load_objects_from_archive(archive, printer_id, logger)
  4474. # Store Spoolman tracking data for per-filament usage reporting
  4475. try:
  4476. await _store_spoolman_print_data(
  4477. printer_id,
  4478. archive.id,
  4479. archive.file_path,
  4480. db,
  4481. printer_manager,
  4482. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4483. plate_id=_get_start_plate_id(archive.id),
  4484. )
  4485. except Exception as e:
  4486. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4487. # Price the print from its spools now rather than only at completion (#3261)
  4488. _schedule_archive_cost_estimate(
  4489. printer_id,
  4490. archive.id,
  4491. printer_manager,
  4492. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4493. plate_id=_get_start_plate_id(archive.id),
  4494. session_factory=async_session,
  4495. )
  4496. # Capture timelapse file baseline for snapshot-diff on completion
  4497. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4498. # hit this branch — without the baseline the completion-time scan
  4499. # falls into its "take baseline now" fallback, which snapshots
  4500. # AFTER the new MP4 already exists and never matches a diff
  4501. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4502. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4503. await _forget_if_printer_gone(printer_id)
  4504. return # Skip creating a new archive
  4505. # The archive was deleted after the job was queued.
  4506. if not archives_prints:
  4507. # Only the expected print brought a printer that does not
  4508. # archive this far; with it gone, nothing is archived.
  4509. return
  4510. # Otherwise archive the print anew rather than drop it, so it still
  4511. # gets its notification, usage tracking and history.
  4512. logger.warning(
  4513. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4514. expected_archive_id,
  4515. printer_id,
  4516. )
  4517. # Check if there's already a "printing" archive for this printer/file
  4518. # This prevents duplicates when backend restarts during an active print
  4519. from backend.app.models.archive import PrintArchive
  4520. existing_archive: PrintArchive | None = None
  4521. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4522. # across a backend restart for the same print, so this is the most
  4523. # reliable way to reattach. Only a row still printing: a cancelled one
  4524. # has been through completion (usage, history, notifications) already,
  4525. # and reopening it would count the print twice.
  4526. if subtask_id:
  4527. by_id = await db.execute(
  4528. select(PrintArchive)
  4529. .where(PrintArchive.printer_id == printer_id)
  4530. .where(PrintArchive.subtask_id == subtask_id)
  4531. .where(PrintArchive.status == "printing")
  4532. .order_by(PrintArchive.created_at.desc())
  4533. .limit(1)
  4534. )
  4535. existing_archive = by_id.scalar_one_or_none()
  4536. # Fallback match: name-based lookup. Kept as-is for prints whose
  4537. # subtask_id is missing ("0" / local / non-cloud prints).
  4538. if existing_archive is None:
  4539. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4540. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4541. # A print started from the printer's screen names its file in full,
  4542. # so the forms above double its extension. The file itself is the
  4543. # one exact match, and nothing looser is added (#3009).
  4544. if _subtask_is_the_file(subtask_name, filename):
  4545. archive_filenames.append(subtask_name)
  4546. existing = await db.execute(
  4547. select(PrintArchive)
  4548. .where(PrintArchive.printer_id == printer_id)
  4549. .where(PrintArchive.status == "printing")
  4550. .where(
  4551. or_(
  4552. PrintArchive.print_name == check_name,
  4553. PrintArchive.filename.in_(archive_filenames),
  4554. )
  4555. )
  4556. .order_by(PrintArchive.created_at.desc())
  4557. .limit(1)
  4558. )
  4559. existing_archive = existing.scalar_one_or_none()
  4560. if existing_archive:
  4561. # subtask_id match → always resume, regardless of age. Same print,
  4562. # just a backend restart.
  4563. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4564. if subtask_match:
  4565. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4566. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4567. _mark_owned_if_dispatched(existing_archive)
  4568. if existing_archive.energy_start_kwh is None:
  4569. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4570. if not notification_sent:
  4571. archive_data = {
  4572. "print_time_seconds": existing_archive.print_time_seconds,
  4573. "created_by_id": existing_archive.created_by_id,
  4574. }
  4575. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4576. _load_objects_from_archive(existing_archive, printer_id, logger)
  4577. return
  4578. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4579. # stale from the printer's *current* progress, not wall-clock age.
  4580. # A genuinely long print used to trip a blind 4h cutoff and have its
  4581. # live archive cancelled + duplicated on every backend restart
  4582. # (#1485). If the printer reports real progress, this name-matched
  4583. # 'printing' archive IS that ongoing print — resume it whatever its
  4584. # age. Only treat it as a stale leftover when the printer clearly
  4585. # shows a different, freshly-started print: near-0% progress on an
  4586. # archive far too old to still be at 0%. Unknown progress (printer
  4587. # not connected) never cancels — resuming is the safe default.
  4588. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4589. live_status = printer_manager.get_status(printer_id)
  4590. live_progress = getattr(live_status, "progress", None) if live_status else None
  4591. looks_stale = (
  4592. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4593. )
  4594. # Two subtask ids are two prints, however young the archive: one
  4595. # whose completion was missed must not swallow the next print of
  4596. # the same file. Except Bambuddy's own reprint, which reuses the
  4597. # row and mints a fresh id (#1807): the id it last sent says so,
  4598. # and after a restart, which forgets it, this printer's queue job
  4599. # running the archive.
  4600. if (
  4601. not looks_stale
  4602. and subtask_id
  4603. and existing_archive.subtask_id
  4604. and existing_archive.subtask_id != subtask_id
  4605. ):
  4606. _client = printer_manager.get_client(printer_id)
  4607. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  4608. if _dispatched:
  4609. looks_stale = _dispatched != subtask_id
  4610. else:
  4611. from backend.app.models.print_queue import PrintQueueItem as _PQI
  4612. queue_run = await db.scalar(
  4613. select(_PQI.id)
  4614. .where(_PQI.archive_id == existing_archive.id)
  4615. .where(_PQI.printer_id == printer_id)
  4616. .where(_PQI.status == "printing")
  4617. .limit(1)
  4618. )
  4619. looks_stale = queue_run is None
  4620. if looks_stale:
  4621. logger.warning(
  4622. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  4623. " — marking cancelled and creating new archive",
  4624. existing_archive.id,
  4625. archive_age,
  4626. live_progress,
  4627. existing_archive.subtask_id,
  4628. subtask_id,
  4629. )
  4630. existing_archive.status = "cancelled"
  4631. # Canonical key, not a sentence (issue #2974). "No status update
  4632. # received" is what both stale paths actually observed; which of
  4633. # the two it was is already carried by ``status`` -- cancelled
  4634. # here, the reconciled outcome at the reconnect site -- so one
  4635. # key loses no information and gives the Statistics breakdown a
  4636. # single bucket instead of two untranslatable prose strings.
  4637. existing_archive.failure_reason = "noStatusUpdate"
  4638. await db.commit()
  4639. # Its print keys go with it; the new archive registers its own.
  4640. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id]:
  4641. del _active_prints[_key]
  4642. # Fall through to create new archive (don't return)
  4643. else:
  4644. logger.info(
  4645. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4646. )
  4647. # Track this as the active print
  4648. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4649. _mark_owned_if_dispatched(existing_archive)
  4650. # Attach subtask_id retroactively so future restarts can resume.
  4651. # Compare for inequality (not "is empty") to also pick up reprint
  4652. # dispatches that mint a fresh id — see #1807 for the bogus
  4653. # "Print Stopped" the strict-empty guard caused on reconnect.
  4654. if subtask_id and existing_archive.subtask_id != subtask_id:
  4655. existing_archive.subtask_id = subtask_id
  4656. await db.commit()
  4657. # Also set up energy tracking if not already tracked (#941: persisted column)
  4658. if existing_archive.energy_start_kwh is None:
  4659. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4660. # Send notification with archive data (existing archive)
  4661. if not notification_sent:
  4662. archive_data = {
  4663. "print_time_seconds": existing_archive.print_time_seconds,
  4664. "created_by_id": existing_archive.created_by_id,
  4665. }
  4666. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4667. # Extract printable objects from the archived 3MF file
  4668. _load_objects_from_archive(existing_archive, printer_id, logger)
  4669. return
  4670. # Build list of possible 3MF filenames to try
  4671. possible_names = []
  4672. # Bambu printers typically store files as "Name.gcode.3mf"
  4673. # The subtask_name is usually the best source for the filename
  4674. if subtask_name:
  4675. if _subtask_is_the_file(subtask_name, filename):
  4676. # A print started from the printer's own screen reports the
  4677. # file's full name, extension included. That is the file, so
  4678. # no extension is appended to it (#3009).
  4679. possible_names.append(subtask_name)
  4680. else:
  4681. # Try common Bambu naming patterns
  4682. possible_names.append(f"{subtask_name}.gcode.3mf")
  4683. possible_names.append(f"{subtask_name}.3mf")
  4684. # Try original filename with .3mf extension
  4685. if filename:
  4686. # Extract just the filename part, not the full path
  4687. fname = filename.split("/")[-1] if "/" in filename else filename
  4688. if fname.endswith(".3mf"):
  4689. possible_names.append(fname)
  4690. elif fname.endswith(".gcode"):
  4691. base = fname.rsplit(".", 1)[0]
  4692. possible_names.append(f"{base}.gcode.3mf")
  4693. possible_names.append(f"{base}.3mf")
  4694. else:
  4695. possible_names.append(f"{fname}.gcode.3mf")
  4696. possible_names.append(f"{fname}.3mf")
  4697. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4698. space_variants = []
  4699. for name in possible_names:
  4700. if " " in name:
  4701. space_variants.append(name.replace(" ", "_"))
  4702. possible_names.extend(space_variants)
  4703. # Remove duplicates while preserving order
  4704. seen = set()
  4705. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4706. logger.info("Trying filenames: %s", possible_names)
  4707. # Release the pooled DB connection before the 3MF FTP download. Reaching
  4708. # here means none of the expected-/existing-archive write branches ran
  4709. # (they all return earlier) — only SELECTs have executed on this path, so
  4710. # this commit persists nothing; it ends the read transaction so the
  4711. # connection returns to the pool during the download. That download tries
  4712. # up to five remote paths per candidate filename with retry/backoff and
  4713. # can run for minutes under FTP contention; holding the session across it
  4714. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  4715. # work runs during the download — the new-archive writes below re-acquire
  4716. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  4717. await db.commit()
  4718. # Try to find and download the 3MF file
  4719. temp_path = None
  4720. downloaded_filename = None
  4721. # Cache check: cover endpoint may have already pulled this 3MF during
  4722. # the print (frontend opens the card and shows the thumbnail) — reuse
  4723. # that file instead of re-downloading 36MB over the same FTP link that
  4724. # just served it (#972). The cache keys on a normalized filename so
  4725. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  4726. for try_filename in possible_names:
  4727. if not try_filename.endswith(".3mf"):
  4728. continue
  4729. cached = get_cached_3mf(printer_id, try_filename)
  4730. if cached:
  4731. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  4732. temp_path = cached
  4733. downloaded_filename = try_filename
  4734. break
  4735. # Does this printer keep the sliced file somewhere FTPS can reach? On
  4736. # H2-series and P2S the answer is routinely no — the file stays on
  4737. # internal eMMC and port 990 only ever serves external storage — and
  4738. # then the whole sweep below (six filenames x five directories x four
  4739. # retries, then the directory walk) is ~110 connections that cannot
  4740. # succeed. Skip it and say why (#2780).
  4741. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  4742. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  4743. # running rather than because the file is somewhere unreachable. The
  4744. # distinction is the whole of #2957: one is permanent, the other clears
  4745. # in minutes with the file still sitting on the printer.
  4746. blocked_by_ftps_cooloff = False
  4747. # Set when a probe reached the printer and still came back without the
  4748. # file -- a timeout mid-transfer, a refused connection, anything that is
  4749. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  4750. # caught by name below, so a file that genuinely is not on the card
  4751. # leaves this False and schedules nothing. Anything else means the
  4752. # transfer, not the file, is what failed, and that does not last (#3063).
  4753. ftp_transfer_failed = False
  4754. # The print's name, for a fallback archive whose `subtask_name` the
  4755. # plate guard below had to disown. Display only, and deliberately kept
  4756. # apart from `subtask_name`: that variable is what every file lookup
  4757. # here is built from, and once a name has been shown to fetch another
  4758. # plate's 3MF it must not key `_active_prints` either, or the cover
  4759. # endpoint hands the same contradicted file to
  4760. # `_recover_fallback_archive` and fills the row in with it (#3126).
  4761. display_name_after_plate_reject: str | None = None
  4762. # Get FTP retry settings
  4763. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  4764. # ...but "the printer put it on eMMC" is where it went, not whether we
  4765. # can read it. An H2D with a card in mirrors the job to /cache and
  4766. # serves it happily, and skipping on the URL alone cost that reporter
  4767. # every archive for two days (#2856). So ask the printer instead of
  4768. # guessing: the dispatch named the exact file, which is one connection
  4769. # walking five paths rather than the sweep's ~110. Only when the probe
  4770. # comes back empty does the verdict's reason stand.
  4771. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  4772. if ftps_handshake_blocked(printer.ip_address):
  4773. # Deliberately NOT recorded as a cool-off give-up. This branch
  4774. # only runs on an unreachable verdict, and that verdict is the
  4775. # honest, permanent reason the archive is empty — the probe was
  4776. # a long shot on top of it. Blaming the cool-off here would
  4777. # schedule a retry for a file sitting on internal eMMC, which is
  4778. # the sweep #2780 removed (#2957).
  4779. logger.debug(
  4780. "Not probing for %s on printer %s: its file service is not answering over TLS",
  4781. storage.probe_filename,
  4782. printer_id,
  4783. )
  4784. else:
  4785. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  4786. probe_path.parent.mkdir(parents=True, exist_ok=True)
  4787. try:
  4788. probe_hit = await download_file_try_paths_async(
  4789. printer.ip_address,
  4790. printer.access_code,
  4791. ftp_probe_paths(storage.probe_filename),
  4792. probe_path,
  4793. socket_timeout=ftp_timeout,
  4794. printer_model=printer.model,
  4795. )
  4796. except Exception as e:
  4797. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  4798. probe_hit = False
  4799. if probe_hit:
  4800. downloaded_filename = storage.probe_filename
  4801. temp_path = probe_path
  4802. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  4803. # Naming the path, not just the file: a printer that keeps
  4804. # uploads around for weeks can serve a same-named copy of an
  4805. # earlier slice, and without the directory in the log that
  4806. # mismatch is invisible rather than merely rare (#1820).
  4807. logger.info(
  4808. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  4809. downloaded_filename,
  4810. probe_hit,
  4811. printer_id,
  4812. storage.reason,
  4813. )
  4814. if not storage.reachable and not downloaded_filename:
  4815. # Same opening words whether or not a probe ran, because that is
  4816. # the phrase support asks people to grep for — only the tail says
  4817. # which of the two happened.
  4818. logger.info(
  4819. "Skipping the 3MF lookup for printer %s: %s — %s",
  4820. printer_id,
  4821. storage.reason,
  4822. "no copy of it on external storage either"
  4823. if storage.probe_filename
  4824. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  4825. )
  4826. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  4827. if not try_filename.endswith(".3mf"):
  4828. continue
  4829. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  4830. # printers, so try it first — deferring it to last cost #972's reporter
  4831. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  4832. # landing on the path that actually had the file.
  4833. remote_paths = [
  4834. f"/{try_filename}",
  4835. f"/cache/{try_filename}",
  4836. f"/model/{try_filename}",
  4837. f"/data/{try_filename}",
  4838. f"/data/Metadata/{try_filename}",
  4839. ]
  4840. temp_path = app_settings.archive_dir / "temp" / try_filename
  4841. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4842. for remote_path in remote_paths:
  4843. if ftps_handshake_blocked(printer.ip_address):
  4844. # The printer's FTPS service is not completing a TLS
  4845. # handshake, so it has no path we could reach — walking the
  4846. # remaining candidates only re-runs the same failure
  4847. # (#2780). Fall through to the no-3MF archive now.
  4848. #
  4849. # Remember *why*, though. This is the one give-up that is
  4850. # temporary: the cool-off clears in minutes and the file was
  4851. # on the printer the whole time. The fallback archive is
  4852. # stamped with it so a retry can be scheduled, and so the
  4853. # Archives banner stops blaming storage (#2957).
  4854. blocked_by_ftps_cooloff = True
  4855. logger.warning(
  4856. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  4857. printer_id,
  4858. )
  4859. break
  4860. logger.debug("Trying FTP download: %s", remote_path)
  4861. try:
  4862. if ftp_retry_enabled:
  4863. downloaded = await with_ftp_retry(
  4864. download_file_async,
  4865. printer.ip_address,
  4866. printer.access_code,
  4867. remote_path,
  4868. temp_path,
  4869. timeout=ftp_timeout,
  4870. socket_timeout=ftp_timeout,
  4871. printer_model=printer.model,
  4872. max_retries=ftp_retry_count,
  4873. retry_delay=ftp_retry_delay,
  4874. operation_name=f"Download 3MF from {remote_path}",
  4875. cooloff_ip=printer.ip_address,
  4876. non_retry_exceptions=(FileNotOnPrinterError,),
  4877. )
  4878. else:
  4879. downloaded = await download_file_async(
  4880. printer.ip_address,
  4881. printer.access_code,
  4882. remote_path,
  4883. temp_path,
  4884. timeout=ftp_timeout,
  4885. socket_timeout=ftp_timeout,
  4886. printer_model=printer.model,
  4887. )
  4888. if downloaded:
  4889. downloaded_filename = try_filename
  4890. logger.info("Downloaded: %s", remote_path)
  4891. # Populate shared cache so the cover endpoint (if it
  4892. # runs next) doesn't refetch the same 36MB over FTP.
  4893. cache_3mf_download(printer_id, try_filename, temp_path)
  4894. break
  4895. # with_ftp_retry returns None once it has spent its budget,
  4896. # and download_file_async returns False on a timeout, so an
  4897. # exhausted transfer arrives here rather than as an
  4898. # exception (#3063).
  4899. ftp_transfer_failed = True
  4900. except FileNotOnPrinterError:
  4901. # 550 — file isn't at this path. Advance to next candidate
  4902. # without burning the retry budget.
  4903. logger.debug("3MF not at %s (550), trying next path", remote_path)
  4904. except Exception as e:
  4905. ftp_transfer_failed = True
  4906. logger.debug("FTP download failed for %s: %s", remote_path, e)
  4907. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  4908. break
  4909. # If still not found, try listing directories to find matching file
  4910. # Different printer models use different directory structures. Skipped
  4911. # when the printer's FTPS handshake is failing — the directory walk is
  4912. # five more connections that cannot get further than the download did.
  4913. if (
  4914. not downloaded_filename
  4915. and storage.reachable
  4916. and (filename or subtask_name)
  4917. and not ftps_handshake_blocked(printer.ip_address)
  4918. ):
  4919. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  4920. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  4921. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  4922. # Every folder is listed before one file is picked, so a file named
  4923. # for the print in a later folder wins over one that merely
  4924. # contains the name in an earlier folder.
  4925. listed_paths: list[str] = []
  4926. for search_dir in search_dirs:
  4927. try:
  4928. dir_files = await list_files_async(
  4929. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  4930. )
  4931. except Exception as e:
  4932. logger.debug("Failed to list %s: %s", search_dir, e)
  4933. continue
  4934. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  4935. if threemf_files:
  4936. logger.info(
  4937. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  4938. )
  4939. listed_paths += [
  4940. posixpath.join(search_dir, f.get("name", "")) for f in dir_files if not f.get("is_directory")
  4941. ]
  4942. for remote_full_path in _3mf_files_for_print(listed_paths, search_term):
  4943. fname = posixpath.basename(remote_full_path)
  4944. logger.info("Found matching file: %s", remote_full_path)
  4945. temp_path = app_settings.archive_dir / "temp" / fname
  4946. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4947. try:
  4948. if ftp_retry_enabled:
  4949. downloaded = await with_ftp_retry(
  4950. download_file_async,
  4951. printer.ip_address,
  4952. printer.access_code,
  4953. remote_full_path,
  4954. temp_path,
  4955. timeout=ftp_timeout,
  4956. socket_timeout=ftp_timeout,
  4957. printer_model=printer.model,
  4958. max_retries=ftp_retry_count,
  4959. retry_delay=ftp_retry_delay,
  4960. operation_name=f"Download 3MF from {remote_full_path}",
  4961. cooloff_ip=printer.ip_address,
  4962. )
  4963. else:
  4964. downloaded = await download_file_async(
  4965. printer.ip_address,
  4966. printer.access_code,
  4967. remote_full_path,
  4968. temp_path,
  4969. timeout=ftp_timeout,
  4970. socket_timeout=ftp_timeout,
  4971. printer_model=printer.model,
  4972. )
  4973. except Exception as e:
  4974. logger.debug("Failed to download %s: %s", remote_full_path, e)
  4975. continue
  4976. if downloaded:
  4977. downloaded_filename = fname
  4978. logger.info("Found and downloaded: %s", remote_full_path)
  4979. cache_3mf_download(printer_id, fname, temp_path)
  4980. break
  4981. # The listing named the file, so it is on the card;
  4982. # only the transfer failed (#3063).
  4983. ftp_transfer_failed = True
  4984. # Validate the downloaded 3MF actually matches the plate that's running
  4985. # (#1204): subtask_name lags across consecutive plates of the same model,
  4986. # so the first FTP candidate (built from subtask_name) can land on the
  4987. # previous plate's still-resident upload. Cross-check the slice_info
  4988. # plate index against the plate parsed from gcode_file (always fresh —
  4989. # it's the field whose change triggered this callback).
  4990. if downloaded_filename and temp_path:
  4991. expected_plate = parse_plate_id(filename)
  4992. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  4993. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  4994. logger.warning(
  4995. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  4996. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  4997. downloaded_filename,
  4998. actual_plate,
  4999. expected_plate,
  5000. subtask_name,
  5001. )
  5002. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  5003. retry_succeeded = False
  5004. if corrected_subtask and corrected_subtask != subtask_name:
  5005. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  5006. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  5007. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  5008. for remote_path in (
  5009. f"/{try_filename}",
  5010. f"/cache/{try_filename}",
  5011. f"/model/{try_filename}",
  5012. f"/data/{try_filename}",
  5013. f"/data/Metadata/{try_filename}",
  5014. ):
  5015. try:
  5016. if ftp_retry_enabled:
  5017. downloaded = await with_ftp_retry(
  5018. download_file_async,
  5019. printer.ip_address,
  5020. printer.access_code,
  5021. remote_path,
  5022. retry_temp_path,
  5023. timeout=ftp_timeout,
  5024. socket_timeout=ftp_timeout,
  5025. printer_model=printer.model,
  5026. max_retries=ftp_retry_count,
  5027. retry_delay=ftp_retry_delay,
  5028. operation_name=f"Re-download 3MF from {remote_path}",
  5029. cooloff_ip=printer.ip_address,
  5030. non_retry_exceptions=(FileNotOnPrinterError,),
  5031. )
  5032. else:
  5033. downloaded = await download_file_async(
  5034. printer.ip_address,
  5035. printer.access_code,
  5036. remote_path,
  5037. retry_temp_path,
  5038. timeout=ftp_timeout,
  5039. socket_timeout=ftp_timeout,
  5040. printer_model=printer.model,
  5041. )
  5042. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  5043. logger.info(
  5044. "[CALLBACK] Re-download succeeded with corrected name %s "
  5045. "(plate %s) — replacing wrong file",
  5046. try_filename,
  5047. expected_plate,
  5048. )
  5049. try:
  5050. temp_path.unlink(missing_ok=True)
  5051. except OSError:
  5052. pass
  5053. temp_path = retry_temp_path
  5054. downloaded_filename = try_filename
  5055. subtask_name = corrected_subtask
  5056. cache_3mf_download(printer_id, try_filename, temp_path)
  5057. retry_succeeded = True
  5058. break
  5059. elif downloaded:
  5060. # Wrong plate again — discard and keep trying
  5061. try:
  5062. retry_temp_path.unlink(missing_ok=True)
  5063. except OSError:
  5064. pass
  5065. except FileNotOnPrinterError:
  5066. continue
  5067. except Exception as e:
  5068. logger.debug("Re-download failed for %s: %s", remote_path, e)
  5069. if retry_succeeded:
  5070. break
  5071. # If the retry didn't find a matching file, drop the wrong 3MF
  5072. # so the no-3MF fallback below creates an archive whose name
  5073. # at least reflects the right plate.
  5074. if not retry_succeeded:
  5075. logger.warning(
  5076. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  5077. expected_plate,
  5078. )
  5079. try:
  5080. temp_path.unlink(missing_ok=True)
  5081. except OSError:
  5082. pass
  5083. temp_path = None
  5084. downloaded_filename = None
  5085. # Whatever the sweep's transport did earlier, it is not why
  5086. # this archive ends up empty: a 3MF downloaded fine, it was
  5087. # just the wrong plate. Retrying would re-fetch that same
  5088. # contradicted file under the same stale names and hand it
  5089. # to _recover_fallback_archive, which checks that a
  5090. # candidate is a readable 3MF but not which plate it is --
  5091. # so the row would be filled in with another plate's
  5092. # filament and cost, the exact swap #2957 removed (#3063).
  5093. ftp_transfer_failed = False
  5094. # Disown the name for *lookups*: it has just been shown to
  5095. # fetch another plate's 3MF, and it keys `_active_prints`
  5096. # below, where the cover endpoint's own download of that
  5097. # same name would find this archive and fill it in with the
  5098. # file we are discarding here.
  5099. #
  5100. # Keep it for the *title*, which is a separate question.
  5101. # ``swap_plate_suffix`` returns None both for a name that
  5102. # carries no "- Plate N" / "_plate_N" suffix and for no
  5103. # name at all, and those are not the same situation: a name
  5104. # without a suffix holds no stale plate number to be wrong
  5105. # about. Blanking both uses at once dropped the project
  5106. # name too, and the row fell through to the gcode_file path
  5107. # titled "plate_1" though the real name was in hand.
  5108. # #1204's own premise is consecutive plates *of the same
  5109. # model*, so the project part is right either way (#3126).
  5110. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  5111. subtask_name = corrected_subtask or ""
  5112. # Deleted while the 3MF was being fetched (that can take minutes): no
  5113. # archive, timelapse or tracking for a printer that will never report
  5114. # the print's end. forget_printer again: the download registered its
  5115. # 3MF cache entry after the delete cleared the id. (A delete committing
  5116. # while the archive is written is caught after its commit.)
  5117. if await _printer_gone(db, printer_id):
  5118. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  5119. await forget_printer(printer_id)
  5120. return
  5121. if not downloaded_filename or not temp_path:
  5122. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  5123. # Create a fallback archive without 3MF data so the print is still tracked
  5124. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  5125. try:
  5126. from backend.app.models.archive import PrintArchive
  5127. # Why the card is empty. The two temporary causes outrank the
  5128. # storage verdict because they say the sweep never got a fair
  5129. # answer: a cool-off skipped it at the transport, and a failed
  5130. # transfer reached the printer but never finished. Either way
  5131. # the file is still on the card, so reporting where the printer
  5132. # files its jobs would describe a setting that is not the
  5133. # problem (#2957, #3063).
  5134. if blocked_by_ftps_cooloff:
  5135. no_3mf_reason = REASON_FTPS_COOLOFF
  5136. elif storage.reachable and ftp_transfer_failed:
  5137. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5138. else:
  5139. no_3mf_reason = storage.reason
  5140. # Derive print name from subtask_name or filename. The
  5141. # plate guard's disowned name comes second: it is a real name
  5142. # for a real print, and only the gcode_file path is left
  5143. # otherwise -- which titles the row "plate_1" (#3126).
  5144. print_name = subtask_name or display_name_after_plate_reject or filename
  5145. if print_name:
  5146. # Clean up the name (remove extensions, path parts)
  5147. print_name = print_name.split("/")[-1]
  5148. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5149. else:
  5150. print_name = "Unknown Print"
  5151. # Recover estimated print time from MQTT (best-effort for notifications)
  5152. fallback_print_time = None
  5153. mqtt_remaining = data.get("remaining_time")
  5154. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5155. fallback_print_time = int(mqtt_remaining)
  5156. if fallback_print_time is None:
  5157. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5158. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5159. fallback_print_time = int(mc_remaining * 60)
  5160. # Best-effort filament metadata from MQTT — see
  5161. # _extract_filament_data_from_mqtt. Without this the fallback
  5162. # archive's filament fields stayed NULL even though the AMS
  5163. # state at print start was sitting right there in `data`.
  5164. # The slicer's ams_mapping (when present) narrows the result
  5165. # to slots actually used by the print (#1533).
  5166. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  5167. # Create minimal archive entry
  5168. fallback_archive = PrintArchive(
  5169. printer_id=printer_id,
  5170. filename=filename or f"{print_name}.3mf",
  5171. file_path="", # Empty - no 3MF file available
  5172. file_size=0,
  5173. print_name=print_name,
  5174. print_time_seconds=fallback_print_time,
  5175. status="printing",
  5176. started_at=datetime.now(timezone.utc),
  5177. subtask_id=subtask_id,
  5178. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5179. filament_type=mqtt_filament_meta.get("filament_type"),
  5180. filament_color=mqtt_filament_meta.get("filament_color"),
  5181. extra_data={
  5182. "no_3mf_available": True,
  5183. # Why the card is empty, when we know -- see above. The
  5184. # banner reads this to stop telling H2/P2 owners to
  5185. # switch on a setting that is already on and would not
  5186. # have helped (#2780).
  5187. "no_3mf_reason": no_3mf_reason,
  5188. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5189. "_print_data": data,
  5190. },
  5191. )
  5192. db.add(fallback_archive)
  5193. try:
  5194. await db.commit()
  5195. except IntegrityError:
  5196. # Not "Failed to create fallback archive" below, and no
  5197. # start notification for a printer that is gone.
  5198. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5199. return
  5200. raise
  5201. await db.refresh(fallback_archive)
  5202. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5203. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5204. return
  5205. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5206. # Track as active print
  5207. _bind_active_print(printer_id, fallback_archive.id, fallback_archive.filename, filename, subtask_name)
  5208. # Record starting energy if smart plug available (#941: persisted column)
  5209. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5210. # Send WebSocket notification
  5211. await ws_manager.send_archive_created(
  5212. {
  5213. "id": fallback_archive.id,
  5214. "printer_id": fallback_archive.printer_id,
  5215. "filename": fallback_archive.filename,
  5216. "print_name": fallback_archive.print_name,
  5217. "status": fallback_archive.status,
  5218. }
  5219. )
  5220. # MQTT relay - publish archive created
  5221. try:
  5222. await mqtt_relay.on_archive_created(
  5223. archive_id=fallback_archive.id,
  5224. print_name=fallback_archive.print_name,
  5225. printer_name=printer.name,
  5226. status=fallback_archive.status,
  5227. )
  5228. except Exception:
  5229. pass # Don't fail if MQTT fails
  5230. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5231. try:
  5232. await _store_spoolman_print_data(
  5233. printer_id,
  5234. fallback_archive.id,
  5235. fallback_archive.file_path,
  5236. db,
  5237. printer_manager,
  5238. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  5239. plate_id=_get_start_plate_id(fallback_archive.id),
  5240. )
  5241. except Exception as e:
  5242. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5243. # Both temporary give-ups are worth coming back for, and for
  5244. # the same reason: the file is on the printer and the last look
  5245. # failed at the transport rather than finding nothing. One waits
  5246. # out the handshake block (#2957), the other waits for the
  5247. # printer to stop being busy (#3063). Deliberately not scheduled
  5248. # for a storage verdict: a file on internal eMMC will not appear
  5249. # at any FTPS path however long we wait, and retrying it is
  5250. # exactly the sweep #2780 removed.
  5251. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5252. # `possible_names`, not the raw MQTT strings: it is the exact
  5253. # list this flow just tried, already stripped of any path
  5254. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5255. # some firmware) and deduped.
  5256. _schedule_fallback_3mf_retry(
  5257. printer_id=printer_id,
  5258. archive_id=fallback_archive.id,
  5259. filenames=list(possible_names),
  5260. reason=no_3mf_reason,
  5261. )
  5262. # Send notification without archive data (file not found)
  5263. if not notification_sent:
  5264. await _send_print_start_notification(printer_id, data, logger=logger)
  5265. # The same baseline the other two on_print_start branches take
  5266. # (#2704), and last for the same reason they are: it lists the
  5267. # printer's timelapse directory, so a slow card must not delay
  5268. # the _active_prints registration, the energy reading, the
  5269. # archive-created event or the start notification above it.
  5270. #
  5271. # This branch never took one, so every no-3MF archive reached
  5272. # completion with no baseline in memory and none on the row, and
  5273. # the completion scan fell into its "snapshot now" fallback --
  5274. # which runs after the printer has written the video, so the new
  5275. # file landed inside the baseline and no diff ever matched
  5276. # (#2957 follow-up).
  5277. #
  5278. # Skipped when the FTPS cool-off is what produced this fallback:
  5279. # the listing needs the same connection that just failed, so it
  5280. # could only record that the card was unreadable. The scan
  5281. # handles that case by refusing to choose between candidates.
  5282. if not blocked_by_ftps_cooloff:
  5283. await _capture_timelapse_baseline_at_start(
  5284. printer, printer_id, logger, archive_id=fallback_archive.id
  5285. )
  5286. await _forget_if_printer_gone(printer_id)
  5287. return
  5288. except Exception as e:
  5289. logger.error("Failed to create fallback archive: %s", e)
  5290. # Send notification without archive data (file not found)
  5291. if not notification_sent:
  5292. await _send_print_start_notification(printer_id, data, logger=logger)
  5293. return
  5294. try:
  5295. # Archive the file with status "printing"
  5296. service = ArchiveService(db)
  5297. try:
  5298. archive = await service.archive_print(
  5299. printer_id=printer_id,
  5300. source_file=temp_path,
  5301. print_data={**data, "status": "printing"},
  5302. subtask_id=subtask_id,
  5303. )
  5304. except IntegrityError:
  5305. # archive_print removed the folder it had copied the 3MF into.
  5306. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5307. return
  5308. raise
  5309. if archive:
  5310. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5311. # Set on the row rather than passed to archive_print, which also
  5312. # serves the queue dispatcher — there the queue item decides.
  5313. # Guarded because this branch has no ``except``: an unhandled
  5314. # write error would take the _active_prints registration, the
  5315. # start notification, the energy reading and the timelapse
  5316. # baseline below it with it, and a missing prompt is by far the
  5317. # cheaper failure.
  5318. archive_id = archive.id
  5319. try:
  5320. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5321. archive.confirm_requested = True
  5322. await db.commit()
  5323. except Exception as e:
  5324. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5325. # The rollback expires every loaded object, and on an async
  5326. # session reading one afterwards raises instead of
  5327. # reloading, so the two this branch goes on to use are
  5328. # fetched again. The archive itself was committed by
  5329. # archive_print; only the flag is lost.
  5330. try:
  5331. await db.rollback()
  5332. archive = await db.get(PrintArchive, archive_id)
  5333. printer = await db.get(Printer, printer_id)
  5334. except Exception as reload_error:
  5335. logger.warning(
  5336. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5337. )
  5338. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5339. return
  5340. # Track this active print (use both original filename and downloaded filename)
  5341. _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
  5342. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5343. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5344. # Record starting energy from smart plug if available (#941: persisted column)
  5345. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5346. await ws_manager.send_archive_created(
  5347. {
  5348. "id": archive.id,
  5349. "printer_id": archive.printer_id,
  5350. "filename": archive.filename,
  5351. "print_name": archive.print_name,
  5352. "status": archive.status,
  5353. }
  5354. )
  5355. # MQTT relay - publish archive created
  5356. try:
  5357. await mqtt_relay.on_archive_created(
  5358. archive_id=archive.id,
  5359. print_name=archive.print_name,
  5360. printer_name=printer.name,
  5361. status=archive.status,
  5362. )
  5363. except Exception:
  5364. pass # Don't fail if MQTT fails
  5365. # Send notification with archive data (new archive created)
  5366. if not notification_sent:
  5367. archive_data = {
  5368. "print_time_seconds": archive.print_time_seconds,
  5369. "created_by_id": archive.created_by_id,
  5370. }
  5371. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5372. # Extract printable objects for skip object functionality
  5373. try:
  5374. from backend.app.services.archive import extract_printable_objects_from_3mf
  5375. client = printer_manager.get_client(printer_id)
  5376. if client:
  5377. with open(temp_path, "rb") as f:
  5378. threemf_data = f.read()
  5379. # Extract with positions for UI overlay, scoped to the
  5380. # plate that is printing — an all-plates 3MF carries
  5381. # every plate's objects (#2522).
  5382. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5383. threemf_data,
  5384. plate_number=resolve_plate_id(client.state),
  5385. include_positions=True,
  5386. )
  5387. if printable_objects:
  5388. # Store objects in printer state
  5389. client.state.printable_objects = printable_objects
  5390. client.state.printable_objects_bbox_all = bbox_all
  5391. client.state.skipped_objects = [] # Reset skipped objects for new print
  5392. logger.info(
  5393. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5394. )
  5395. except Exception as e:
  5396. logger.debug("Failed to extract printable objects: %s", e)
  5397. # Store Spoolman tracking data for per-filament usage reporting
  5398. try:
  5399. await _store_spoolman_print_data(
  5400. printer_id,
  5401. archive.id,
  5402. archive.file_path,
  5403. db,
  5404. printer_manager,
  5405. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5406. plate_id=_get_start_plate_id(archive.id),
  5407. )
  5408. except Exception as e:
  5409. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5410. # Price the print from its spools now rather than only at completion (#3261)
  5411. _schedule_archive_cost_estimate(
  5412. printer_id,
  5413. archive.id,
  5414. printer_manager,
  5415. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5416. plate_id=_get_start_plate_id(archive.id),
  5417. session_factory=async_session,
  5418. )
  5419. # Capture timelapse file baseline for snapshot-diff on completion
  5420. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5421. await _forget_if_printer_gone(printer_id)
  5422. finally:
  5423. # Keep temp_path around until print completes so the cover endpoint
  5424. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5425. # the file. If the cache entry was evicted early (file vanished),
  5426. # clean up any stragglers here to avoid leaking disk on retries.
  5427. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5428. if temp_path and temp_path.exists() and cached_now != temp_path:
  5429. temp_path.unlink()
  5430. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5431. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5432. # tests can shrink them without waiting out real delays.
  5433. #
  5434. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  5435. # looking. Across 247 support bundles the attempt that found the video was #1
  5436. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  5437. # decaying one, which is the signature of a budget that expires while files are
  5438. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  5439. # prints make big videos and the printer writes them after the print ends, so
  5440. # the poll now runs for minutes and costs one FTP LIST per round.
  5441. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  5442. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  5443. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  5444. def _timelapse_scan_max_attempts() -> int:
  5445. """Round cap for the poll, derived from the wall-clock budget.
  5446. The deadline alone is not a sufficient bound: it assumes each round really
  5447. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5448. and an FTP list that fails immediately would otherwise spin against the
  5449. printer at full speed for the whole window. Whichever bound is reached
  5450. first ends the poll.
  5451. """
  5452. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5453. # A zero interval makes the wall-clock budget meaningless; fall back to
  5454. # the round count the production interval would have given.
  5455. return 32
  5456. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5457. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  5458. """Video filenames already attached to some other archive of this printer.
  5459. Used to disambiguate when more than one file is new since the baseline —
  5460. which happens when a previous print's video landed after this print's
  5461. baseline was taken. Ordering the candidates would be the obvious fix and is
  5462. the wrong one: it can only be done on mtime or on the filename timestamp,
  5463. both of which come from the printer's own clock, and a LAN-only printer
  5464. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  5465. ``attach_timelapse`` saves the video into the archive directory under the
  5466. printer's original filename, and the later MP4 conversion keeps the stem,
  5467. so the stem of ``timelapse_path`` recovers what was claimed.
  5468. """
  5469. from backend.app.models.archive import PrintArchive
  5470. rows = await db.execute(
  5471. select(PrintArchive.timelapse_path).where(
  5472. PrintArchive.printer_id == printer_id,
  5473. PrintArchive.id != exclude_archive_id,
  5474. PrintArchive.timelapse_path.is_not(None),
  5475. )
  5476. )
  5477. return {Path(p).stem for p in rows.scalars().all() if p}
  5478. def _timelapse_listing_is_trustworthy(printer) -> bool:
  5479. """Whether an *empty* timelapse listing for *printer* can be believed.
  5480. ``list_files_async`` answers ``[]`` when its connect fails rather than
  5481. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  5482. from one holding no videos. Everywhere that only wants to know "is there a
  5483. video yet" the difference does not matter — both mean "not yet, retry".
  5484. It matters where an empty listing is recorded as a *baseline*. Recording
  5485. "the card held nothing" for a card that was never read means every video on
  5486. it counts as new once the cool-off expires, and the completion scan then
  5487. attaches a stale video to this print and deletes it from the printer
  5488. (#2957 follow-up). Those two callers ask this first.
  5489. """
  5490. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  5491. ip_address = getattr(printer, "ip_address", None)
  5492. if not ip_address:
  5493. return True
  5494. return not ftps_handshake_blocked(ip_address)
  5495. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5496. """List video files from printer's timelapse directory.
  5497. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5498. Returns (video_files, found_path) where video_files is a list of file dicts
  5499. and found_path is the directory where they were found, or ([], None).
  5500. An empty return does not distinguish "no videos" from "could not read the
  5501. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  5502. baseline callers consult before believing one.
  5503. """
  5504. from backend.app.services.bambu_ftp import list_files_async
  5505. logger = logging.getLogger(__name__)
  5506. # No card in the slot means no /timelapse to walk — four connections that
  5507. # can only fail, on a path whose failures are swallowed and so would go on
  5508. # costing time silently forever (#2780).
  5509. #
  5510. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5511. # inside the loop's own try/except, so a caller that passed something
  5512. # unexpected used to get an empty listing rather than an exception. Keep
  5513. # that, instead of making this gate the first thing that can raise here.
  5514. printer_id = getattr(printer, "id", None)
  5515. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5516. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5517. return [], None
  5518. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  5519. try:
  5520. found_files = await list_files_async(
  5521. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5522. )
  5523. if found_files:
  5524. video_files = [
  5525. f
  5526. for f in found_files
  5527. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5528. ]
  5529. if video_files:
  5530. return video_files, timelapse_path
  5531. except Exception as e:
  5532. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5533. continue
  5534. return [], None
  5535. async def _capture_timelapse_baseline_at_start(
  5536. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5537. ) -> None:
  5538. """Snapshot the printer's timelapse directory at print start so the
  5539. completion-time scan can pick the new file by set-difference.
  5540. Must be called from every on_print_start path that proceeds to a real
  5541. print — both the new-archive branch and the expected-archive branch (which
  5542. queue / VP-dispatched prints take). Without a baseline,
  5543. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5544. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5545. so the new file ends up in the "baseline" set and no diff ever matches.
  5546. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  5547. unreliable — the snapshot-diff approach sidesteps that entirely.
  5548. When ``archive_id`` is known the baseline is also written to the archive
  5549. row, so it survives a restart and the manual "Scan for Timelapse" button
  5550. can run the same diff instead of falling back to clock-based matching
  5551. (#2704). Only baselines taken at print start are persisted — one taken at
  5552. completion already contains the new video and would poison a later scan.
  5553. """
  5554. names: set[str] | None = None
  5555. try:
  5556. if not _timelapse_listing_is_trustworthy(printer):
  5557. # Recorded anyway, deliberately. An empty baseline taken off a card
  5558. # we could not read is not authoritative, but it is still the right
  5559. # *default*: Bambuddy deletes each video from the printer once it is
  5560. # attached, so the usual card holds exactly one video at completion
  5561. # and an empty baseline resolves it correctly. Persisting NULL
  5562. # instead would send completion to take its own snapshot, by which
  5563. # point this print's video is on the card and would be swallowed by
  5564. # it. The ambiguity is handled where it actually bites — see
  5565. # ``require_unambiguous`` in the scan (#2957 follow-up).
  5566. logger.warning(
  5567. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  5568. "handshake cool-off, so the card could not be read — treating it as empty",
  5569. printer_id,
  5570. )
  5571. baseline_files, _ = await _list_timelapse_videos(printer)
  5572. names = {f.get("name", "") for f in baseline_files}
  5573. _timelapse_baselines[printer_id] = names
  5574. logger.info(
  5575. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  5576. len(names),
  5577. printer_id,
  5578. )
  5579. except Exception as e:
  5580. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  5581. if archive_id is None:
  5582. return
  5583. try:
  5584. async with async_session() as db:
  5585. from backend.app.models.archive import PrintArchive
  5586. archive = await db.get(PrintArchive, archive_id)
  5587. if archive is not None:
  5588. # Written even when the listing failed, and then as NULL. A
  5589. # reprint reuses the archive row, so leaving the previous run's
  5590. # baseline in place would have the scan diff this print against
  5591. # the state of the printer before the *last* one — and a stale
  5592. # baseline reads as authoritative, where NULL correctly falls
  5593. # back to a fresh snapshot.
  5594. archive.timelapse_baseline = sorted(names) if names is not None else None
  5595. await db.commit()
  5596. except Exception as e:
  5597. # In-memory baseline still covers the normal completion path.
  5598. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  5599. async def _scan_for_timelapse_with_retries(
  5600. archive_id: int, baseline_names: set[str] | None = None, *, plate_id: int | None = None
  5601. ):
  5602. """Poll the printer for this print's timelapse and attach it.
  5603. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  5604. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  5605. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  5606. (#2704). Comparing the current listing against the set of filenames that
  5607. existed when the print started needs no clock at all, because the printer
  5608. writes the video only once the print has ended.
  5609. Baseline precedence: the caller's in-memory set, then the one persisted on
  5610. the archive at print start, then a snapshot taken now. The last of those is
  5611. a poor substitute — by completion the new video may already be on the card,
  5612. in which case it lands in the "baseline" and no diff can ever match — but it
  5613. is all that is available for a print that began before Bambuddy started.
  5614. On success the video is deleted from the printer, which keeps ``/timelapse``
  5615. down to the unclaimed files and makes the next diff unambiguous.
  5616. """
  5617. logger = logging.getLogger(__name__)
  5618. # Cleared when the baseline had to be taken off a card we could not read, so
  5619. # the attach step refuses to choose between several candidates (#2957).
  5620. baseline_trusted = True
  5621. # --- Phase 1: establish the baseline -------------------------------------
  5622. try:
  5623. async with async_session() as db:
  5624. from backend.app.models.printer import Printer
  5625. service = ArchiveService(db)
  5626. archive = await service.get_archive(archive_id)
  5627. if not archive:
  5628. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  5629. return
  5630. if archive.timelapse_path:
  5631. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  5632. return
  5633. if not archive.printer_id:
  5634. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  5635. return
  5636. # The run this scan is for. The archive row passes to a newer run
  5637. # when it prints again (the next plate, a reprint), and that run's
  5638. # video is its own.
  5639. run_started_at = archive.started_at
  5640. if baseline_names is not None:
  5641. logger.info(
  5642. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  5643. len(baseline_names),
  5644. archive_id,
  5645. )
  5646. elif archive.timelapse_baseline is not None:
  5647. # Persisted at print start — survives a restart mid-print.
  5648. baseline_names = set(archive.timelapse_baseline)
  5649. logger.info(
  5650. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  5651. len(baseline_names),
  5652. archive_id,
  5653. )
  5654. else:
  5655. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5656. printer = result.scalar_one_or_none()
  5657. if not printer:
  5658. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  5659. return
  5660. if not _timelapse_listing_is_trustworthy(printer):
  5661. # The card is unreadable at the one moment a baseline has to
  5662. # be taken, so the empty listing below means "we never
  5663. # looked", not "these are all new". Carry on with it anyway
  5664. # — the usual card holds exactly one video, which resolves
  5665. # correctly — but stop the poll from *choosing* between
  5666. # several, which is how a stale video got attached to this
  5667. # print and then deleted off the printer (#2957 follow-up).
  5668. baseline_trusted = False
  5669. logger.warning(
  5670. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  5671. "handshake cool-off. A single new video still resolves; several will not be "
  5672. "guessed between — use Scan for Timelapse to pick one by hand",
  5673. archive_id,
  5674. archive.printer_id,
  5675. )
  5676. baseline_files, _ = await _list_timelapse_videos(printer)
  5677. baseline_names = {f.get("name", "") for f in baseline_files}
  5678. logger.info(
  5679. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  5680. len(baseline_names),
  5681. archive_id,
  5682. )
  5683. except Exception as e:
  5684. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  5685. return
  5686. # --- Phase 2: poll for a file that was not there when the print began -----
  5687. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  5688. max_attempts = _timelapse_scan_max_attempts()
  5689. seen_names: set[str] = set()
  5690. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  5691. attempt = 0
  5692. while True:
  5693. await asyncio.sleep(delay)
  5694. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  5695. attempt += 1
  5696. try:
  5697. from backend.app.models.printer import Printer
  5698. # Read phase: fetch archive + printer in a short session and release
  5699. # the pooled connection BEFORE the FTP list/download below. Holding it
  5700. # across the FTP round-trips left one connection idle-in-transaction per
  5701. # in-flight scan (issue #2572).
  5702. async with async_session() as db:
  5703. service = ArchiveService(db)
  5704. archive = await service.get_archive(archive_id)
  5705. if not archive:
  5706. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  5707. return
  5708. if archive.timelapse_path:
  5709. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  5710. return
  5711. if archive.started_at != run_started_at:
  5712. logger.info(
  5713. "[TIMELAPSE] Archive %s is printing again, stopping the previous run's poll", archive_id
  5714. )
  5715. return
  5716. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5717. printer = result.scalar_one_or_none()
  5718. if not printer:
  5719. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  5720. return
  5721. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  5722. # I/O phase (no DB connection held): FTP list + download.
  5723. video_files, found_path = await _list_timelapse_videos(printer)
  5724. # The poll can run for dozens of rounds, so only narrate a round
  5725. # that saw something change. Repeating the whole listing every 30 s
  5726. # would bury the one interesting line in the support bundle.
  5727. names_now = {f.get("name", "") for f in video_files}
  5728. changed = attempt == 1 or names_now != seen_names
  5729. seen_names = names_now
  5730. speak = logger.info if changed else logger.debug
  5731. if video_files:
  5732. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  5733. if changed:
  5734. for f in video_files[:5]:
  5735. logger.info("[TIMELAPSE] - %s", f.get("name"))
  5736. attached = await _attach_first_unclaimed_timelapse(
  5737. archive_id,
  5738. printer,
  5739. video_files,
  5740. baseline_names,
  5741. claimed,
  5742. attempt,
  5743. logger,
  5744. quiet=not changed,
  5745. require_unambiguous=not baseline_trusted,
  5746. plate_id=plate_id,
  5747. run_started_at=run_started_at,
  5748. )
  5749. if attached:
  5750. return
  5751. else:
  5752. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  5753. except Exception as e:
  5754. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  5755. if attempt >= max_attempts or time.monotonic() >= deadline:
  5756. break
  5757. # No name-match fallback: it compared the print name against the filename,
  5758. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  5759. # bundles it fired 159 times and matched zero times, so all it added was a
  5760. # misleading log line before giving up.
  5761. logger.warning(
  5762. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  5763. archive_id,
  5764. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  5765. )
  5766. async def _attach_layer_timelapse(
  5767. archive_id: int, timelapse_path: Path, plate_id: int | None, run_started_at: datetime | None
  5768. ) -> None:
  5769. """Attach the external camera's stitched timelapse to the archive.
  5770. The camera's video is the one the user set up in Bambuddy, so it wins
  5771. over the printer's own when both are on: it replaces the printer's video
  5772. (usually there first; stitching takes minutes) and that file is deleted,
  5773. leaving nothing in the archive folder unreferenced. ``run_started_at`` is
  5774. the run the frames were taken for: when the archive is printing again by
  5775. the time the stitch is done, the video is not the new run's and is
  5776. dropped. The stitched file is a temporary either way.
  5777. """
  5778. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  5779. logger = logging.getLogger(__name__)
  5780. try:
  5781. async with async_session() as db:
  5782. service = ArchiveService(db)
  5783. archive = await service.get_archive(archive_id)
  5784. if archive is None:
  5785. return
  5786. if archive.started_at != run_started_at:
  5787. logger.info(
  5788. "[LAYER-TL] Archive %s is printing again; dropping the previous run's layer timelapse", archive_id
  5789. )
  5790. return
  5791. replaced = archive.timelapse_path
  5792. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  5793. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  5794. if not await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=plate_id):
  5795. return
  5796. attached = archive.timelapse_path
  5797. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  5798. if replaced and replaced != attached:
  5799. try:
  5800. old = safe_join_under(app_settings.base_dir, replaced, http=False)
  5801. except PathTraversalError:
  5802. return
  5803. await asyncio.to_thread(old.unlink, missing_ok=True)
  5804. logger.info("[LAYER-TL] Replaced the printer's timelapse %s on archive %s", replaced, archive_id)
  5805. finally:
  5806. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  5807. # ``run_started_at`` not given: attach whichever run the archive is on.
  5808. _ANY_RUN = object()
  5809. async def _attach_first_unclaimed_timelapse(
  5810. archive_id: int,
  5811. printer,
  5812. video_files: list[dict],
  5813. baseline_names: set[str],
  5814. claimed: set[str],
  5815. attempt: int,
  5816. logger: logging.Logger,
  5817. *,
  5818. quiet: bool = False,
  5819. require_unambiguous: bool = False,
  5820. plate_id: int | None = None,
  5821. run_started_at: datetime | None | object = _ANY_RUN,
  5822. ) -> bool:
  5823. """Download and attach the one video that belongs to this print.
  5824. A candidate is any file absent from the print-start baseline. More than one
  5825. can qualify when a previous print's video landed late, after this print's
  5826. baseline was taken — those are filtered out by name, because they are
  5827. already attached to another archive. Sorting the candidates instead would
  5828. mean sorting on mtime or on the filename timestamp, both of which come from
  5829. the printer's unsynced clock.
  5830. Returns True once a video is attached. The printer's copy is deleted only
  5831. after the attach succeeds on bytes whose length matched the listing.
  5832. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  5833. already seen this exact listing — the poll runs for many rounds and only the
  5834. rounds where something changed are worth an INFO line.
  5835. """
  5836. from backend.app.services.bambu_ftp import (
  5837. DownloadDeadlineExceeded,
  5838. delete_archived_timelapse,
  5839. download_file_bytes_async,
  5840. remote_file_settled,
  5841. )
  5842. speak = logger.debug if quiet else logger.info
  5843. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  5844. if not new_files:
  5845. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  5846. return False
  5847. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  5848. if not candidates:
  5849. speak(
  5850. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  5851. attempt,
  5852. len(new_files),
  5853. )
  5854. return False
  5855. if len(candidates) > 1:
  5856. if require_unambiguous:
  5857. # The baseline is not evidence -- it was taken off a card that could
  5858. # not be read -- so "new since the baseline" does not narrow these
  5859. # down at all. Taking the first would attach an arbitrary video to
  5860. # this print and then delete it from the printer.
  5861. logger.warning(
  5862. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  5863. "leaving all of them on the printer for manual selection",
  5864. attempt,
  5865. len(candidates),
  5866. ", ".join(str(f.get("name")) for f in candidates),
  5867. )
  5868. return False
  5869. logger.warning(
  5870. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  5871. "the rest stay on the printer for manual selection",
  5872. attempt,
  5873. len(candidates),
  5874. ", ".join(str(f.get("name")) for f in candidates),
  5875. )
  5876. target = candidates[0]
  5877. file_name = str(target.get("name") or "") # every listed entry has one
  5878. remote_path = target.get("path") or f"/timelapse/{file_name}"
  5879. logger.info(
  5880. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  5881. attempt,
  5882. file_name,
  5883. archive_id,
  5884. )
  5885. # The listing always carries a size (`list_files` skips entries it can't
  5886. # parse), but read it explicitly: the delete below is destructive and must
  5887. # depend on a size we actually had, not on one we hoped was there.
  5888. expected_size = target.get("size")
  5889. try:
  5890. timelapse_data = await download_file_bytes_async(
  5891. printer.ip_address,
  5892. printer.access_code,
  5893. remote_path,
  5894. printer_model=printer.model,
  5895. expected_size=expected_size,
  5896. )
  5897. except DownloadDeadlineExceeded:
  5898. # Too slow for its size this round; the printer keeps its copy.
  5899. timelapse_data = None
  5900. if not timelapse_data:
  5901. # Short or failed transfer. The printer keeps its copy, so the next
  5902. # round can try again — which is exactly why the delete below is
  5903. # gated on a verified download.
  5904. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  5905. return False
  5906. # The length check above proves we got what the listing said, not that the
  5907. # printer had finished writing. A video still being written can be listed
  5908. # short, served short, and pass — so confirm it has stopped growing before
  5909. # committing to it and deleting the original (#2704).
  5910. if not await remote_file_settled(
  5911. printer.ip_address,
  5912. printer.access_code,
  5913. remote_path,
  5914. len(timelapse_data),
  5915. printer_model=printer.model,
  5916. ):
  5917. return False
  5918. # Write phase: attach in a fresh short-lived session. The download took a
  5919. # while: by now the archive may have its video, or be printing again for a
  5920. # newer run, whose video this is not. Then nothing is attached or deleted,
  5921. # and the poll ends (True).
  5922. async with async_session() as db:
  5923. service = ArchiveService(db)
  5924. if run_started_at is not _ANY_RUN:
  5925. current = await service.get_archive(archive_id)
  5926. if current is None or current.timelapse_path or current.started_at != run_started_at:
  5927. logger.info(
  5928. "[TIMELAPSE] Archive %s moved on during the download (video attached or printing again); "
  5929. "%s stays on the printer",
  5930. archive_id,
  5931. file_name,
  5932. )
  5933. return True
  5934. success = await service.attach_timelapse(archive_id, timelapse_data, file_name, plate_id=plate_id)
  5935. if not success:
  5936. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  5937. return False
  5938. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  5939. await delete_archived_timelapse(
  5940. printer.ip_address,
  5941. printer.access_code,
  5942. remote_path,
  5943. verified=expected_size is not None,
  5944. printer_model=printer.model,
  5945. printer_name=printer.name,
  5946. )
  5947. return True
  5948. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  5949. # module-level so tests can monkeypatch them down to ~0 without timing out.
  5950. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  5951. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  5952. # How long the *background* upgrade keeps waiting after the notification has
  5953. # already gone out (#2704 follow-up). The short bound above exists so a slow
  5954. # printer can't hold up the print-complete notification; this one exists so the
  5955. # archive still ends up with the better frame afterwards.
  5956. #
  5957. # Measured across 261 attaches in the support bundles, the video lands a median
  5958. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  5959. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  5960. # was 546s. Every other model was inside 26s. The long budget is therefore
  5961. # almost entirely for P1-series users; on everything else the short wait already
  5962. # wins and this task never runs.
  5963. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  5964. async def _capture_finish_photo_from_timelapse(
  5965. archive_id: int,
  5966. archive_dir: Path,
  5967. timeout: float | None = None,
  5968. rotation: int = 0,
  5969. ) -> tuple[str | None, bool]:
  5970. """Wait for the per-print timelapse to land on the archive and extract its
  5971. last frame as the finish photo (#1397).
  5972. Bambu firmware stops timelapse recording after the toolhead parks but
  5973. before the bed-drop end-gcode runs, so the last frame frames the finished
  5974. print correctly. A live camera grab at gcode_state=FINISH captures the
  5975. bed already lowered.
  5976. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  5977. ``archive.timelapse_path`` when the file lands. This function polls for
  5978. that field.
  5979. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  5980. the wait ran out with no video on the archive yet — i.e. the video may
  5981. still be coming and a later attempt could succeed. It is False when the
  5982. video landed (whether or not extraction worked), because in that case
  5983. waiting longer changes nothing. The caller uses that to decide between
  5984. falling back permanently and scheduling a background upgrade.
  5985. ``rotation`` is the printer's camera_rotation, applied to the extracted
  5986. still (#2708) so this source agrees with every other finish-photo source.
  5987. The archived video itself is the printer's own file and is left alone —
  5988. rotating it would mean re-encoding it.
  5989. """
  5990. import uuid
  5991. from backend.app.models.archive import PrintArchive
  5992. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  5993. logger = logging.getLogger(__name__)
  5994. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  5995. deadline = asyncio.get_event_loop().time() + budget
  5996. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  5997. while True:
  5998. async with async_session() as db:
  5999. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6000. archive = result.scalar_one_or_none()
  6001. timelapse_relpath = archive.timelapse_path if archive else None
  6002. if timelapse_relpath:
  6003. video_path = app_settings.base_dir / timelapse_relpath
  6004. if video_path.exists() and video_path.stat().st_size > 0:
  6005. photos_dir = archive_dir / "photos"
  6006. photos_dir.mkdir(parents=True, exist_ok=True)
  6007. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6008. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6009. output_path = photos_dir / filename
  6010. if await extract_video_last_frame(video_path, output_path):
  6011. await apply_camera_rotation_to_file(output_path, rotation, logger)
  6012. logger.info(
  6013. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  6014. video_path.name,
  6015. archive_id,
  6016. )
  6017. return filename, False
  6018. logger.warning(
  6019. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  6020. video_path.name,
  6021. archive_id,
  6022. )
  6023. return None, False
  6024. if asyncio.get_event_loop().time() >= deadline:
  6025. logger.info(
  6026. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  6027. archive_id,
  6028. budget,
  6029. )
  6030. return None, True
  6031. await asyncio.sleep(poll_interval)
  6032. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  6033. """Add the timelapse's last frame to an archive after the fact (#2704).
  6034. The print-complete notification waits only ~60s for the video, because
  6035. holding a notification for minutes is worse than sending it with a live
  6036. camera grab. On a P1-series printer the video often lands well after that,
  6037. so the archive used to be stuck with the live grab — which is taken at
  6038. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  6039. the worse photo of the two.
  6040. This keeps waiting in the background and, when the video arrives, extracts
  6041. the frame and puts it *first* in the archive's photo list, so opening the
  6042. gallery shows it. The live grab is deliberately kept: the notification that
  6043. already went out links to that exact file, and deleting it would leave a
  6044. broken image in Discord or Telegram.
  6045. """
  6046. logger = logging.getLogger(__name__)
  6047. filename, _ = await _capture_finish_photo_from_timelapse(
  6048. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  6049. )
  6050. if not filename:
  6051. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  6052. return
  6053. try:
  6054. async with async_session() as db:
  6055. from backend.app.models.archive import PrintArchive
  6056. archive = await db.get(PrintArchive, archive_id)
  6057. if archive is None:
  6058. return
  6059. photos = list(archive.photos or [])
  6060. if filename in photos:
  6061. return
  6062. # Front of the list: PhotoGalleryModal opens at index 0.
  6063. archive.photos = [filename, *photos]
  6064. await db.commit()
  6065. except Exception as e:
  6066. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  6067. return
  6068. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  6069. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  6070. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  6071. """Put the filament-attribution context back after a restart mid-print.
  6072. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  6073. both die with the process. The print keeps running, so at completion the
  6074. tracker would fall back to whatever the printer reports *now* — and AMS
  6075. filament backup makes "now" the substitute tray, charging the whole print
  6076. to the spool that only finished it.
  6077. The persisted row is only trusted when its print name still matches what
  6078. the printer says it is running: a row left behind by a completion we never
  6079. saw must not attach itself to the next print.
  6080. """
  6081. try:
  6082. from backend.app.api.routes.settings import get_setting
  6083. from backend.app.services.usage_tracker import (
  6084. clear_persisted_session,
  6085. get_persisted_print_name,
  6086. restore_session,
  6087. )
  6088. persisted_name = await get_persisted_print_name(db, printer_id)
  6089. current_name = (state.subtask_name or "").strip()
  6090. if persisted_name and current_name and persisted_name.strip() != current_name:
  6091. logger.info(
  6092. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  6093. printer_id,
  6094. persisted_name,
  6095. current_name,
  6096. )
  6097. await clear_persisted_session(db, printer_id)
  6098. # Fall through to seeding: the print on the printer is real, it just
  6099. # isn't the one the row described.
  6100. persisted_log = None
  6101. else:
  6102. # Spoolman users get the tray-change log back but no in-memory
  6103. # session — see ``on_print_start`` on why that dict is load-bearing
  6104. # for the remain%-sync guard.
  6105. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6106. persisted_log = await restore_session(
  6107. db,
  6108. printer_id,
  6109. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  6110. )
  6111. if persisted_log:
  6112. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  6113. # Anything this process already observed goes after the persisted
  6114. # history — the log is ordered by layer, and a fresh process can
  6115. # only have seen changes from later in the print.
  6116. for entry in state.tray_change_log or []:
  6117. if tuple(entry) not in restored:
  6118. restored.append(tuple(entry))
  6119. state.tray_change_log = restored
  6120. tray_now = state.tray_now
  6121. if 0 <= tray_now <= 254:
  6122. if not state.tray_change_log:
  6123. # No persisted history — a print that started before this build,
  6124. # or before the row existed. Seed with the tray feeding right
  6125. # now so the remainder of the print is at least attributable to
  6126. # the right spool.
  6127. state.tray_change_log = [(tray_now, state.layer_num)]
  6128. logger.info(
  6129. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  6130. printer_id,
  6131. tray_now,
  6132. state.layer_num,
  6133. )
  6134. # The tray handler updates ``last_loaded_tray`` on every push
  6135. # regardless of whether it logged a change, so re-align it to avoid
  6136. # a duplicate entry on the next push. Only ever with a real tray:
  6137. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  6138. # 255" fallback, and writing 255 into it would defeat that.
  6139. state.last_loaded_tray = tray_now
  6140. except Exception:
  6141. # Never let attribution recovery cost the caller its timelapse
  6142. # baseline — that capture has to happen before the printer uploads
  6143. # the in-flight MP4 and there is no second chance at it.
  6144. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  6145. async def on_print_running_observed(printer_id: int, data: dict):
  6146. """Restart-recovery for a print that started before Bambuddy came up.
  6147. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  6148. after Bambuddy startup (#1304 guard, prevents duplicate archive
  6149. creation). This hook restores the persisted archive into ``_active_prints``
  6150. and captures the timelapse baseline that normally hangs off print start.
  6151. Fires once per session, in lieu of on_print_start when restart-recovery
  6152. kicks in. The printer doesn't upload the timelapse until after PRINT
  6153. COMPLETE, so a baseline captured any time during the print is still
  6154. pre-upload.
  6155. """
  6156. logger = logging.getLogger(__name__)
  6157. async with async_session() as db:
  6158. from backend.app.models.printer import Printer
  6159. state = printer_manager.get_status(printer_id)
  6160. if state is not None:
  6161. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  6162. if authorization is True:
  6163. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  6164. await _restore_usage_tracking_session(printer_id, state, db, logger)
  6165. await _restore_printable_objects(printer_id, state, db, logger)
  6166. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6167. printer = result.scalar_one_or_none()
  6168. if not printer:
  6169. logger.warning(
  6170. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  6171. printer_id,
  6172. )
  6173. return
  6174. # Avoid double-capture: ownership reconciliation above must still run when
  6175. # a baseline already exists, but the camera work itself is one-shot.
  6176. if printer_id in _timelapse_baselines:
  6177. logger.debug(
  6178. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  6179. printer_id,
  6180. )
  6181. return
  6182. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  6183. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  6184. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  6185. against the printer's current MQTT state.
  6186. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  6187. COMPLETE events, typically a print finishing during an MQTT disconnect
  6188. window followed by a smart-plug power cycle):
  6189. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  6190. provably not running anymore — only branch that should fire under
  6191. normal disconnect-then-reconnect timing.
  6192. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  6193. firmware mints a fresh ``subtask_id`` for each print, including the
  6194. ghost replay it runs after a power cycle from a leftover SD file —
  6195. so a mismatch unambiguously means the in-DB archive is no longer
  6196. the print on the printer.
  6197. 3. Printer is running but ``subtask_name`` is empty. The printer
  6198. doesn't know what it's running; the archive's reference to it is
  6199. already broken.
  6200. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  6201. with matching subtask_id+subtask_name is left alone. The cost of a false
  6202. positive is a duplicate archive on the next real PRINT COMPLETE — the
  6203. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  6204. clears on synthesis, so the real completion creates a fresh row instead
  6205. of overwriting the synthesised one (#1679). The cost of a false negative
  6206. is the ghost-print loop in #1542.
  6207. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  6208. MQTT has connected but the first ``push_status`` response hasn't been
  6209. applied yet — ``PrinterState`` is sitting on its construction defaults.
  6210. The reconcile caller in ``on_printer_status_change`` is already gated
  6211. on a real ``state.state``, so in normal operation this branch is
  6212. unreachable; it's kept as belt-and-braces for future callers and for
  6213. the narrow window where a partial state update could arrive
  6214. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  6215. ``not stale`` on degenerate input is strictly conservative: a real
  6216. stale archive will still be caught by the next push_status arriving
  6217. with terminal state.
  6218. """
  6219. current_state = (state.state or "").upper()
  6220. if current_state in ("", "UNKNOWN"):
  6221. # No real push_status yet — PrinterState defaults are not evidence.
  6222. return False, ""
  6223. if current_state in ("IDLE", "FINISH", "FAILED"):
  6224. return True, f"printer state {current_state}"
  6225. # Below here the printer is in a running / pre-running state (RUNNING /
  6226. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  6227. current_subtask_id = (state.subtask_id or "").strip()
  6228. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  6229. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  6230. current_subtask_name = (state.subtask_name or "").strip()
  6231. if not current_subtask_name:
  6232. return True, "printer subtask_name empty"
  6233. return False, ""
  6234. async def prime_kprofile_table(printer_id: int) -> int:
  6235. """Read the printer's calibration table once per connection.
  6236. The AMS slot card shows a K value per slot (#2854). On the printers whose
  6237. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  6238. report ``cali_idx`` and nothing else -- that number can only come from
  6239. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  6240. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  6241. backup, or the printer answering a query BambuStudio made on the report
  6242. topic we share. A Bambuddy that nobody visited showed a card with no K
  6243. values at all.
  6244. Only the diameters actually fitted are asked for, which is one request on a
  6245. single-nozzle printer and two on a dual. Probing the four sizes blind is
  6246. what the backup does, and it is both wasteful and the thing that used to
  6247. blank the table.
  6248. Returns the number of nozzles whose table was read.
  6249. """
  6250. client = printer_manager.get_client(printer_id)
  6251. state = printer_manager.get_status(printer_id)
  6252. if client is None or state is None or not state.connected:
  6253. return 0
  6254. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  6255. # ask once, and both entries are empty until the first push_status lands.
  6256. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  6257. if not diameters:
  6258. logging.getLogger(__name__).debug(
  6259. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  6260. printer_id,
  6261. )
  6262. return 0
  6263. primed = 0
  6264. for diameter in diameters:
  6265. try:
  6266. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  6267. except Exception as exc: # noqa: BLE001
  6268. # A printer that won't answer costs the card its K values, nothing
  6269. # more — never the connection this runs on the back of.
  6270. logging.getLogger(__name__).warning(
  6271. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  6272. )
  6273. continue
  6274. primed += 1
  6275. logging.getLogger(__name__).info(
  6276. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  6277. )
  6278. return primed
  6279. def _sd_files_in_use(state) -> set[str]:
  6280. """Names of the SD-card files the printer may be printing right now (#3009).
  6281. The post-print cleanup works out what to delete from the finished archive,
  6282. not from the printer. When reconciliation closes an old archive because the
  6283. printer has moved on to a new job, and that job is the same file reprinted
  6284. from the printer's screen, the cleanup would delete the file mid-print.
  6285. Empty unless the printer is busy: on an ordinary completion the state is
  6286. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  6287. name, a path or a URL depending on firmware, and some report only the
  6288. plate's G-code, so the job name is matched as well, in the same spellings
  6289. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  6290. ignores case.
  6291. """
  6292. def _text(value) -> str:
  6293. return value.strip() if isinstance(value, str) else ""
  6294. if state is None:
  6295. return set()
  6296. current_state = _text(getattr(state, "state", None)).upper()
  6297. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  6298. return set()
  6299. in_use: set[str] = set()
  6300. gcode_file = _text(getattr(state, "gcode_file", None))
  6301. if gcode_file:
  6302. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  6303. # both legal in a file name, and raises on some inputs.
  6304. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  6305. if name:
  6306. in_use.add(name.lower())
  6307. subtask_name = _text(getattr(state, "subtask_name", None))
  6308. if subtask_name:
  6309. for name in (subtask_name, subtask_name.replace(" ", "_")):
  6310. for ext in (".3mf", ".gcode"):
  6311. in_use.add(f"{name}{ext}".lower())
  6312. return in_use
  6313. async def reconcile_stale_active_prints(printer_id: int) -> int:
  6314. """Synthesise ``on_print_complete`` for archives whose print can't be
  6315. running on the printer anymore.
  6316. Called once per MQTT (re)connection (from on_printer_status_change when
  6317. the connected edge flips False → True) and at Bambuddy startup (from
  6318. the FastAPI lifespan). Without this, a print that completes during a
  6319. disconnect window — followed by a smart-plug-driven power cycle — leaves
  6320. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  6321. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  6322. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  6323. power cycle until the operator notices (#1542 follow-up). Reconciliation
  6324. closes the loop by faking the missed PRINT COMPLETE — the existing
  6325. cleanup chain handles SD-file deletion, status updates, usage tracking,
  6326. and notifications.
  6327. Synthesised ``status="aborted"`` is the conservative label: we have no
  6328. proof the print finished successfully (and no progress evidence to
  6329. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  6330. fires later, overwrites the status with the correct value.
  6331. Returns the number of archives reconciled.
  6332. """
  6333. state = printer_manager.get_status(printer_id)
  6334. if not state:
  6335. return 0
  6336. # Don't reconcile while disconnected — we'd be making a decision against
  6337. # stale cached state. The connected → reconcile edge handles this.
  6338. if not state.connected:
  6339. return 0
  6340. from backend.app.models.archive import PrintArchive
  6341. reconciled = 0
  6342. async with async_session() as db:
  6343. result = await db.execute(
  6344. select(PrintArchive).where(
  6345. PrintArchive.printer_id == printer_id,
  6346. PrintArchive.status == "printing",
  6347. )
  6348. )
  6349. active = list(result.scalars().all())
  6350. if not active:
  6351. return 0
  6352. logger = logging.getLogger(__name__)
  6353. for archive in active:
  6354. is_stale, reason = _is_active_archive_stale(archive, state)
  6355. if not is_stale:
  6356. continue
  6357. logger.info(
  6358. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  6359. printer_id,
  6360. archive.id,
  6361. archive.filename,
  6362. reason,
  6363. )
  6364. # Synthesised payload: minimal fields the on_print_complete chain
  6365. # needs. `_reconciled` marker lets downstream code distinguish this
  6366. # from a real MQTT-driven completion if it ever needs to (e.g. for
  6367. # metrics / debug logging). raw_data is the live printer state so
  6368. # the usage tracker can compare end-of-print remain% against the
  6369. # captured start values.
  6370. try:
  6371. await on_print_complete(
  6372. printer_id,
  6373. {
  6374. "status": "aborted",
  6375. "filename": archive.filename,
  6376. "subtask_name": archive.print_name or "",
  6377. "subtask_id": archive.subtask_id or "",
  6378. "raw_data": state.raw_data or {},
  6379. "_reconciled": True,
  6380. },
  6381. )
  6382. reconciled += 1
  6383. except Exception as e:
  6384. # Catch-all: a reconciliation failure must not block the
  6385. # printer's normal status flow. The archive stays in
  6386. # ``status="printing"`` and the next reconnect retries.
  6387. logger.warning(
  6388. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  6389. archive.id,
  6390. e,
  6391. )
  6392. return reconciled
  6393. # #2547: clearance left between the nozzle and the top of the print when the
  6394. # plate is commanded back into camera framing. The nozzle is parked away from
  6395. # the part by then, so this is belt-and-braces against a max_z_height that
  6396. # under-reports (e.g. a slicer that excludes a final Z hop).
  6397. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  6398. # How far below the restored position to drop the plate again afterwards, so
  6399. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  6400. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  6401. # on machines with less headroom.
  6402. _PLATE_PARK_DROP_MM = 100.0
  6403. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  6404. # this axis, so it is a proven-safe speed for the full travel.
  6405. _PLATE_RESTORE_FEEDRATE = 600
  6406. # Time allowed for the plate to reach the restored position before the camera
  6407. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  6408. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  6409. # How long `_background_finish_photo` waits for this producer. Must cover the
  6410. # settle window plus a worst-case RTSP grab (15s), and stay below the
  6411. # notification path's own photo wait so a slow producer degrades to a
  6412. # photo-less notification rather than a missed one. The chamber light's
  6413. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  6414. # camera_light.MAX_DELAY_SECONDS stays below it.
  6415. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  6416. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  6417. """The ``_active_prints`` keys a finished print may be registered under.
  6418. Matching how they were registered in on_print_start. Shared by
  6419. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  6420. to find the same binding.
  6421. """
  6422. possible_keys = []
  6423. # Try subtask_name variations first (most reliable for matching)
  6424. if subtask_name:
  6425. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  6426. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  6427. possible_keys.append((printer_id, subtask_name))
  6428. # Try filename variations
  6429. if filename:
  6430. # Extract just the filename if it's a path
  6431. fname = filename.split("/")[-1] if "/" in filename else filename
  6432. if fname.endswith(".3mf"):
  6433. possible_keys.append((printer_id, fname))
  6434. elif fname.endswith(".gcode"):
  6435. base_name = fname.rsplit(".", 1)[0]
  6436. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  6437. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6438. possible_keys.append((printer_id, fname))
  6439. else:
  6440. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  6441. possible_keys.append((printer_id, f"{fname}.3mf"))
  6442. possible_keys.append((printer_id, fname))
  6443. # Also try full path versions
  6444. if filename.endswith(".3mf"):
  6445. possible_keys.append((printer_id, filename))
  6446. elif filename.endswith(".gcode"):
  6447. base_name = filename.rsplit(".", 1)[0]
  6448. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6449. possible_keys.append((printer_id, filename))
  6450. else:
  6451. possible_keys.append((printer_id, f"{filename}.3mf"))
  6452. possible_keys.append((printer_id, filename))
  6453. return possible_keys
  6454. def _archive_name_forms(archive) -> set[str]:
  6455. """The names an archive could be echoed back as, in normalised form (#3240).
  6456. Its print name, and its filename with and without the 3MF extension.
  6457. """
  6458. forms = set()
  6459. if archive.print_name:
  6460. forms.add(_normalise_subtask_name(archive.print_name))
  6461. if archive.filename:
  6462. forms.add(_normalise_subtask_name(archive.filename))
  6463. for suffix in (".gcode.3mf", ".3mf"):
  6464. if archive.filename.lower().endswith(suffix):
  6465. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  6466. forms.discard("")
  6467. return forms
  6468. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  6469. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  6470. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  6471. from the plate recorded when the job was dispatched. Neither is touched:
  6472. ``on_print_complete`` pops both, which is why the finish-photo producer
  6473. calls this before its first await, while they are still there.
  6474. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  6475. archive, or that it only knows by a name -- and on any error: the producer
  6476. calls this before the ``try`` that always releases the photo consumer, so
  6477. it must not raise.
  6478. """
  6479. try:
  6480. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  6481. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  6482. if archive_id is None:
  6483. return None, None
  6484. return archive_id, _print_plate_ids.get(archive_id)
  6485. except Exception:
  6486. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  6487. return None, None
  6488. async def _max_z_for_current_print(
  6489. printer_id: int,
  6490. data: dict,
  6491. logger,
  6492. archive_id: int | None,
  6493. plate_id: int | None = None,
  6494. ) -> float | None:
  6495. """Height of the print that just finished on ``printer_id``, or None (#2547).
  6496. This number becomes the target of a real Z move, so every step here refuses
  6497. rather than guesses. A height belonging to some *other* print is the one
  6498. failure that could drive the nozzle into the model: 20 mm carried onto a
  6499. 200 mm print would command the plate up through the part.
  6500. Three independent things therefore have to agree before a height is
  6501. returned:
  6502. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  6503. when it started (see ``_bound_print``), never one found by name. A name
  6504. is not an identity: every plate of a multi-plate file shares one, and a
  6505. reprint reuses its archive row, so the newest archive with the right
  6506. name can be another plate of the same file. Support bundles show the
  6507. old name lookup doing exactly that (archive 288 for a print bound to
  6508. 169, 313 layers against 125), stopped only by the layer check below.
  6509. No binding, no move.
  6510. 2. **Identity.** The bound archive's name still has to be the finished
  6511. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  6512. because the printer echoes spaces as underscores (#3240). Exact: not a
  6513. substring, and not the completion check's tolerance for a truncated
  6514. echo.
  6515. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  6516. match the layer count the printer itself reported over MQTT for the print
  6517. that just ended. These come from genuinely different sources, so a
  6518. mismatch means the row is not this print, whatever its name says.
  6519. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  6520. plate of a multi-plate file reuses the archive row without updating its
  6521. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  6522. ``on_print_complete`` may already have flipped the status by the time we
  6523. run.
  6524. """
  6525. subtask_name = (data.get("subtask_name") or "").strip()
  6526. if not subtask_name:
  6527. # Nothing to identify the print by — refuse rather than fall back to
  6528. # "whatever ran last on this printer".
  6529. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  6530. return None
  6531. if archive_id is None:
  6532. logger.info(
  6533. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  6534. printer_id,
  6535. subtask_name,
  6536. )
  6537. return None
  6538. try:
  6539. from backend.app.models.archive import PrintArchive
  6540. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  6541. async with async_session() as db:
  6542. result = await db.execute(
  6543. select(PrintArchive).where(
  6544. PrintArchive.id == archive_id,
  6545. PrintArchive.printer_id == printer_id,
  6546. PrintArchive.status.in_(("printing", "completed")),
  6547. PrintArchive.deleted_at.is_(None),
  6548. )
  6549. )
  6550. archive = result.scalar_one_or_none()
  6551. if archive is None or not archive.file_path:
  6552. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  6553. return None
  6554. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  6555. logger.warning(
  6556. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  6557. printer_id,
  6558. archive_id,
  6559. subtask_name,
  6560. )
  6561. return None
  6562. client = printer_manager.get_client(printer_id)
  6563. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  6564. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  6565. logger.warning(
  6566. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  6567. "— refusing to move the plate on a height that may not be this print's",
  6568. printer_id,
  6569. archive.id,
  6570. archive.total_layers,
  6571. reported_layers,
  6572. )
  6573. return None
  6574. # Stored relative to the data directory, like every other archive path
  6575. # (#3240: this read a `data_dir` setting that does not exist).
  6576. path = app_settings.base_dir / archive.file_path
  6577. plate = plate_id or archive.plate_id or 1
  6578. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  6579. except Exception as e:
  6580. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  6581. return None
  6582. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  6583. """Raise the plate back into camera framing before the finish photo (#2547).
  6584. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  6585. the time ``gcode_state`` reaches FINISH the finished print sits far below
  6586. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  6587. This commands an absolute ``G1 Z`` back to just above the last printed
  6588. layer.
  6589. Absolute, not relative, is the whole safety argument. ``max_z_height +
  6590. clearance`` is a height the toolhead was physically at seconds earlier, so
  6591. it is inside the travel limits by construction and leaves the nozzle above
  6592. the part. It is also unambiguous across model families: Z is the
  6593. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  6594. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  6595. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  6596. (#2579).
  6597. Returns True if the move was sent and waited out, False if it was skipped.
  6598. """
  6599. client = printer_manager.get_client(printer_id)
  6600. if client is None:
  6601. return False
  6602. # Re-read state immediately before commanding motion. If the queue has
  6603. # already started the next print, the printer is no longer ours to move.
  6604. state = getattr(client, "state", None)
  6605. if state is None or state.state != "FINISH":
  6606. logger.info(
  6607. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  6608. printer_id,
  6609. getattr(state, "state", "unknown"),
  6610. )
  6611. return False
  6612. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  6613. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  6614. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  6615. return False
  6616. logger.info(
  6617. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  6618. printer_id,
  6619. target_z,
  6620. max_z_height,
  6621. _PLATE_RESTORE_CLEARANCE_MM,
  6622. _PLATE_RESTORE_SETTLE_SECONDS,
  6623. )
  6624. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  6625. return True
  6626. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  6627. """Drop the plate again after the finish photo (#2547).
  6628. Without this the user walks up to a finished print sitting just under the
  6629. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  6630. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  6631. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  6632. print homes anyway.
  6633. """
  6634. client = printer_manager.get_client(printer_id)
  6635. state = getattr(client, "state", None) if client else None
  6636. if client is None or state is None or state.state != "FINISH":
  6637. return
  6638. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  6639. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  6640. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  6641. """True if a queue item is about to take this printer (#2547).
  6642. The scheduler dispatches the next job the moment a print completes, and a
  6643. plate move interleaved with a print start is not a race worth having. The
  6644. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  6645. this window; this closes the head of it.
  6646. """
  6647. try:
  6648. from backend.app.models.print_queue import PrintQueueItem
  6649. async with async_session() as db:
  6650. result = await db.execute(
  6651. select(PrintQueueItem.id)
  6652. .where(
  6653. PrintQueueItem.printer_id == printer_id,
  6654. PrintQueueItem.status.in_(("pending", "printing")),
  6655. )
  6656. .limit(1)
  6657. )
  6658. return result.scalar_one_or_none() is not None
  6659. except Exception as e:
  6660. # Fail closed: if we can't tell, don't move the plate.
  6661. logging.getLogger(__name__).debug(
  6662. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  6663. )
  6664. return True
  6665. async def on_finish_photo_moment(printer_id: int, data: dict):
  6666. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  6667. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  6668. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  6669. fallback for prints that skip stage 22 (cancel, external-spool-only,
  6670. HMS halt, firmware variants). Grabs one frame via the same
  6671. external-camera / RTSP path the post-completion fallback uses, stores
  6672. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  6673. ``_background_finish_photo`` consume the cached bytes when it runs.
  6674. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  6675. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  6676. set to Smooth (#1721). No force-on now means the user's explicit
  6677. timelapse=off in the slicer send dialog is respected.
  6678. """
  6679. logger = logging.getLogger(__name__)
  6680. trigger = data.get("trigger", "unknown")
  6681. timelapse_was_active = bool(data.get("timelapse_was_active"))
  6682. logger.info(
  6683. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  6684. printer_id,
  6685. trigger,
  6686. timelapse_was_active,
  6687. )
  6688. # If a timelapse is actively recording, skip the pre-capture — the
  6689. # post-completion path will extract the last frame from the recorded
  6690. # video, which still provides the best framing (toolhead parked,
  6691. # before bed drop) without the per-layer parking side effects.
  6692. if timelapse_was_active:
  6693. logger.info(
  6694. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  6695. printer_id,
  6696. )
  6697. return
  6698. # #1790: register the producer-done event BEFORE the first await so the
  6699. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  6700. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  6701. # The `finally` below guarantees `set()` runs on every exit, including
  6702. # early returns and exceptions, so the consumer's bounded wait can't hang.
  6703. producer_done = asyncio.Event()
  6704. _stage22_finish_in_flight[printer_id] = producer_done
  6705. # #3240: also before the first await. On the FINISH-state path
  6706. # `on_print_complete` is dispatched right behind us and pops both the
  6707. # print's archive binding and its plate; read here, they are still there.
  6708. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  6709. # #2547: set once the plate has actually been raised, and read by the
  6710. # `finally` below. Declared out here so a failure anywhere after the move —
  6711. # a camera timeout, a DB error — still lowers the plate again.
  6712. restore_max_z: float | None = None
  6713. try:
  6714. async with async_session() as db:
  6715. from backend.app.api.routes.settings import get_setting
  6716. from backend.app.models.printer import Printer
  6717. capture_setting = await get_setting(db, "capture_finish_photo")
  6718. if capture_setting is not None and capture_setting.lower() != "true":
  6719. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  6720. return
  6721. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6722. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  6723. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6724. printer = result.scalar_one_or_none()
  6725. if printer is None:
  6726. logger.warning(
  6727. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  6728. printer_id,
  6729. )
  6730. return
  6731. frame_bytes: bytes | None = None
  6732. # #2708: the banked frame arrives already rotated — it comes from
  6733. # `_capture_snapshot_for_notification`, which rotates before returning.
  6734. # Every other source below is a raw grab. Tracking which lets us store
  6735. # exactly one rotation in `_stage22_finish_frames` either way.
  6736. frame_already_rotated = False
  6737. # On the FINISH-state path the End G-code has already run, and two very
  6738. # different situations arrive here needing opposite answers.
  6739. #
  6740. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  6741. # snippet may have ejected the plate — the scene in front of the camera
  6742. # is no longer the finished print, and no amount of moving the plate
  6743. # brings it back. Use the banked in-print frame instead.
  6744. #
  6745. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  6746. # than the camera frames well, and the toolhead is parked out of the
  6747. # way. That is the *best* moment available on firmware that never emits
  6748. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  6749. # back. Preferring the bank here unconditionally, as this code used to,
  6750. # is what shipped a mid-print photo with the toolhead over the part.
  6751. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  6752. banked = _inprint_frame_bank.get(printer_id)
  6753. if banked:
  6754. frame_bytes = banked
  6755. frame_already_rotated = True
  6756. logger.info(
  6757. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  6758. "frame (%d bytes) instead of a post-swap live grab",
  6759. len(banked),
  6760. )
  6761. else:
  6762. logger.warning(
  6763. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  6764. "in-print bank is empty — falling back to a live grab, which may show a "
  6765. "swapped or empty plate",
  6766. printer_id,
  6767. )
  6768. # `restore_max_z` is set only once the plate is actually up, because the
  6769. # `finally` reads it to decide whether it owes a move back down.
  6770. #
  6771. # Never on a print whose End G-code Bambuddy injected, even when the bank
  6772. # came up empty above: that machine may have just ejected its plate, and
  6773. # driving Z into whatever a swap mechanism is doing is not a risk worth
  6774. # taking for a photo of a bed we already know may be bare.
  6775. if (
  6776. frame_bytes is None
  6777. and trigger == "finish_state"
  6778. and restore_plate_enabled
  6779. and not print_dispatch_context.end_gcode_injected(printer_id)
  6780. ):
  6781. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  6782. if wants_restore is None:
  6783. logger.info(
  6784. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  6785. printer_id,
  6786. )
  6787. elif await _plate_restore_is_blocked_by_queue(printer_id):
  6788. logger.info(
  6789. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  6790. printer_id,
  6791. )
  6792. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  6793. restore_max_z = wants_restore
  6794. # Chamber light for the live capture below (#1655). The banked frame
  6795. # above was taken without it, like every in-print bank.
  6796. async with camera_light(printer if frame_bytes is None else None):
  6797. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  6798. from backend.app.api.routes.camera import live_frame_for_capture
  6799. from backend.app.services.external_camera import capture_frame
  6800. # #2707: this used to collide with the live view and fail, which is
  6801. # how finish-photo notifications went out with no image attached.
  6802. # Leaving frame_bytes None keeps the rest of the fallback chain.
  6803. defer, buffered = live_frame_for_capture(printer_id)
  6804. if defer:
  6805. frame_bytes = buffered
  6806. else:
  6807. frame_bytes = await capture_frame(
  6808. printer.external_camera_url,
  6809. printer.external_camera_type or "mjpeg",
  6810. snapshot_url=printer.external_camera_snapshot_url,
  6811. )
  6812. if frame_bytes:
  6813. logger.info(
  6814. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  6815. len(frame_bytes),
  6816. )
  6817. elif frame_bytes is None:
  6818. from backend.app.api.routes.camera import get_buffered_frame
  6819. buffered = get_buffered_frame(printer_id)
  6820. if buffered:
  6821. frame_bytes = buffered
  6822. logger.info(
  6823. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  6824. len(frame_bytes),
  6825. )
  6826. else:
  6827. from backend.app.services.camera import capture_camera_frame_bytes
  6828. frame_bytes = await capture_camera_frame_bytes(
  6829. ip_address=printer.ip_address,
  6830. access_code=printer.access_code,
  6831. model=printer.model,
  6832. timeout=15,
  6833. )
  6834. if frame_bytes:
  6835. logger.info(
  6836. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  6837. len(frame_bytes),
  6838. )
  6839. if frame_bytes:
  6840. if not frame_already_rotated:
  6841. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  6842. _stage22_finish_frames[printer_id] = frame_bytes
  6843. else:
  6844. logger.warning(
  6845. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  6846. printer_id,
  6847. )
  6848. except Exception as e:
  6849. logger.warning(
  6850. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  6851. printer_id,
  6852. e,
  6853. )
  6854. finally:
  6855. # #2547: we raised the plate, so we own lowering it — including when the
  6856. # capture above failed or threw partway through.
  6857. if restore_max_z is not None:
  6858. try:
  6859. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  6860. except Exception as e:
  6861. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6862. # #1790: always unblock the consumer's bounded wait — whether we stored
  6863. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  6864. # dict entry by the consumer doesn't affect signalling.
  6865. producer_done.set()
  6866. def _subtask_name_from_filename(filename: str) -> str:
  6867. """Recover the subtask name a print command would have carried for *filename*.
  6868. The dispatcher derives the printer-facing subtask name from the archive's
  6869. file name, so stripping the extensions back off gives the value MQTT echoes
  6870. on completion. Only the two extensions Bambuddy actually stores are removed,
  6871. and in the order they nest (``.gcode.3mf``), so a model whose own name
  6872. contains a dot -- ``My.Model.3mf`` -- keeps it.
  6873. """
  6874. name = PurePosixPath(filename).name
  6875. for suffix in (".3mf", ".gcode"):
  6876. if name.lower().endswith(suffix):
  6877. name = name[: -len(suffix)]
  6878. return name
  6879. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  6880. """Whether the subtask name is the printed 3MF's own file name.
  6881. A print started from the printer's screen reports the same full name, with
  6882. its extension, as both subtask and file (#3009). A dispatched print reports
  6883. a bare subtask name; one that merely ends in ".3mf" can be a model named
  6884. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  6885. """
  6886. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  6887. return False
  6888. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  6889. # How the printer marks a subtask name it had to cut short. Observed on real
  6890. # hardware at ~100 characters, but the cut-off is not a fixed character count
  6891. # (a name with multibyte characters came back at 98), so match the marker
  6892. # rather than a length.
  6893. _SUBTASK_TRUNCATION_MARKER = "..."
  6894. def _normalise_subtask_name(name: str) -> str:
  6895. """Canonical form for comparing a dispatched name against MQTT's echo.
  6896. The printer does not echo the name back verbatim: it substitutes
  6897. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  6898. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  6899. The 3MF lookup in this module has always known that -- it builds
  6900. space-to-underscore variants of every candidate filename, and its
  6901. directory search normalises both sides before comparing. This exists so
  6902. the completion check reads the same rule from the same place instead of
  6903. growing its own, which is exactly how it came to disagree (#2829).
  6904. A space at either end is substituted too: ``Part .gcode.3mf`` is
  6905. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  6906. are dropped after the substitution so both sides agree (#3241).
  6907. """
  6908. return name.strip().replace(" ", "_").strip("_").casefold()
  6909. def _3mf_files_for_print(paths: list[str], search_term: str) -> list[str]:
  6910. """The 3MF files of the printer's folder listings that are this print's.
  6911. A file of the print's own name wins, in whichever folder. Only without one
  6912. is a file that merely contains the name taken, and then only when it is
  6913. the one such file: "Cube_large.3mf" is not "Cube"'s file, and of several
  6914. candidates none can be told apart. Paths keep the listings' order.
  6915. """
  6916. threemf = [path for path in paths if path.lower().endswith(".3mf")]
  6917. exact = [path for path in threemf if _subtask_names_match(_subtask_name_from_filename(path), search_term)]
  6918. if exact:
  6919. return exact
  6920. term = _normalise_subtask_name(search_term)
  6921. partial = [path for path in threemf if term in _normalise_subtask_name(PurePosixPath(path).name)]
  6922. if len(partial) > 1:
  6923. logging.getLogger(__name__).info(
  6924. "Several 3MF files contain %r and none is named for it: %s", search_term, partial
  6925. )
  6926. return []
  6927. return partial
  6928. def _subtask_names_match(expected: str, observed: str) -> bool:
  6929. """Whether two subtask names describe the same print.
  6930. Beyond the space/underscore substitution, the printer truncates long names
  6931. and marks the cut with ``...``. A truncated echo has to count as a match or
  6932. every print with a long name strands its queue item the same way.
  6933. """
  6934. expected_n = _normalise_subtask_name(expected)
  6935. observed_n = _normalise_subtask_name(observed)
  6936. if expected_n == observed_n:
  6937. return True
  6938. # Either side can be the truncated one: the printer truncates what it
  6939. # echoes, and an archive whose own filename was recorded from a previous
  6940. # truncated echo carries the marker too.
  6941. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  6942. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  6943. continue
  6944. # The full side has lost its edge underscores; a cut that lands right
  6945. # after one keeps it, so drop it here too (#3241). Nothing left before
  6946. # the marker is no evidence of anything, and must not match every name.
  6947. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  6948. if kept and full.startswith(kept):
  6949. return True
  6950. return False
  6951. async def _queue_item_dispatched_name(db, item) -> str:
  6952. """The subtask name *item* was dispatched under, or "" when unknowable.
  6953. A row with no archive, or an archive with no file name, is unverifiable
  6954. rather than wrong; every caller answers that with its permissive branch.
  6955. """
  6956. if item.archive_id is None:
  6957. return ""
  6958. from backend.app.models.archive import PrintArchive
  6959. archive = await db.get(PrintArchive, item.archive_id)
  6960. if archive is None or not archive.filename:
  6961. return ""
  6962. return _subtask_name_from_filename(archive.filename)
  6963. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  6964. """Whether this completion event is plausibly about *item*'s print.
  6965. The caller finds its queue row by printer and ``status='printing'`` alone,
  6966. which is all a completion event gives it -- there is no run identifier in
  6967. the MQTT payload to match on. That makes the lookup indiscriminate: any
  6968. completion delivered for this printer closes whichever row happens to be
  6969. printing, however unrelated. Comparing the subtask name against the archive
  6970. the row was dispatched with costs one primary-key load and rules that out.
  6971. Deliberately permissive: it answers False only on a positive disagreement
  6972. between two names we actually have. A row with no archive, an archive with
  6973. no file name, or an event with no subtask name is unverifiable rather than
  6974. wrong, and refusing those would strand the item in ``printing`` and wedge
  6975. the printer's queue -- a worse failure than the one being prevented.
  6976. """
  6977. observed = (data.get("subtask_name") or "").strip()
  6978. if not observed or item.archive_id is None:
  6979. return True
  6980. from backend.app.models.archive import PrintArchive
  6981. archive = await db.get(PrintArchive, item.archive_id)
  6982. if archive is None or not archive.filename:
  6983. return True
  6984. expected = _subtask_name_from_filename(archive.filename)
  6985. if not expected or _subtask_names_match(expected, observed):
  6986. return True
  6987. logging.getLogger(__name__).warning(
  6988. "Ignoring print completion for queue item %s: it was dispatched as %r "
  6989. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  6990. "printing rather than closing a run this event is not about.",
  6991. item.id,
  6992. expected,
  6993. archive.id,
  6994. archive.filename,
  6995. observed,
  6996. )
  6997. return False
  6998. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  6999. """Spend the 3MF download cache on a still-empty fallback archive.
  7000. ``on_print_complete`` drops the cache as its first act, which deletes the
  7001. file. If the cover endpoint (or anything else) pulled the 3MF while the
  7002. print ran and the archive never got one, this is the last moment those bytes
  7003. exist (#2957).
  7004. """
  7005. logger = logging.getLogger(__name__)
  7006. names = [
  7007. n
  7008. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  7009. if n
  7010. ]
  7011. for name in names:
  7012. try:
  7013. cached = get_cached_3mf(printer_id, name)
  7014. # The print has ended: its completion prices the archive, so no
  7015. # print-start estimate is scheduled to race it.
  7016. if cached and await try_recover_fallback_archive(printer_id, name, cached, price=False):
  7017. return
  7018. except Exception as e:
  7019. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  7020. # Longest the print's end waits for its file to be deleted from the SD card
  7021. _SD_CLEANUP_BUDGET_SECONDS = 45.0
  7022. async def _cleanup_sd_card_after_print(
  7023. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  7024. ) -> None:
  7025. """Delete a finished print's file from the printer's SD card."""
  7026. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  7027. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  7028. # auto-start files found in root on power cycle, causing ghost prints.
  7029. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  7030. try:
  7031. if subtask_name:
  7032. archive_filename: str | None = None
  7033. async with async_session() as db:
  7034. from backend.app.models.archive import PrintArchive
  7035. from backend.app.models.printer import Printer
  7036. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7037. printer = result.scalar_one_or_none()
  7038. if archive_id:
  7039. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  7040. archive_filename = archive_row.scalar_one_or_none()
  7041. if printer:
  7042. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  7043. from backend.app.utils.filename import derive_remote_filename
  7044. # Primary candidate: the exact path the dispatcher uploaded to
  7045. # (derived from archive.filename via the same rule as upload).
  7046. # Without it, a library row that ended up with a doubled
  7047. # .gcode.3mf (#1542) leaves the real file behind because the
  7048. # subtask_name + ext fallbacks below don't match what's on the
  7049. # SD card. Fallbacks remain for archive-less prints (subtask
  7050. # never resolved to an archive) and for older naming variants.
  7051. candidate_paths: list[str] = []
  7052. if archive_filename:
  7053. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  7054. for ext in (".3mf", ".gcode"):
  7055. fallback = f"/{subtask_name}{ext}"
  7056. if fallback not in candidate_paths:
  7057. candidate_paths.append(fallback)
  7058. # Three outcomes track across all candidates so the final log
  7059. # line reflects what actually happened. The A1 in #1721 always
  7060. # ends here with ``any_not_found=True`` and the others False
  7061. # — its firmware auto-cleans the SD card before our cleanup
  7062. # runs, every candidate FTP-DELE returns 550, and the old
  7063. # code burned 3 retries × 2 s × 3 candidates per print
  7064. # logging a misleading "may linger" WARNING on a successful
  7065. # print.
  7066. any_deleted = False
  7067. any_real_failure = False
  7068. any_not_found = False
  7069. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  7070. for remote_path in candidate_paths:
  7071. if PurePosixPath(remote_path).name.lower() in files_in_use:
  7072. logger.info(
  7073. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  7074. remote_path,
  7075. printer.name,
  7076. )
  7077. continue
  7078. # Retry only the FAILED case — 550 NOT_FOUND will never
  7079. # recover by waiting, so a "file isn't here" answer
  7080. # advances immediately to the next candidate without
  7081. # consuming the retry budget.
  7082. for attempt in range(1, 4):
  7083. try:
  7084. delete_result = await delete_file_async(
  7085. printer.ip_address,
  7086. printer.access_code,
  7087. remote_path,
  7088. printer_model=printer.model,
  7089. )
  7090. except Exception as e:
  7091. delete_result = DeleteResult.FAILED
  7092. logger.warning(
  7093. "SD card cleanup attempt %d/3 raised for %s: %s",
  7094. attempt,
  7095. remote_path,
  7096. e,
  7097. )
  7098. if delete_result == DeleteResult.DELETED:
  7099. any_deleted = True
  7100. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  7101. break
  7102. if delete_result == DeleteResult.NOT_FOUND:
  7103. any_not_found = True
  7104. break # 550 will not recover; try next candidate
  7105. # FAILED: real error — retry with backoff, then give up
  7106. if attempt < 3:
  7107. await asyncio.sleep(2)
  7108. else:
  7109. any_real_failure = True
  7110. logger.warning(
  7111. "SD card cleanup failed after 3 attempts for %s "
  7112. "(network/auth/transient error — file may linger on SD card)",
  7113. remote_path,
  7114. )
  7115. if not any_deleted and not any_real_failure and any_not_found:
  7116. # Every candidate said "not here." Either the printer
  7117. # firmware swept the SD card itself (common on A1) or the
  7118. # dispatcher's upload path doesn't match our candidate
  7119. # rule. Either way: nothing to clean up, no warning.
  7120. logger.debug(
  7121. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  7122. "(printer likely self-cleaned)",
  7123. printer.name,
  7124. )
  7125. except Exception as e:
  7126. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  7127. async def on_print_complete(printer_id: int, data: dict):
  7128. """Handle print completion - update the archive status."""
  7129. import time
  7130. logger = logging.getLogger(__name__)
  7131. start_time = time.time()
  7132. def log_timing(section: str):
  7133. elapsed = time.time() - start_time
  7134. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  7135. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  7136. # A kill-switch stop sends its provider notification immediately. Keep the
  7137. # task so the later notification path can await it and avoid a duplicate;
  7138. # if that immediate attempt failed, the regular completion path retries.
  7139. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  7140. # Last chance before the bytes go: if this print's archive is still an empty
  7141. # fallback and something downloaded the 3MF while it ran, fill the archive in
  7142. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  7143. # below deletes the file (#2957).
  7144. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  7145. # A pending cool-off retry has nothing left to recover for — the cache is
  7146. # about to be dropped and the print is over.
  7147. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  7148. if retry_task and not retry_task.done():
  7149. retry_task.cancel()
  7150. # Drop the 3MF download cache for this printer (#972). The print is over,
  7151. # nothing else legitimately needs the bytes; keeping them would only risk
  7152. # handing a stale file to the next print if it reuses the same name.
  7153. clear_3mf_cache(printer_id)
  7154. try:
  7155. ws_data = {
  7156. "status": data.get("status"),
  7157. "filename": data.get("filename"),
  7158. "subtask_name": data.get("subtask_name"),
  7159. "timelapse_was_active": data.get("timelapse_was_active"),
  7160. }
  7161. await ws_manager.send_print_complete(printer_id, ws_data)
  7162. log_timing("WebSocket send_print_complete")
  7163. except Exception as e:
  7164. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  7165. # Capture user info before clearing (needed for print log entry)
  7166. _print_user_info = printer_manager.get_current_print_user(printer_id)
  7167. # Clear current print user tracking (Issue #206)
  7168. printer_manager.clear_current_print_user(printer_id)
  7169. # If the user explicitly stopped this print from the queue UI the printer will
  7170. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  7171. # correct "print stopped" notification/email is sent instead of a failure alert.
  7172. _raw_status = data.get("status", "completed")
  7173. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  7174. logger.info(
  7175. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  7176. _raw_status,
  7177. printer_id,
  7178. )
  7179. data = {**data, "status": "cancelled"}
  7180. elif printer_id in _kill_switch_stopped and _raw_status in ("failed", "aborted"):
  7181. logger.info(
  7182. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (stopped by the printer kill switch)",
  7183. _raw_status,
  7184. printer_id,
  7185. )
  7186. data = {**data, "status": "cancelled", "_kill_switch": True}
  7187. _user_stopped_printers.discard(printer_id)
  7188. _kill_switch_stopped.discard(printer_id)
  7189. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  7190. # may have left material on the bed: a user can cancel ten hours into a
  7191. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  7192. # touchscreen-stop reports `aborted` rather than `cancelled` because
  7193. # `_user_stopped_printers` is only populated when the user stops via the
  7194. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  7195. # which auto-dispatched the next queued print onto a fouled bed two seconds
  7196. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  7197. # Auto Off power cycles and Bambuddy restarts.
  7198. try:
  7199. notify_live_activities.print_finished(printer_id, data)
  7200. except Exception:
  7201. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  7202. _final_status = data.get("status", "completed")
  7203. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  7204. printer_manager.set_awaiting_plate_clear(printer_id, True)
  7205. # MQTT relay - publish print complete
  7206. try:
  7207. printer_info = printer_manager.get_printer(printer_id)
  7208. if printer_info:
  7209. await mqtt_relay.on_print_complete(
  7210. printer_id,
  7211. printer_info.name,
  7212. printer_info.serial_number,
  7213. data.get("filename", ""),
  7214. data.get("subtask_name", ""),
  7215. data.get("status", "completed"),
  7216. )
  7217. except Exception:
  7218. pass # Don't fail print complete callback if MQTT fails
  7219. filename = data.get("filename", "")
  7220. subtask_name = data.get("subtask_name", "")
  7221. if not filename and not subtask_name:
  7222. logger.warning("Print complete without filename or subtask_name")
  7223. return
  7224. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  7225. # Build list of possible keys to try (matching how they were registered in on_print_start)
  7226. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  7227. # Find the archive for this print
  7228. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  7229. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  7230. archive_id = None
  7231. for key in possible_keys:
  7232. archive_id = _active_prints.pop(key, None)
  7233. if archive_id:
  7234. _owned_print_archive_ids.discard(archive_id)
  7235. logger.info("Found archive %s with key %s", archive_id, key)
  7236. # Also clean up any other keys pointing to this archive
  7237. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  7238. for k in keys_to_remove:
  7239. _active_prints.pop(k, None)
  7240. break
  7241. # The archive bound when the print started, before the name search below.
  7242. # Only this one may give the finish-photo plate restore a height (#3240):
  7243. # the search matches names by substring.
  7244. bound_archive_id = archive_id
  7245. if not archive_id:
  7246. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  7247. async with async_session() as db:
  7248. from backend.app.models.archive import PrintArchive
  7249. # Try matching by subtask_name (stored as print_name) first. The
  7250. # same name rule as the queue's completion check: a name inside
  7251. # another ("Clip" in "Cable Clip") is a different print, and the
  7252. # printer's underscores for spaces and truncation still match.
  7253. if subtask_name:
  7254. printing = await db.scalars(
  7255. select(PrintArchive)
  7256. .where(PrintArchive.printer_id == printer_id)
  7257. .where(PrintArchive.status == "printing")
  7258. .order_by(PrintArchive.created_at.desc())
  7259. )
  7260. # A print started from the printer's screen reports its file
  7261. # name, extensions included, as the subtask (#3009).
  7262. reported = {subtask_name, _subtask_name_from_filename(subtask_name)}
  7263. archive = next(
  7264. (
  7265. candidate
  7266. for candidate in printing
  7267. if any(
  7268. (candidate.print_name and _subtask_names_match(candidate.print_name, name))
  7269. or (
  7270. candidate.filename
  7271. and _subtask_names_match(_subtask_name_from_filename(candidate.filename), name)
  7272. )
  7273. for name in reported
  7274. )
  7275. ),
  7276. None,
  7277. )
  7278. if archive:
  7279. archive_id = archive.id
  7280. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  7281. # Also try by filename
  7282. if not archive_id and filename:
  7283. result = await db.execute(
  7284. select(PrintArchive)
  7285. .where(PrintArchive.printer_id == printer_id)
  7286. .where(PrintArchive.filename == filename)
  7287. .where(PrintArchive.status == "printing")
  7288. .order_by(PrintArchive.created_at.desc())
  7289. .limit(1)
  7290. )
  7291. archive = result.scalar_one_or_none()
  7292. if archive:
  7293. archive_id = archive.id
  7294. # Bounded: a printer whose FTP hangs on DELE took up to 3 candidates x 3
  7295. # attempts x a 60 s timeout, about nine minutes, before the queue item was
  7296. # closed below. The stranded-job closer gives up after five and closed it
  7297. # first, so the job's auto-off and its billing never ran. Inline rather
  7298. # than in the background, so the next job of the same file isn't released
  7299. # (and uploaded under the name being deleted) while the cleanup still
  7300. # works on it. A delete already sent may still finish in its FTP thread
  7301. # after the cutoff, as one past delete_file_async's own timeout always did.
  7302. try:
  7303. await asyncio.wait_for(
  7304. _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger),
  7305. timeout=_SD_CLEANUP_BUDGET_SECONDS,
  7306. )
  7307. except TimeoutError:
  7308. logger.warning(
  7309. "SD card cleanup on printer %s took over %ss; leaving the file there and closing the print",
  7310. printer_id,
  7311. _SD_CLEANUP_BUDGET_SECONDS,
  7312. )
  7313. log_timing("SD card cleanup")
  7314. # Update queue item status early — must run before the archive_id early-return
  7315. # so queue items don't get stuck in "printing" when archive lookup fails.
  7316. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  7317. queue_item_id = None
  7318. billing_run_id: str | None = None
  7319. billing_user_id: int | None = None
  7320. billing_cost_center_id: int | None = None
  7321. billing_plate_id: int | None = None
  7322. queue_status = None
  7323. queue_auto_off = False
  7324. try:
  7325. from backend.app.core.database import run_with_retry
  7326. from backend.app.models.print_queue import PrintQueueItem
  7327. async def _update_queue_status(db):
  7328. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  7329. nonlocal queue_item_id, queue_status, queue_auto_off
  7330. result = await db.execute(
  7331. select(PrintQueueItem)
  7332. .where(PrintQueueItem.printer_id == printer_id)
  7333. .where(PrintQueueItem.status == "printing")
  7334. )
  7335. printing_items = list(result.scalars().all())
  7336. if len(printing_items) > 1:
  7337. logger.warning(
  7338. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  7339. printer_id,
  7340. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  7341. )
  7342. item = printing_items[0] if printing_items else None
  7343. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  7344. return
  7345. if item:
  7346. queue_status = data.get("status", "completed")
  7347. # MQTT sends "aborted" for cancelled prints; normalise to
  7348. # "cancelled" so it matches the queue schema Literal.
  7349. if queue_status == "aborted":
  7350. queue_status = "cancelled"
  7351. item.status = queue_status
  7352. item.completed_at = datetime.now(timezone.utc)
  7353. if queue_status == "failed" and not item.error_message:
  7354. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  7355. # Bump usage counters on the source library file so admins can
  7356. # sort by "last printed" and (eventually) auto-purge stale
  7357. # files — #1008.
  7358. await _bump_library_file_usage_if_completed(db, item, queue_status)
  7359. await db.commit()
  7360. queue_item_id = item.id
  7361. billing_run_id = item.billing_run_id
  7362. billing_user_id = item.created_by_id
  7363. billing_cost_center_id = item.cost_center_id
  7364. billing_plate_id = item.plate_id
  7365. queue_auto_off = item.auto_off_after
  7366. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  7367. await run_with_retry(_update_queue_status, label="queue status update")
  7368. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  7369. # their own sessions and have their own error handling — no retry needed.
  7370. if queue_item_id is not None:
  7371. # Batch orders (#342): this run may have been the last one an order
  7372. # owed. Re-evaluate here rather than lazily on read, so a finished
  7373. # order reports itself complete without someone opening the page.
  7374. try:
  7375. from backend.app.services.print_batch import refresh_batch_status_for_item
  7376. async with async_session() as db:
  7377. await refresh_batch_status_for_item(db, queue_item_id)
  7378. await db.commit()
  7379. except Exception as e:
  7380. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  7381. # MQTT relay - publish queue job completed
  7382. try:
  7383. printer_info = printer_manager.get_printer(printer_id)
  7384. await mqtt_relay.on_queue_job_completed(
  7385. job_id=queue_item_id,
  7386. filename=filename or subtask_name,
  7387. printer_id=printer_id,
  7388. printer_name=printer_info.name if printer_info else "Unknown",
  7389. status=queue_status,
  7390. )
  7391. except Exception:
  7392. pass # Don't fail if MQTT fails
  7393. # Check if queue is now empty and send notification
  7394. try:
  7395. from sqlalchemy import func as sa_func
  7396. async with async_session() as db:
  7397. count_result = await db.execute(
  7398. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  7399. )
  7400. pending_count = count_result.scalar() or 0
  7401. if pending_count == 0:
  7402. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  7403. completed_result = await db.execute(
  7404. select(sa_func.count(PrintQueueItem.id)).where(
  7405. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  7406. PrintQueueItem.completed_at >= today_start,
  7407. )
  7408. )
  7409. completed_count = completed_result.scalar() or 1
  7410. await notification_service.on_queue_completed(
  7411. completed_count=completed_count,
  7412. db=db,
  7413. )
  7414. except Exception:
  7415. pass # Don't fail if notification fails
  7416. # Handle auto_off_after - power off printer if the queue item opted
  7417. # in. Delegates to the smart-plug manager so the off honours each
  7418. # plug's configured strategy (time delay or temperature threshold),
  7419. # is cancelled if the printer starts printing again, and never cuts
  7420. # power on a loaded print (#1890). Previously an inline block here
  7421. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  7422. # timeout regardless of print state — cutting a touchscreen reprint.
  7423. if queue_auto_off:
  7424. try:
  7425. async with async_session() as db:
  7426. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  7427. except Exception as e:
  7428. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  7429. except Exception as e:
  7430. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  7431. log_timing("Queue item update")
  7432. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  7433. # Must run before archive_id early-return so it fires for all prints (including
  7434. # prints started from BambuStudio/touchscreen that have no archive).
  7435. if data.get("status") == "completed":
  7436. try:
  7437. from backend.app.api.routes.settings import get_setting
  7438. async with async_session() as db:
  7439. threshold_str = await get_setting(db, "bed_cooled_threshold")
  7440. threshold = float(threshold_str) if threshold_str else 35.0
  7441. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  7442. async with async_session() as db:
  7443. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  7444. if providers:
  7445. _bed_cool_waiters[printer_id] = {
  7446. "threshold": threshold,
  7447. "filename": filename or subtask_name or "",
  7448. "registered_at": time.time(),
  7449. }
  7450. logger.info(
  7451. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  7452. printer_id,
  7453. threshold,
  7454. )
  7455. else:
  7456. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  7457. except Exception as e:
  7458. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  7459. # Capture the slicer estimate before usage tracking runs. The tracker may
  7460. # update archive.cost with this run's measured cost; billing partial runs
  7461. # against that already-partial value would discount the charge twice.
  7462. billing_planned_grams: float | None = None
  7463. billing_base_cost: float | None = None
  7464. if archive_id:
  7465. try:
  7466. async with async_session() as db:
  7467. from backend.app.models.archive import PrintArchive
  7468. billing_archive = await db.get(PrintArchive, archive_id)
  7469. if billing_archive:
  7470. billing_path = (
  7471. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  7472. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7473. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  7474. billing_archive,
  7475. billing_path,
  7476. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  7477. )
  7478. except Exception as e:
  7479. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  7480. # --- Track filament consumption (must run before archive_id early-return so usage
  7481. # is recorded even when auto-archive is disabled) ---
  7482. usage_results: list[dict] = []
  7483. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  7484. stored_ams_mapping = data.get("ams_mapping")
  7485. # Fallback to _print_ams_mappings for queue/reprint (set before print starts).
  7486. # Drained either way, like the plate below: left over, it would be read by
  7487. # the archive's next run, dispatched without a mapping.
  7488. registered_ams_mapping = _print_ams_mappings.pop(archive_id, None) if archive_id else None
  7489. if not stored_ams_mapping:
  7490. stored_ams_mapping = registered_ams_mapping
  7491. # Always drain the plate_id register on completion — the session already
  7492. # consumed it at print-start injection; leaving it would leak into the next
  7493. # print on the same archive_id (rare but possible with reprints) (#1697).
  7494. # Capture the popped value so the completion notification can scope the
  7495. # archive-level (summed-across-plates per #1593) filament + time totals
  7496. # down to the single plate that was actually printed (#1785).
  7497. notify_plate_id: int | None = None
  7498. if archive_id:
  7499. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  7500. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  7501. try:
  7502. async with async_session() as db:
  7503. from backend.app.api.routes.settings import get_setting
  7504. _spoolman_on = await get_setting(db, "spoolman_enabled")
  7505. if not _spoolman_on or _spoolman_on.lower() != "true":
  7506. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  7507. async with async_session() as db:
  7508. usage_results = await usage_on_print_complete(
  7509. printer_id,
  7510. data,
  7511. printer_manager,
  7512. db,
  7513. archive_id=archive_id,
  7514. ams_mapping=stored_ams_mapping,
  7515. )
  7516. if usage_results:
  7517. await ws_manager.broadcast(
  7518. {
  7519. "type": "spool_usage_logged",
  7520. "printer_id": printer_id,
  7521. "usage": usage_results,
  7522. }
  7523. )
  7524. log_timing("Usage tracker")
  7525. except Exception as e:
  7526. logger.warning("Usage tracker on_print_complete failed: %s", e)
  7527. # Drop the print-start context unconditionally — the Spoolman branch above
  7528. # skips the internal tracker entirely, so nothing else would clear what
  7529. # print start captured, and a row surviving its print would be restored
  7530. # onto the next one after a restart.
  7531. try:
  7532. from backend.app.services.usage_tracker import discard_session
  7533. async with async_session() as db:
  7534. await discard_session(db, printer_id)
  7535. except Exception as e:
  7536. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  7537. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  7538. # A partial run's cost from the Spoolman spools it was charged to; the
  7539. # built-in inventory's comes in usage_results.
  7540. spoolman_run_cost: float | None = None
  7541. if archive_id:
  7542. if data.get("status") == "completed":
  7543. try:
  7544. await _report_spoolman_usage(printer_id, archive_id)
  7545. log_timing("Spoolman usage report")
  7546. except Exception as e:
  7547. logger.warning("Spoolman usage reporting failed: %s", e)
  7548. else:
  7549. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  7550. try:
  7551. async with async_session() as db:
  7552. spoolman_run_cost = await _cleanup_spoolman_tracking(
  7553. printer_id,
  7554. archive_id,
  7555. db,
  7556. last_layer_num=data.get("last_layer_num"),
  7557. last_progress=data.get("last_progress"),
  7558. )
  7559. except Exception as e:
  7560. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  7561. await _release_archived_spoolman_slots(printer_id)
  7562. log_timing("Filament usage tracking")
  7563. if not archive_id:
  7564. # The printer's own calibration run has no archive by design, so this
  7565. # arrives here every time one finishes. Returning before the no-archive
  7566. # notification keeps a calibration from being announced as a finished
  7567. # print. Everything above this point has already run — the plate-clear
  7568. # gate, the queue reconciliation, the SD-card cleanup — so only the
  7569. # notification is skipped.
  7570. if is_internal_printer_job(filename, subtask_name):
  7571. logger.info(
  7572. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  7573. filename,
  7574. subtask_name,
  7575. )
  7576. return
  7577. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  7578. # Still send print-complete/failed/stopped notifications even without an archive.
  7579. # Try to enrich with queue/library-file data so user-specific emails work too.
  7580. async def _notify_no_archive():
  7581. try:
  7582. async with async_session() as db:
  7583. from backend.app.models.library import LibraryFile
  7584. from backend.app.models.print_queue import PrintQueueItem
  7585. from backend.app.models.printer import Printer
  7586. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7587. printer_obj = result.scalar_one_or_none()
  7588. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  7589. # Only the queue item this completion itself closed (the
  7590. # reconciliation above, which checks the run belongs to it).
  7591. # A print started outside Bambuddy closed none, and must not
  7592. # borrow an earlier job's owner, email or times.
  7593. no_archive_data: dict | None = None
  7594. try:
  7595. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  7596. if queue_item:
  7597. no_archive_data = {"created_by_id": queue_item.created_by_id}
  7598. # How long it really ran, as the archive path reports it (#1198).
  7599. started = to_naive_utc(queue_item.started_at)
  7600. ended = to_naive_utc(queue_item.completed_at)
  7601. if started and ended and (ended - started).total_seconds() > 0:
  7602. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  7603. # Estimated time: the queue item caches it from its
  7604. # archive or library file; otherwise read the library
  7605. # file's metadata (LibraryFile has no column for it).
  7606. if queue_item.print_time_seconds:
  7607. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  7608. elif queue_item.library_file_id:
  7609. lib_result = await db.execute(
  7610. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  7611. )
  7612. lib_file = lib_result.scalar_one_or_none()
  7613. estimate = (
  7614. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  7615. )
  7616. if estimate:
  7617. no_archive_data["print_time_seconds"] = estimate
  7618. except Exception as lookup_err:
  7619. logger.debug(
  7620. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  7621. )
  7622. # Enrich with usage tracker results (captured in enclosing scope)
  7623. if usage_results:
  7624. if no_archive_data is None:
  7625. no_archive_data = {}
  7626. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7627. if total_from_usage > 0:
  7628. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7629. no_archive_data["usage_results"] = usage_results
  7630. # Try MQTT remaining_time for print duration when no queue/library data
  7631. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  7632. mqtt_remaining = data.get("remaining_time")
  7633. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  7634. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  7635. ps = data.get("status", "completed")
  7636. logger.info(
  7637. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  7638. )
  7639. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7640. await notification_service.on_print_complete(
  7641. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  7642. )
  7643. else:
  7644. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7645. # Send user-specific email if we have a created_by_id
  7646. if no_archive_data and no_archive_data.get("created_by_id"):
  7647. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7648. await _dispatch_user_print_email(
  7649. ps,
  7650. no_archive_data["created_by_id"],
  7651. p_name,
  7652. raw_filename,
  7653. db,
  7654. )
  7655. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  7656. except Exception as e:
  7657. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  7658. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  7659. return
  7660. log_timing("Archive lookup")
  7661. # Update archive status
  7662. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  7663. try:
  7664. async with async_session() as db:
  7665. service = ArchiveService(db)
  7666. status = data.get("status", "completed")
  7667. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  7668. if hms_errors:
  7669. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  7670. failure_reason = derive_failure_reason(status, hms_errors)
  7671. if data.get("_reconciled"):
  7672. # A reconciled completion closes out a stale archive at
  7673. # reconnect — it is not a user action, so don't mislabel it
  7674. # "userCancelled". It shares the stale-cleanup path's key
  7675. # (issue #2974) and records that the real end time is unknown,
  7676. # which is also why its logged duration is 0 (#2592).
  7677. failure_reason = "noStatusUpdate"
  7678. elif data.get("_kill_switch"):
  7679. # Not the user's cancel: the kill switch stopped a print that did
  7680. # not come from Bambuddy.
  7681. failure_reason = "killSwitch"
  7682. if failure_reason:
  7683. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  7684. elif status == "failed" and hms_errors:
  7685. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  7686. await service.update_archive_status(
  7687. archive_id,
  7688. status=status,
  7689. completed_at=(
  7690. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  7691. ),
  7692. failure_reason=failure_reason,
  7693. )
  7694. logger.info(
  7695. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  7696. )
  7697. await ws_manager.send_archive_updated(
  7698. {
  7699. "id": archive_id,
  7700. "status": status,
  7701. }
  7702. )
  7703. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  7704. # MQTT relay - publish archive updated
  7705. try:
  7706. await mqtt_relay.on_archive_updated(
  7707. archive_id=archive_id,
  7708. print_name=filename or subtask_name,
  7709. status=status,
  7710. )
  7711. except Exception:
  7712. pass # Don't fail if MQTT fails
  7713. except Exception as e:
  7714. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  7715. # Continue with other operations even if archive update fails
  7716. log_timing("Archive status update")
  7717. # Apply finance wallet charge or release reservations once. For all partial
  7718. # terminal states (failed, aborted at the printer display, or cancelled via
  7719. # Bambuddy) use this run's measured spool delta, falling back to the last
  7720. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  7721. # estimate and therefore cannot represent an interrupted run.
  7722. try:
  7723. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  7724. async with async_session() as db:
  7725. from backend.app.models.archive import PrintArchive
  7726. from backend.app.services.finance_billing import apply_print_charge_for_archive
  7727. archive = await db.get(PrintArchive, archive_id)
  7728. if archive and billing_run_id is None:
  7729. billing_run_id = getattr(archive, "billing_run_id", None)
  7730. if archive and archive.created_by_id is None and _print_user_info:
  7731. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  7732. await db.flush()
  7733. run_status = data.get("status", "completed")
  7734. last_progress = data.get("last_progress")
  7735. if last_progress is None:
  7736. last_progress = data.get("progress")
  7737. actual_run_grams = _compute_run_filament_grams(
  7738. run_status,
  7739. billing_planned_grams,
  7740. last_progress,
  7741. usage_results,
  7742. )
  7743. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  7744. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  7745. charged = await apply_print_charge_for_archive(
  7746. db,
  7747. archive_id,
  7748. charged_user_id=billing_user_id,
  7749. cost_center_id=(
  7750. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  7751. ),
  7752. print_queue_id=queue_item_id,
  7753. print_run_id=billing_run_id,
  7754. base_cost_override=billing_base_cost,
  7755. filament_usage=filament_usage,
  7756. )
  7757. await db.commit()
  7758. if charged:
  7759. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  7760. except Exception as e:
  7761. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  7762. printer_info = printer_manager.get_printer(printer_id)
  7763. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7764. billing_filename = filename or subtask_name or "Unknown"
  7765. billing_error = str(e)
  7766. try:
  7767. await ws_manager.broadcast(
  7768. {
  7769. "type": "billing_charge_failed",
  7770. "printer_id": printer_id,
  7771. "printer_name": billing_printer_name,
  7772. "filename": billing_filename,
  7773. "archive_id": archive_id,
  7774. }
  7775. )
  7776. except Exception as notification_error:
  7777. logger.error(
  7778. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  7779. archive_id,
  7780. notification_error,
  7781. )
  7782. async def _notify_billing_charge_failed() -> None:
  7783. try:
  7784. async with async_session() as notification_db:
  7785. await notification_service.on_billing_charge_failed(
  7786. printer_id,
  7787. billing_printer_name,
  7788. billing_filename,
  7789. archive_id,
  7790. billing_error,
  7791. notification_db,
  7792. )
  7793. except Exception as provider_error:
  7794. logger.error(
  7795. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  7796. archive_id,
  7797. provider_error,
  7798. exc_info=True,
  7799. )
  7800. spawn_background_task(
  7801. _notify_billing_charge_failed(),
  7802. name=f"billing-charge-failed-{archive_id}",
  7803. )
  7804. log_timing("Finance charge update")
  7805. # Write independent print log entry (separate table, never touches archives)
  7806. try:
  7807. async with async_session() as db:
  7808. from backend.app.models.archive import PrintArchive
  7809. from backend.app.services.print_log import record_archive_wear, write_log_entry
  7810. archive = await db.get(PrintArchive, archive_id)
  7811. if archive:
  7812. # Back-fill created_by_id on reprint (#730): reprint reuses the
  7813. # source archive row rather than creating a new one, so an
  7814. # archive that was auto-created from a printer-initiated
  7815. # print (created_by_id=NULL) would otherwise stay unattributed
  7816. # forever. When we have a print-session user AND the archive
  7817. # has no attribution yet, credit the current user. Never
  7818. # overwrite an existing attribution — the original uploader
  7819. # keeps ownership.
  7820. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  7821. if archive.created_by_id is None and _print_user_id is not None:
  7822. archive.created_by_id = _print_user_id
  7823. p_info = printer_manager.get_printer(printer_id)
  7824. # Per-run actuals — written to PrintLogEntry so stats reflect
  7825. # what THIS print actually used, not the source archive's
  7826. # first-run values (#1378). Helper handles the partial-print
  7827. # math (failed / cancelled / stopped get scaled to progress
  7828. # or to tracked spool deltas).
  7829. _run_status = data.get("status", "completed")
  7830. # #2614: scope the per-run estimate to the printed plate. For a
  7831. # multi-plate 3MF dispatched one plate at a time, the archive's
  7832. # filament/cost are the whole-file totals; the PrintLogEntry must
  7833. # reflect only this plate. No effect on single-plate archives (the
  7834. # plate estimate equals the whole-file value) or on the tracker
  7835. # path (measured spool deltas win in _compute_run_filament_grams).
  7836. _est_full_path = (
  7837. app_settings.base_dir / archive.file_path if archive.file_path else None
  7838. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7839. # The plate that printed, as billing reads it: a reprint of
  7840. # another plate must not log the archive's first plate.
  7841. _est_grams, _est_cost = _plate_scoped_run_estimate(
  7842. archive,
  7843. _est_full_path,
  7844. billing_plate_id if billing_plate_id is not None else notify_plate_id,
  7845. )
  7846. _run_grams = _compute_run_filament_grams(
  7847. _run_status,
  7848. _est_grams,
  7849. data.get("last_progress", data.get("progress")),
  7850. usage_results,
  7851. )
  7852. # Per-run cost — prefer usage_results sum. For partial prints
  7853. # we deliberately skip the topup-to-estimate logic in
  7854. # usage_tracker (which assumes the print completed); the raw
  7855. # tracked-spool sum is closer to what THIS run actually cost.
  7856. _run_cost: float | None = None
  7857. if usage_results:
  7858. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  7859. if _run_cost is None and _run_status != "completed":
  7860. _run_cost = spoolman_run_cost
  7861. if _run_cost is None and _run_status == "completed":
  7862. _run_cost = _est_cost
  7863. from backend.app.models.printer import Printer as _Printer
  7864. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  7865. run_entry = await write_log_entry(
  7866. db,
  7867. archive_id=archive.id,
  7868. # Captured by _update_queue_status above; None for
  7869. # printer-initiated prints with no queue row. Batch
  7870. # cost/energy roll-up joins on it (#342).
  7871. queue_item_id=queue_item_id,
  7872. status=_run_status,
  7873. print_name=archive.print_name,
  7874. printer_name=p_info.name if p_info else None,
  7875. printer_id=printer_id,
  7876. started_at=archive.started_at,
  7877. completed_at=archive.completed_at,
  7878. filament_type=archive.filament_type,
  7879. filament_color=archive.filament_color,
  7880. filament_used_grams=_run_grams,
  7881. cost=_run_cost,
  7882. wear_cost_per_hour=_wear_rate,
  7883. failure_reason=archive.failure_reason,
  7884. thumbnail_path=archive.thumbnail_path,
  7885. created_by_id=archive.created_by_id,
  7886. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  7887. # Reconciled completions have an unknown real end time —
  7888. # log 0 duration instead of the whole disconnect gap (#2592).
  7889. reconciled=bool(data.get("_reconciled")),
  7890. )
  7891. await record_archive_wear(db, archive, run_entry)
  7892. await db.commit()
  7893. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  7894. except Exception as e:
  7895. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  7896. log_timing("Print log entry")
  7897. # Run slow operations as background tasks to avoid blocking the event loop
  7898. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  7899. async def _background_energy_calculation():
  7900. """Calculate and save energy usage in background.
  7901. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  7902. backend restart no longer loses per-print energy data).
  7903. """
  7904. try:
  7905. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  7906. async with async_session() as db:
  7907. from backend.app.models.archive import PrintArchive
  7908. archive = await db.get(PrintArchive, archive_id)
  7909. if archive is None:
  7910. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  7911. return
  7912. starting_kwh = archive.energy_start_kwh
  7913. if starting_kwh is None:
  7914. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  7915. return
  7916. candidates = await energy_plug_candidates(db, printer_id)
  7917. if not candidates:
  7918. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  7919. return
  7920. # Same ordering as the start reading, so the delta below is
  7921. # against the counter that produced `starting_kwh` (#2859).
  7922. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  7923. if selected is None:
  7924. logger.warning(
  7925. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  7926. printer_id,
  7927. ", ".join(plug.name for plug in candidates),
  7928. )
  7929. return
  7930. plug, energy = selected
  7931. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  7932. energy_used = round(energy["total"] - starting_kwh, 4)
  7933. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  7934. if energy_used < 0:
  7935. logger.warning(
  7936. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  7937. archive_id,
  7938. starting_kwh,
  7939. energy["total"],
  7940. )
  7941. return
  7942. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  7943. # Each hour of the print at the price of that hour (#1251). If
  7944. # that fails, the last price known, as before, rather than no
  7945. # energy at all. Read first: the session may be unusable after.
  7946. last_price = await stored_price(db)
  7947. try:
  7948. energy_cost_value = round(
  7949. await print_energy_cost(
  7950. db,
  7951. plug_id=archive.energy_start_plug_id,
  7952. start_at=archive.energy_start_at,
  7953. start_kwh=starting_kwh,
  7954. start_price=archive.energy_start_price,
  7955. end_kwh=energy["total"],
  7956. end_plug_id=plug.id,
  7957. price_now=await current_price(db),
  7958. ),
  7959. 3,
  7960. )
  7961. except Exception as e:
  7962. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  7963. energy_cost_value = round(energy_used * last_price, 3)
  7964. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  7965. # reprint doesn't visually clobber the source archive's energy data
  7966. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  7967. from sqlalchemy import func
  7968. from backend.app.models.print_log import PrintLogEntry
  7969. existing_runs = await db.scalar(
  7970. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  7971. )
  7972. if (existing_runs or 0) <= 1:
  7973. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  7974. # we just wrote for THIS print. Either way it's the first run.
  7975. archive.energy_kwh = energy_used
  7976. archive.energy_cost = energy_cost_value
  7977. # Backfill the latest PrintLogEntry for this archive with energy
  7978. # (write_log_entry above ran before this background task completed,
  7979. # so energy fields are still NULL on that row).
  7980. latest_run = await db.execute(
  7981. select(PrintLogEntry)
  7982. .where(PrintLogEntry.archive_id == archive_id)
  7983. .order_by(PrintLogEntry.id.desc())
  7984. .limit(1)
  7985. )
  7986. run_row = latest_run.scalar_one_or_none()
  7987. if run_row is not None:
  7988. run_row.energy_kwh = energy_used
  7989. run_row.energy_cost = energy_cost_value
  7990. await db.commit()
  7991. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  7992. except Exception as e:
  7993. logger.warning("[ENERGY-BG] Failed: %s", e)
  7994. async def _background_finish_photo() -> str | None:
  7995. """Capture finish photo in background. Returns photo filename if captured."""
  7996. # #2547: set once this function has raised the plate itself (the
  7997. # timelapse path, where the moment producer returned without doing it).
  7998. # Declared out here so the `finally` can lower it again no matter where
  7999. # the capture below fails.
  8000. plate_restored_z: float | None = None
  8001. try:
  8002. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  8003. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  8004. # Read phase: settings + printer + archive in a short session, released
  8005. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  8006. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  8007. # tens of seconds; holding this session across it pinned one pooled
  8008. # connection idle-in-transaction per finishing print (issue #2572).
  8009. async with async_session() as db:
  8010. from backend.app.api.routes.settings import get_setting
  8011. from backend.app.models.archive import PrintArchive
  8012. from backend.app.models.printer import Printer
  8013. capture_enabled = await get_setting(db, "capture_finish_photo")
  8014. if capture_enabled is not None and capture_enabled.lower() != "true":
  8015. return None
  8016. if not archive_id:
  8017. return None
  8018. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  8019. archive = (
  8020. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8021. ).scalar_one_or_none()
  8022. if not printer or not archive:
  8023. return None
  8024. import uuid
  8025. from datetime import datetime
  8026. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  8027. if not archive.file_path:
  8028. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  8029. archive_dir = resolve_archive_dir(archive)
  8030. photo_filename = None
  8031. # Prefer the timelapse last-frame source when a timelapse was
  8032. # recording — it captures the moment after the toolhead parks
  8033. # but before the bed drops, which the live-camera grab below
  8034. # would miss (#1397). Skipped for external cameras (those have
  8035. # their own framing and don't see a Bambu timelapse). Only
  8036. # runs when the USER explicitly enabled timelapse for this
  8037. # print — #1721 removed Bambuddy's force-on at dispatch
  8038. # because it caused per-layer nozzle parking on Smooth-mode
  8039. # slicer profiles.
  8040. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  8041. printer.external_camera_enabled and printer.external_camera_url
  8042. )
  8043. timelapse_still_pending = False
  8044. if prefer_timelapse_source:
  8045. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  8046. archive_id=archive_id,
  8047. archive_dir=archive_dir,
  8048. rotation=getattr(printer, "camera_rotation", 0),
  8049. )
  8050. # #1721: replacement framing path — on_finish_photo_moment
  8051. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  8052. # parked, bed not yet dropped) and cached the JPEG bytes in
  8053. # _stage22_finish_frames. Consume them now so the saved photo
  8054. # has the better framing instead of the post-bed-drop angle
  8055. # the live-camera fallback below would give.
  8056. if not photo_filename:
  8057. # #1790: on the FINISH-state fallback path the producer
  8058. # task is dispatched back-to-back with this consumer, so
  8059. # a bare pop would race past with an empty result and
  8060. # the RTSP fallback below would collide with the
  8061. # producer's still-in-flight grab (single-client RTSP
  8062. # on Bambu printers). Wait for the producer to finish
  8063. # or give up before touching the cache.
  8064. #
  8065. # #2547: 20s was enough when the producer only ever grabbed a
  8066. # frame. It now also raises the plate first, which costs the
  8067. # settle window before the grab even starts — so the budget has
  8068. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  8069. # under the notification's own photo wait below.
  8070. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  8071. if in_flight is not None:
  8072. try:
  8073. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  8074. except TimeoutError:
  8075. logger.warning(
  8076. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  8077. printer_id,
  8078. )
  8079. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  8080. if cached_frame:
  8081. # Already rotated by the producer (#2708) — rotating again
  8082. # here would undo the fix on the banked-frame path, whose
  8083. # bytes reach the cache having been rotated once already.
  8084. photos_dir = archive_dir / "photos"
  8085. photos_dir.mkdir(parents=True, exist_ok=True)
  8086. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8087. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8088. photo_path = photos_dir / photo_filename
  8089. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  8090. logger.info(
  8091. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  8092. photo_filename,
  8093. len(cached_frame),
  8094. )
  8095. # #2547: the timelapse path reaches the live grab below whenever the
  8096. # video hasn't landed in time — the documented usual outcome on
  8097. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  8098. # returned early for those prints without raising the plate, so
  8099. # without this the photo that actually ships in the notification is
  8100. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  8101. # asked us to fix. The archive still gets the better video frame
  8102. # later; this is about the image the user is sent.
  8103. #
  8104. # Gated on `timelapse_was_active` precisely because that is the
  8105. # condition under which the producer skipped. On every other path it
  8106. # has already raised and lowered the plate, and repeating that here
  8107. # would be a second pointless round trip.
  8108. if (
  8109. not photo_filename
  8110. and data.get("timelapse_was_active")
  8111. and not print_dispatch_context.end_gcode_injected(printer_id)
  8112. ):
  8113. try:
  8114. async with async_session() as db:
  8115. from backend.app.api.routes.settings import get_setting
  8116. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  8117. if restore_setting is None or restore_setting.lower() == "true":
  8118. max_z = await _max_z_for_current_print(
  8119. printer_id, data, logger, bound_archive_id, notify_plate_id
  8120. )
  8121. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  8122. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  8123. plate_restored_z = max_z
  8124. except Exception as e:
  8125. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  8126. # Fallback chain: external camera → buffered live frame →
  8127. # fresh RTSP capture. Only runs if the timelapse path above
  8128. # didn't already produce a photo.
  8129. # Chamber light for the live capture below (#1655).
  8130. async with camera_light(printer if not photo_filename else None):
  8131. if not photo_filename:
  8132. if printer.external_camera_enabled and printer.external_camera_url:
  8133. logger.info("[PHOTO-BG] Using external camera")
  8134. from backend.app.api.routes.camera import live_frame_for_capture
  8135. from backend.app.services.external_camera import capture_frame
  8136. # #2707: the second half of the finish-photo failure — the
  8137. # pre-capture and this fallback both collided with the live
  8138. # view. None here continues down the fallback chain.
  8139. defer, buffered = live_frame_for_capture(printer_id)
  8140. if defer:
  8141. frame_data = buffered
  8142. else:
  8143. frame_data = await capture_frame(
  8144. printer.external_camera_url,
  8145. printer.external_camera_type or "mjpeg",
  8146. snapshot_url=printer.external_camera_snapshot_url,
  8147. )
  8148. if frame_data:
  8149. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  8150. photos_dir = archive_dir / "photos"
  8151. photos_dir.mkdir(parents=True, exist_ok=True)
  8152. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8153. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8154. photo_path = photos_dir / photo_filename
  8155. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  8156. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  8157. else:
  8158. # Check if camera stream is active - use buffered frame to avoid freeze
  8159. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  8160. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  8161. active_chamber_for_printer = [
  8162. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  8163. ]
  8164. buffered_frame = get_buffered_frame(printer_id)
  8165. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  8166. # Use frame from active stream
  8167. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  8168. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  8169. photos_dir = archive_dir / "photos"
  8170. photos_dir.mkdir(parents=True, exist_ok=True)
  8171. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8172. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8173. photo_path = photos_dir / photo_filename
  8174. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  8175. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  8176. else:
  8177. # No active stream - capture new frame
  8178. from backend.app.services.camera import capture_finish_photo
  8179. photo_filename = await capture_finish_photo(
  8180. printer_id=printer_id,
  8181. ip_address=printer.ip_address,
  8182. access_code=printer.access_code,
  8183. model=printer.model,
  8184. archive_dir=archive_dir,
  8185. rotation=getattr(printer, "camera_rotation", 0),
  8186. )
  8187. # Write phase: attach the photo in a fresh short-lived session.
  8188. if photo_filename:
  8189. async with async_session() as db:
  8190. from backend.app.models.archive import PrintArchive
  8191. arch = await db.get(PrintArchive, archive_id)
  8192. if arch is not None:
  8193. photos = arch.photos or []
  8194. photos.append(photo_filename)
  8195. arch.photos = photos
  8196. await db.commit()
  8197. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  8198. # The short wait above is bounded so a slow printer can't hold up
  8199. # the print-complete notification, which is what the caller is
  8200. # blocking on. When it ran out with the video still on its way,
  8201. # keep waiting off to the side and add the better frame to the
  8202. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  8203. # users, whose videos routinely take minutes to transfer, never get
  8204. # the pre-bed-drop framing this path exists to provide.
  8205. #
  8206. # Spawned here rather than at the point the wait gave up: both this
  8207. # function and the upgrade do a read-modify-write on `photos`, and
  8208. # the live-camera fallback above can take tens of seconds. Starting
  8209. # the upgrade before that write means the two can interleave and one
  8210. # silently drops the other's entry, leaving a JPEG on disk that the
  8211. # gallery never lists.
  8212. if timelapse_still_pending:
  8213. spawn_background_task(
  8214. _upgrade_finish_photo_from_timelapse(
  8215. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  8216. ),
  8217. name=f"finish-photo-upgrade-{archive_id}",
  8218. )
  8219. return photo_filename
  8220. except Exception as e:
  8221. logger.warning("[PHOTO-BG] Failed: %s", e)
  8222. return None
  8223. finally:
  8224. # #2547: we raised the plate, so we owe the move back down — even if
  8225. # the capture in between threw. Otherwise the user finds the print
  8226. # pinned under the nozzle.
  8227. if plate_restored_z is not None:
  8228. try:
  8229. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  8230. except Exception as e:
  8231. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  8232. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  8233. # Photo capture task - result will be used by notifications
  8234. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  8235. log_timing("Background tasks scheduled (energy, photo)")
  8236. # Also run smart plug, notifications, and maintenance as background tasks
  8237. print_status = data.get("status", "completed")
  8238. async def _background_smart_plug():
  8239. """Handle smart plug automation in background."""
  8240. try:
  8241. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  8242. async with async_session() as db:
  8243. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  8244. logger.info("[AUTO-OFF-BG] Completed")
  8245. except Exception as e:
  8246. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  8247. async def _background_notifications(finish_photo_filename: str | None = None):
  8248. """Send print complete notifications in background."""
  8249. try:
  8250. logger.info(
  8251. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  8252. )
  8253. async with async_session() as db:
  8254. from backend.app.models.archive import PrintArchive
  8255. from backend.app.models.printer import Printer
  8256. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8257. printer = result.scalar_one_or_none()
  8258. printer_name = printer.name if printer else f"Printer {printer_id}"
  8259. archive_data = None
  8260. if archive_id:
  8261. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8262. archive = archive_result.scalar_one_or_none()
  8263. if archive:
  8264. # Actual elapsed time from started_at/completed_at when both are
  8265. # populated (every terminal status sets completed_at after #1198).
  8266. # Falls back to None so the notification path can decide whether to
  8267. # render the slicer estimate as a last resort.
  8268. actual_time_seconds = None
  8269. if archive.started_at and archive.completed_at:
  8270. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  8271. if elapsed > 0:
  8272. actual_time_seconds = int(elapsed)
  8273. archive_data = {
  8274. "print_time_seconds": archive.print_time_seconds,
  8275. "actual_time_seconds": actual_time_seconds,
  8276. "actual_filament_grams": archive.filament_used_grams,
  8277. "failure_reason": archive.failure_reason,
  8278. "created_by_id": archive.created_by_id,
  8279. }
  8280. # Scale filament usage for partial prints
  8281. if print_status != "completed" and archive.filament_used_grams:
  8282. progress = data.get("progress") or 0
  8283. scale = _partial_progress_scale(progress)
  8284. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  8285. archive_data["progress"] = progress
  8286. # Pass per-slot data from archive.extra_data
  8287. if archive.extra_data and archive.extra_data.get("filament_slots"):
  8288. slots = archive.extra_data["filament_slots"]
  8289. if print_status != "completed":
  8290. scale = _partial_progress_scale(data.get("progress"))
  8291. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  8292. archive_data["filament_slots"] = slots
  8293. # Scope project-summed totals down to the plate that was
  8294. # actually printed — see _scope_notification_archive_data_to_plate
  8295. # for the why (#1785).
  8296. archive_data = _scope_notification_archive_data_to_plate(
  8297. archive_data,
  8298. archive.file_path,
  8299. notify_plate_id,
  8300. print_status,
  8301. data.get("progress"),
  8302. app_settings.base_dir,
  8303. )
  8304. # Enrich filament_grams from usage_results when archive has no 3MF data
  8305. if not archive_data.get("actual_filament_grams") and usage_results:
  8306. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8307. if total_from_usage > 0:
  8308. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8309. # Pass usage tracker results for AMS slot info in notifications
  8310. if usage_results:
  8311. archive_data["usage_results"] = usage_results
  8312. # Add finish photo URL and image bytes if available
  8313. if finish_photo_filename:
  8314. photo_url, photo_bytes = await _finish_photo_for_notification(
  8315. db, archive, archive_id, finish_photo_filename
  8316. )
  8317. if photo_url:
  8318. archive_data["finish_photo_url"] = photo_url
  8319. if photo_bytes:
  8320. archive_data["image_data"] = photo_bytes
  8321. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8322. await notification_service.on_print_complete(
  8323. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  8324. )
  8325. else:
  8326. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8327. # Post-print outcome confirmation (#1898). Runs in this
  8328. # background task so the finish photo fetched above rides
  8329. # along with the prompt.
  8330. if print_status == "completed" and archive_id:
  8331. await _dispatch_outcome_confirmation_safely(
  8332. db, printer_id, printer_name, data, archive_id, archive_data
  8333. )
  8334. # Send user-specific email notification
  8335. if archive_data:
  8336. created_by_id = archive_data.get("created_by_id")
  8337. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8338. await _dispatch_user_print_email(
  8339. print_status,
  8340. created_by_id,
  8341. printer_name,
  8342. raw_filename,
  8343. db,
  8344. image_data=archive_data.get("image_data"),
  8345. finish_photo_url=archive_data.get("finish_photo_url"),
  8346. )
  8347. logger.info("[NOTIFY-BG] Completed")
  8348. except Exception as e:
  8349. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  8350. async def _background_maintenance_check():
  8351. """Check for maintenance due in background."""
  8352. if print_status != "completed":
  8353. return
  8354. try:
  8355. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  8356. async with async_session() as db:
  8357. from backend.app.models.printer import Printer
  8358. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8359. printer = result.scalar_one_or_none()
  8360. printer_name = printer.name if printer else f"Printer {printer_id}"
  8361. await ensure_default_types(db)
  8362. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  8363. attention = [
  8364. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  8365. ]
  8366. items_needing_attention = [
  8367. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  8368. for item in attention
  8369. ]
  8370. if items_needing_attention:
  8371. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  8372. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  8373. # MQTT relay - publish maintenance alerts
  8374. for item in attention:
  8375. current_value, threshold, unit = maintenance_alert_values(item)
  8376. try:
  8377. await mqtt_relay.on_maintenance_alert(
  8378. printer_id=printer_id,
  8379. printer_name=printer_name,
  8380. maintenance_type=item.maintenance_type_name,
  8381. current_value=current_value,
  8382. threshold=threshold,
  8383. unit=unit,
  8384. )
  8385. except Exception:
  8386. pass # Don't fail if MQTT fails
  8387. else:
  8388. logger.info("[MAINT-BG] Completed (no items need attention)")
  8389. except Exception as e:
  8390. logger.warning("[MAINT-BG] Failed: %s", e)
  8391. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  8392. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  8393. # Notification task waits for photo capture to complete first (with timeout).
  8394. # When a timelapse was recording, photo sourcing polls the per-print
  8395. # timelapse for up to 60s (#1397) — extend the budget so the notification
  8396. # carries the correct bed-up photo instead of falling through to the
  8397. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  8398. #
  8399. # #2547: both budgets now have to cover a plate restore as well.
  8400. #
  8401. # Without timelapse, the wait is on the moment producer, which raises the
  8402. # plate before its grab — so this has to outlast that producer's own budget.
  8403. #
  8404. # With timelapse, the capture polls up to
  8405. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  8406. # falls back to a live grab, which is the case that raises the plate. At the
  8407. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  8408. # restore would have moved the plate for a photo nobody waited for.
  8409. photo_wait_timeout = (
  8410. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  8411. if data.get("timelapse_was_active")
  8412. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  8413. )
  8414. async def _photo_then_notify():
  8415. """Wait for photo capture, then send notification with photo URL."""
  8416. finish_photo = None
  8417. try:
  8418. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  8419. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  8420. except TimeoutError:
  8421. logger.warning(
  8422. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  8423. photo_wait_timeout,
  8424. )
  8425. except Exception as e:
  8426. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  8427. try:
  8428. await _background_notifications(finish_photo)
  8429. except Exception as e:
  8430. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  8431. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  8432. # Stitch external camera layer timelapse if session was active
  8433. print_status = data.get("status", "completed")
  8434. async def _background_layer_timelapse():
  8435. """Stitch layer timelapse and attach to archive."""
  8436. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  8437. try:
  8438. if print_status == "completed":
  8439. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  8440. # The run the frames belong to, read before the stitch: it can
  8441. # take long enough for the archive to start printing again.
  8442. run_started_at = None
  8443. if archive_id:
  8444. async with async_session() as db:
  8445. run_archive = await ArchiveService(db).get_archive(archive_id)
  8446. run_started_at = run_archive.started_at if run_archive else None
  8447. timelapse_path = await tl_complete(printer_id)
  8448. if timelapse_path and archive_id:
  8449. await _attach_layer_timelapse(archive_id, timelapse_path, notify_plate_id, run_started_at)
  8450. elif timelapse_path:
  8451. # Timelapse created but no archive - just clean up
  8452. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  8453. else:
  8454. # Print failed or cancelled - cancel timelapse session
  8455. cancel_session(printer_id)
  8456. logger.info(
  8457. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  8458. )
  8459. except Exception as e:
  8460. logger.warning("[LAYER-TL] Failed: %s", e)
  8461. # A completed print's session left _active_sessions when its stitch
  8462. # began: the one there now belongs to the next print, which may have
  8463. # started during the stitch, and must not lose its frames.
  8464. if print_status != "completed":
  8465. try:
  8466. cancel_session(printer_id)
  8467. except Exception:
  8468. pass # Best-effort timelapse session cancellation on error
  8469. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  8470. log_timing("All background tasks scheduled")
  8471. # Auto-scan for timelapse if recording was active during the print
  8472. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  8473. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  8474. # Schedule timelapse scan as background task with retries
  8475. # The printer needs time to encode the video after print completion
  8476. baseline = _timelapse_baselines.pop(printer_id, None)
  8477. spawn_background_task(
  8478. _scan_for_timelapse_with_retries(archive_id, baseline, plate_id=notify_plate_id),
  8479. name=f"scan-timelapse-{archive_id}",
  8480. )
  8481. log_timing("Timelapse scan scheduled")
  8482. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  8483. # AMS sensor history recording
  8484. _ams_history_task: asyncio.Task | None = None
  8485. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  8486. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  8487. def _retention_days(stored: str | None, default: int) -> int:
  8488. """A history retention setting as days to keep: at least 1, the default
  8489. when unset or unreadable. A stored 0 or less (the API took one before it
  8490. had a minimum) would put the cutoff at now and delete all history."""
  8491. try:
  8492. return max(1, int(stored)) if stored is not None else default
  8493. except (TypeError, ValueError):
  8494. return default
  8495. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  8496. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  8497. _ams_alarm_cooldown: dict[str, datetime] = {}
  8498. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  8499. # (printer_id, ams_id) already reported as sending the drop index and no
  8500. # percentage. Logged once each so a supported printer that turns out to do this
  8501. # shows up in a support bundle rather than as a user wondering where the
  8502. # humidity reading went -- see the note at the read site below (#3140).
  8503. _ams_index_only_logged: set[tuple[int, int]] = set()
  8504. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  8505. """Temperature at which the AMS alarm fires, falling back to the display band.
  8506. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  8507. when a notification was sent as well, which is why a room above it made the
  8508. alarm fire once an hour for as long as the weather lasted -- and the only way
  8509. to stop that was to raise the display band and lose the colour that says the
  8510. unit is warm (#2905).
  8511. Unset resolves to the fair threshold, so an install that never sets one is
  8512. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  8513. so that arrives here as a string and is handled by the same branch as any
  8514. other unparseable value -- there is no separate sentinel to keep in sync.
  8515. A non-positive value is refused rather than honoured: zero would alarm
  8516. permanently, and it is far more likely to be a cleared field than a
  8517. deliberate choice.
  8518. """
  8519. if raw_alarm_value is None:
  8520. return fair_threshold
  8521. try:
  8522. value = float(raw_alarm_value)
  8523. except (TypeError, ValueError):
  8524. return fair_threshold
  8525. if not math.isfinite(value) or value <= 0:
  8526. return fair_threshold
  8527. return value
  8528. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  8529. # through a cycle and the cool-down after it (#1802). Stored in the settings
  8530. # table rather than alongside _ams_alarm_cooldown above, because a restart
  8531. # partway through a cool-down would otherwise resume alarming about heat the
  8532. # user asked for — the same internal-timestamp-row pattern as
  8533. # support.py's debug_logging_enabled_at.
  8534. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  8535. # Upper bound on that suppression. The latch normally clears as soon as the unit
  8536. # reads at or below the threshold; see utils.ams_drying for why this cap only
  8537. # matters when it never does.
  8538. AMS_DRYING_GRACE_MINUTES = 120
  8539. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  8540. """Read the persisted per-AMS drying latch, dropping entries out of window.
  8541. Anything older than the grace cap would expire on its next visit anyway, so
  8542. discarding it here costs nothing and stops rows for deleted printers from
  8543. accumulating.
  8544. Stamps ahead of now get two defences, because a box whose clock jumps
  8545. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  8546. ones are discarded outright, and the rest are clamped to now. Without the
  8547. clamp the cap would measure from a moment that has not happened yet and hold
  8548. the alarm quiet for the skew on top of the cap. One unnecessary notification
  8549. after a clock jump is a far better failure than an alarm silently disabled
  8550. for hours.
  8551. """
  8552. from backend.app.models.settings import Settings
  8553. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8554. setting = result.scalar_one_or_none()
  8555. if not setting or not setting.value:
  8556. return {}
  8557. try:
  8558. raw = json.loads(setting.value)
  8559. except (ValueError, TypeError):
  8560. return {} # Corrupted row → no latch, alarms behave as they did before
  8561. if not isinstance(raw, dict):
  8562. return {}
  8563. now = datetime.now(timezone.utc)
  8564. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  8565. latch: dict[str, datetime] = {}
  8566. for key, value in raw.items():
  8567. try:
  8568. stamp = datetime.fromisoformat(str(value))
  8569. except (ValueError, TypeError):
  8570. continue
  8571. if stamp.tzinfo is None:
  8572. stamp = stamp.replace(tzinfo=timezone.utc)
  8573. if not (now - window <= stamp <= now + window):
  8574. continue
  8575. # Nothing may sit in the future: suppression is measured as now minus
  8576. # the stamp, so a stamp ahead of now would extend it by the skew on top
  8577. # of the cap. Clamping the survivors keeps the cap an actual cap.
  8578. latch[str(key)] = min(stamp, now)
  8579. return latch
  8580. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  8581. """Persist the latch, writing only when it actually changed.
  8582. Adds the session change but does not commit — the caller's own commit
  8583. carries it, so the latch lands in the same transaction as the sensor rows
  8584. that produced it.
  8585. """
  8586. from backend.app.models.settings import Settings
  8587. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  8588. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8589. setting = result.scalar_one_or_none()
  8590. if setting is None:
  8591. # Don't create the row on installs that never dry anything.
  8592. if payload != "{}":
  8593. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  8594. elif setting.value != payload:
  8595. setting.value = payload
  8596. def _ams_has_filament(ams_data: dict) -> bool:
  8597. """True if this AMS unit has at least one tray slot holding filament.
  8598. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  8599. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  8600. still report sensor readings, but those readings are ambient and not
  8601. actionable: no filament to dry, no humidity to push down. #1619 — gate
  8602. humidity/temperature alarms on this check so empty units don't generate
  8603. hourly noise. Sensor history still records regardless so the UI charts
  8604. stay continuous.
  8605. Fallback path inspects the `tray` array's `tray_type` fields for setups
  8606. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  8607. """
  8608. bits = ams_data.get("tray_exist_bits")
  8609. if isinstance(bits, str) and bits.strip():
  8610. try:
  8611. return int(bits, 16) > 0
  8612. except ValueError:
  8613. pass
  8614. trays = ams_data.get("tray")
  8615. if isinstance(trays, list):
  8616. return any(
  8617. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  8618. )
  8619. return False
  8620. async def record_ams_history():
  8621. """Background task to record AMS humidity and temperature data."""
  8622. logger = logging.getLogger(__name__)
  8623. # Wait a short time for MQTT connections to establish on startup
  8624. await asyncio.sleep(10)
  8625. while True:
  8626. try:
  8627. from backend.app.models.ams_history import AMSSensorHistory
  8628. from backend.app.models.printer import Printer
  8629. from backend.app.models.settings import Settings
  8630. async with async_session() as db:
  8631. # Get all active printers
  8632. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8633. printers = result.scalars().all()
  8634. # Get alarm thresholds from settings
  8635. humidity_threshold = 60.0 # Default: fair threshold
  8636. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  8637. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  8638. setting = result.scalar_one_or_none()
  8639. if setting:
  8640. try:
  8641. humidity_threshold = float(setting.value)
  8642. except (ValueError, TypeError):
  8643. pass # Keep default threshold if stored value is invalid
  8644. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  8645. setting = result.scalar_one_or_none()
  8646. if setting:
  8647. try:
  8648. temp_fair_threshold = float(setting.value)
  8649. except (ValueError, TypeError):
  8650. pass # Keep default threshold if stored value is invalid
  8651. # The alarm gets its own threshold, seeded from the resolved fair
  8652. # value so an install that has never set one behaves exactly as
  8653. # it did before (#2905). ams_temp_fair decides when the card turns
  8654. # amber; 35 C is a reasonable place to change a colour and not a
  8655. # reasonable place to page someone. A room above it makes the
  8656. # alarm fire once an hour for as long as the weather lasts, and
  8657. # the only way to stop it was to raise the display band and lose
  8658. # the colour that says the unit is warm.
  8659. #
  8660. # An unset value is stored as the literal "None", which the except
  8661. # below swallows the same way it swallows garbage -- so the
  8662. # fallback costs nothing and needs no sentinel of its own.
  8663. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  8664. setting = result.scalar_one_or_none()
  8665. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  8666. temp_fair_threshold, setting.value if setting else None
  8667. )
  8668. # Per-filament humidity threshold overrides (#1605) — resolved
  8669. # per-AMS below from the loaded tray types. Reuses the same
  8670. # resolver as the auto-drying scheduler so behavior stays in
  8671. # lockstep across both consumers.
  8672. from backend.app.services.print_scheduler import PrintScheduler
  8673. per_type_humidity_thresholds: dict[str, int] = {}
  8674. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  8675. setting = result.scalar_one_or_none()
  8676. if setting and setting.value:
  8677. try:
  8678. raw = json.loads(setting.value)
  8679. if isinstance(raw, dict):
  8680. for k, v in raw.items():
  8681. try:
  8682. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  8683. v
  8684. )
  8685. except (TypeError, ValueError):
  8686. continue
  8687. except (ValueError, TypeError):
  8688. pass # Invalid JSON → no overrides, fall through to global threshold
  8689. # Per-AMS drying latch (#1802), loaded once per pass and written
  8690. # back below only if a unit changed it.
  8691. drying_latch = await _load_ams_drying_latch(db)
  8692. drying_latch_before = dict(drying_latch)
  8693. recorded_count = 0
  8694. for printer in printers:
  8695. # Get current state from printer manager
  8696. state = printer_manager.get_status(printer.id)
  8697. if not state or not state.connected or not state.raw_data:
  8698. continue # Skip disconnected printers - don't use stale data
  8699. raw_data = state.raw_data
  8700. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  8701. continue
  8702. # Record data for each AMS unit
  8703. for ams_data in raw_data["ams"]:
  8704. ams_id = int(ams_data.get("id", 0))
  8705. # Percentage only. The 1-5 index is inverted, so
  8706. # charting it as a percentage drew the wettest units as
  8707. # the driest (#3140); a unit that reports no percentage
  8708. # leaves a gap in the chart instead. See
  8709. # utils/ams_humidity.
  8710. humidity = ams_humidity_percent(ams_data)
  8711. # No supported printer is known to send the index
  8712. # alone -- the report came from unsupported firmware,
  8713. # and no install has been seen using the old fallback.
  8714. # "Known" is doing work there, so say so once per unit:
  8715. # the alternative is a silent blank card.
  8716. if humidity is None and ams_data.get("humidity") is not None:
  8717. unit_key = (printer.id, ams_id)
  8718. if unit_key not in _ams_index_only_logged:
  8719. _ams_index_only_logged.add(unit_key)
  8720. logger.info(
  8721. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  8722. "percentage. The index is inverted and is not shown as a percentage "
  8723. "(#3140), so this unit has no humidity reading, chart or alarm. "
  8724. "Please report this with the printer and AMS firmware versions.",
  8725. printer.name,
  8726. ams_id,
  8727. )
  8728. # Get temperature
  8729. temperature = None
  8730. temp_str = ams_data.get("temp")
  8731. if temp_str is not None:
  8732. try:
  8733. temperature = float(temp_str)
  8734. except (ValueError, TypeError):
  8735. pass # Skip unparseable temperature value
  8736. # Skip if no data
  8737. if humidity is None and temperature is None:
  8738. continue
  8739. # Record the data point
  8740. history = AMSSensorHistory(
  8741. printer_id=printer.id,
  8742. ams_id=ams_id,
  8743. humidity=humidity,
  8744. # Both columns hold the same reading now that the
  8745. # index can no longer reach ``humidity``. Writing it
  8746. # through the same value also stops a genuine 0%
  8747. # from being stored as NULL, which the old truthiness
  8748. # test did.
  8749. humidity_raw=humidity,
  8750. temperature=temperature,
  8751. )
  8752. db.add(history)
  8753. recorded_count += 1
  8754. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  8755. is_ams_ht = ams_id >= 128
  8756. if is_ams_ht:
  8757. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  8758. else:
  8759. ams_label = f"AMS-{chr(65 + ams_id)}"
  8760. # Skip alarm dispatch for empty AMS units — humidity /
  8761. # temperature readings are ambient with no filament to
  8762. # protect, and the hourly notification just becomes
  8763. # noise. Sensor history was already recorded above so
  8764. # the UI charts stay continuous (#1619). Per-AMS check
  8765. # so a multi-AMS setup with one loaded + one empty
  8766. # still alarms on the loaded unit.
  8767. if not _ams_has_filament(ams_data):
  8768. continue
  8769. # Resolve per-filament humidity threshold for this AMS
  8770. # unit (#1605). Falls back to the global ams_humidity_fair
  8771. # when no per-type overrides are configured.
  8772. trays = ams_data.get("tray", []) or []
  8773. effective_humidity_threshold = float(
  8774. PrintScheduler.resolve_humidity_threshold(
  8775. trays, per_type_humidity_thresholds, int(humidity_threshold)
  8776. )
  8777. )
  8778. # Check humidity alarm (only if above threshold)
  8779. if humidity is not None and humidity > effective_humidity_threshold:
  8780. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  8781. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8782. now = datetime.now(timezone.utc)
  8783. if (
  8784. last_alarm is None
  8785. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8786. ):
  8787. _ams_alarm_cooldown[cooldown_key] = now
  8788. logger.info(
  8789. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  8790. )
  8791. try:
  8792. # Call different notification method based on AMS type
  8793. if is_ams_ht:
  8794. await notification_service.on_ams_ht_humidity_high(
  8795. printer.id,
  8796. printer.name,
  8797. ams_label,
  8798. humidity,
  8799. effective_humidity_threshold,
  8800. db,
  8801. )
  8802. else:
  8803. await notification_service.on_ams_humidity_high(
  8804. printer.id,
  8805. printer.name,
  8806. ams_label,
  8807. humidity,
  8808. effective_humidity_threshold,
  8809. db,
  8810. )
  8811. except Exception as e:
  8812. logger.warning("Failed to send humidity alarm: %s", e)
  8813. # A drying cycle heats the unit far past ams_temp_fair on
  8814. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  8815. # AMS-HT, against a 35 C default — so the alarm fired
  8816. # once an hour for the whole cycle and kept firing while
  8817. # the unit cooled back down (#1802). Latch on the
  8818. # firmware's own drying state and hold until the reading
  8819. # returns to normal. Humidity is deliberately left alone:
  8820. # it falls during drying, which is the whole point.
  8821. latch_key = f"{printer.id}:{ams_id}"
  8822. # The latch releases at `threshold`, so it takes the alarm
  8823. # number too. Handing it the display band would strand the
  8824. # latch on any unit that settles back above it -- a room
  8825. # where the AMS rests at 37.7 C never returns under a 35 C
  8826. # band, so the latch could only expire on the grace cap
  8827. # rather than releasing when the unit had actually cooled.
  8828. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  8829. drying_active=is_drying_active(ams_data),
  8830. temperature=temperature,
  8831. threshold=temp_alarm_threshold,
  8832. latched_at=drying_latch.get(latch_key),
  8833. now=datetime.now(timezone.utc),
  8834. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  8835. )
  8836. if new_latch is None:
  8837. drying_latch.pop(latch_key, None)
  8838. else:
  8839. drying_latch[latch_key] = new_latch
  8840. # Check temperature alarm (only if above threshold)
  8841. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  8842. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  8843. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8844. now = datetime.now(timezone.utc)
  8845. if (
  8846. last_alarm is None
  8847. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8848. ):
  8849. _ams_alarm_cooldown[cooldown_key] = now
  8850. logger.info(
  8851. f"Sending temperature alarm for {printer.name} {ams_label}: "
  8852. f"{temperature}°C > {temp_alarm_threshold}°C"
  8853. )
  8854. try:
  8855. # Call different notification method based on AMS type
  8856. if is_ams_ht:
  8857. # The reported threshold has to be the one
  8858. # that fired, or the message says "> 35 °C"
  8859. # while firing at 45.
  8860. await notification_service.on_ams_ht_temperature_high(
  8861. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8862. )
  8863. else:
  8864. await notification_service.on_ams_temperature_high(
  8865. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8866. )
  8867. except Exception as e:
  8868. logger.warning("Failed to send temperature alarm: %s", e)
  8869. if drying_latch != drying_latch_before:
  8870. await _save_ams_drying_latch(db, drying_latch)
  8871. await db.commit()
  8872. if recorded_count > 0:
  8873. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  8874. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  8875. global _ams_cleanup_counter
  8876. _ams_cleanup_counter += 1
  8877. if _ams_cleanup_counter >= 288:
  8878. _ams_cleanup_counter = 0
  8879. # Get retention days from settings
  8880. from backend.app.models.settings import Settings
  8881. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  8882. setting = result.scalar_one_or_none()
  8883. retention_days = _retention_days(setting.value if setting else None, AMS_HISTORY_RETENTION_DAYS)
  8884. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8885. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  8886. await db.commit()
  8887. if result.rowcount > 0:
  8888. logger.info(
  8889. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  8890. )
  8891. # Wait until next recording interval
  8892. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  8893. except asyncio.CancelledError:
  8894. break
  8895. except Exception as e:
  8896. logger.warning("AMS history recording failed: %s", e)
  8897. await asyncio.sleep(60) # Wait a bit before retrying
  8898. def start_ams_history_recording():
  8899. """Start the AMS history recording background task."""
  8900. global _ams_history_task
  8901. if _ams_history_task is None:
  8902. _ams_history_task = asyncio.create_task(record_ams_history())
  8903. logging.getLogger(__name__).info("AMS history recording started")
  8904. def stop_ams_history_recording():
  8905. """Stop the AMS history recording background task."""
  8906. global _ams_history_task
  8907. if _ams_history_task:
  8908. _ams_history_task.cancel()
  8909. _ams_history_task = None
  8910. logging.getLogger(__name__).info("AMS history recording stopped")
  8911. # Printer sensor history recording (nozzle / bed / chamber)
  8912. _printer_sensor_history_task: asyncio.Task | None = None
  8913. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  8914. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  8915. _printer_sensor_cleanup_counter = 0
  8916. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  8917. # MQTT parser writes, so we don't need to handle per-model field aliases here
  8918. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  8919. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  8920. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  8921. _SENSOR_TARGET_KEYS = {
  8922. "nozzle": "nozzle_target",
  8923. "nozzle_2": "nozzle_2_target",
  8924. "bed": "bed_target",
  8925. "chamber": "chamber_target",
  8926. }
  8927. async def record_printer_sensor_history():
  8928. """Background task to record nozzle / bed / chamber readings.
  8929. Pulls from `state.temperatures` (already normalised across all printer
  8930. models by the MQTT parser) rather than re-parsing raw_data, so we get
  8931. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  8932. """
  8933. logger = logging.getLogger(__name__)
  8934. await asyncio.sleep(10)
  8935. while True:
  8936. try:
  8937. from backend.app.models.printer import Printer
  8938. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  8939. from backend.app.models.settings import Settings
  8940. async with async_session() as db:
  8941. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8942. printers = result.scalars().all()
  8943. recorded_count = 0
  8944. for printer in printers:
  8945. state = printer_manager.get_status(printer.id)
  8946. if not state or not state.connected:
  8947. continue
  8948. temps = getattr(state, "temperatures", None) or {}
  8949. if not isinstance(temps, dict):
  8950. continue
  8951. for kind in _SENSOR_KINDS:
  8952. if kind not in temps:
  8953. continue
  8954. try:
  8955. value = float(temps[kind])
  8956. except (ValueError, TypeError):
  8957. continue
  8958. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  8959. target_val: float | None = None
  8960. if target_raw is not None:
  8961. try:
  8962. target_val = float(target_raw)
  8963. except (ValueError, TypeError):
  8964. target_val = None
  8965. db.add(
  8966. PrinterSensorHistory(
  8967. printer_id=printer.id,
  8968. sensor_kind=kind,
  8969. value=value,
  8970. target=target_val,
  8971. )
  8972. )
  8973. recorded_count += 1
  8974. await db.commit()
  8975. if recorded_count > 0:
  8976. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  8977. # Periodic cleanup — once every ~24h at this interval.
  8978. global _printer_sensor_cleanup_counter
  8979. _printer_sensor_cleanup_counter += 1
  8980. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  8981. if _printer_sensor_cleanup_counter >= cleanup_every:
  8982. _printer_sensor_cleanup_counter = 0
  8983. result = await db.execute(
  8984. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  8985. )
  8986. setting = result.scalar_one_or_none()
  8987. retention_days = _retention_days(
  8988. setting.value if setting else None, PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  8989. )
  8990. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8991. cleanup = await db.execute(
  8992. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  8993. )
  8994. await db.commit()
  8995. if cleanup.rowcount > 0:
  8996. logger.info(
  8997. "Cleaned up %s old printer sensor history entries (older than %s days)",
  8998. cleanup.rowcount,
  8999. retention_days,
  9000. )
  9001. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  9002. except asyncio.CancelledError:
  9003. break
  9004. except Exception as e:
  9005. logger.warning("Printer sensor history recording failed: %s", e)
  9006. await asyncio.sleep(60)
  9007. def start_printer_sensor_history_recording():
  9008. global _printer_sensor_history_task
  9009. if _printer_sensor_history_task is None:
  9010. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  9011. logging.getLogger(__name__).info("Printer sensor history recording started")
  9012. def stop_printer_sensor_history_recording():
  9013. global _printer_sensor_history_task
  9014. if _printer_sensor_history_task:
  9015. _printer_sensor_history_task.cancel()
  9016. _printer_sensor_history_task = None
  9017. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  9018. # Printer runtime tracking
  9019. _runtime_tracking_task: asyncio.Task | None = None
  9020. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  9021. async def track_printer_runtime():
  9022. """Background task to track printer active runtime (RUNNING state only).
  9023. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  9024. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  9025. which track mechanical wear. Pause time has no motion and no wear, so
  9026. counting it inflates maintenance warnings (#1521).
  9027. """
  9028. logger = logging.getLogger(__name__)
  9029. # Wait for MQTT connections to establish on startup
  9030. await asyncio.sleep(15)
  9031. while True:
  9032. try:
  9033. from backend.app.models.printer import Printer
  9034. # Fetch printer IDs in a short-lived read-only session
  9035. async with async_session() as db:
  9036. result = await db.execute(
  9037. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  9038. Printer.is_active.is_(True)
  9039. )
  9040. )
  9041. printer_rows = result.all()
  9042. now = datetime.now(timezone.utc)
  9043. updated_count = 0
  9044. # Update each printer in its own short session to minimise write-lock
  9045. # hold time and avoid blocking critical commits like queue status
  9046. # updates (#897).
  9047. for pid, pname, runtime_secs, last_update in printer_rows:
  9048. state = printer_manager.get_status(pid)
  9049. if not state:
  9050. logger.debug("[%s] Runtime tracking: no state available", pname)
  9051. continue
  9052. if not state.connected:
  9053. logger.debug("[%s] Runtime tracking: not connected", pname)
  9054. continue
  9055. needs_commit = False
  9056. new_runtime = runtime_secs
  9057. new_last_update = last_update
  9058. if state.state == "RUNNING":
  9059. if last_update:
  9060. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  9061. elapsed = (now - lu).total_seconds()
  9062. if elapsed > 0:
  9063. new_runtime = runtime_secs + int(elapsed)
  9064. updated_count += 1
  9065. needs_commit = True
  9066. logger.debug(
  9067. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  9068. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  9069. )
  9070. else:
  9071. needs_commit = True
  9072. logger.debug("[%s] Runtime tracking: first active detection", pname)
  9073. new_last_update = now
  9074. else:
  9075. if last_update is not None:
  9076. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  9077. new_last_update = None
  9078. needs_commit = True
  9079. if needs_commit:
  9080. try:
  9081. async with async_session() as db:
  9082. result = await db.execute(select(Printer).where(Printer.id == pid))
  9083. printer = result.scalar_one_or_none()
  9084. if printer:
  9085. printer.runtime_seconds = new_runtime
  9086. printer.last_runtime_update = new_last_update
  9087. await db.commit()
  9088. except Exception as e:
  9089. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  9090. if updated_count > 0:
  9091. logger.debug("Updated runtime for %s printer(s)", updated_count)
  9092. except asyncio.CancelledError:
  9093. logger.info("Runtime tracking cancelled")
  9094. break
  9095. except Exception as e:
  9096. logger.warning("Runtime tracking failed: %s", e)
  9097. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  9098. def start_runtime_tracking():
  9099. """Start the printer runtime tracking background task."""
  9100. global _runtime_tracking_task
  9101. if _runtime_tracking_task is None:
  9102. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  9103. logging.getLogger(__name__).info("Printer runtime tracking started")
  9104. def stop_runtime_tracking():
  9105. """Stop the printer runtime tracking background task."""
  9106. global _runtime_tracking_task
  9107. if _runtime_tracking_task:
  9108. _runtime_tracking_task.cancel()
  9109. _runtime_tracking_task = None
  9110. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  9111. # SpoolBuddy device watchdog
  9112. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  9113. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  9114. async def _spoolbuddy_watchdog_loop():
  9115. """Periodic check for SpoolBuddy devices that have gone offline."""
  9116. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  9117. while True:
  9118. try:
  9119. await spoolbuddy_watchdog()
  9120. except asyncio.CancelledError:
  9121. break
  9122. except Exception as e:
  9123. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  9124. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  9125. def start_spoolbuddy_watchdog():
  9126. global _spoolbuddy_watchdog_task
  9127. if _spoolbuddy_watchdog_task is None:
  9128. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  9129. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  9130. def stop_spoolbuddy_watchdog():
  9131. global _spoolbuddy_watchdog_task
  9132. if _spoolbuddy_watchdog_task:
  9133. _spoolbuddy_watchdog_task.cancel()
  9134. _spoolbuddy_watchdog_task = None
  9135. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  9136. # Dead-MQTT-session recovery
  9137. #
  9138. # check_staleness() covers the "connected but silent" half-broken session. It
  9139. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  9140. # is the only thing left watching at that point. When paho stops making
  9141. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  9142. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  9143. # offline with the UI open the whole time, recovered only when something
  9144. # happened to nudge it.
  9145. #
  9146. # This loop is that backstop. It only touches printers that had a working
  9147. # session and lost it, and only when the MQTT port still answers — a printer
  9148. # that is simply switched off is left to paho, since rebuilding a client
  9149. # against an unreachable host achieves nothing and would fill the log every
  9150. # night.
  9151. _connection_watchdog_task: asyncio.Task | None = None
  9152. CONNECTION_WATCHDOG_INTERVAL = 60
  9153. # How long a printer must have been silent before we stop trusting paho.
  9154. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  9155. # so a session that is recovering on its own is never interrupted.
  9156. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  9157. # Per-printer floor between rebuild attempts.
  9158. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  9159. _connection_watchdog_last_attempt: dict[int, float] = {}
  9160. async def _recover_dead_printer_sessions() -> int:
  9161. """Rebuild MQTT clients that have been offline too long to still be trying.
  9162. Returns the number of printers a rebuild was attempted for (for tests and
  9163. for the caller's logging). Never raises: one unreachable printer must not
  9164. stop the sweep for the rest of the farm.
  9165. """
  9166. logger = logging.getLogger(__name__)
  9167. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  9168. now = time.monotonic()
  9169. recovered = 0
  9170. for printer_id, client in list(printer_manager._clients.items()):
  9171. try:
  9172. if client.state.connected:
  9173. _connection_watchdog_last_attempt.pop(printer_id, None)
  9174. continue
  9175. # Time since the last inbound message is the age of the last known
  9176. # good session — no extra bookkeeping needed, and it is the same
  9177. # clock is_stale() reads. 0 means this client has never had one:
  9178. # that is the initial-connect path, where paho retrying is the
  9179. # correct and only behaviour, so leave it be.
  9180. last_msg = client._last_message_time
  9181. if not last_msg:
  9182. continue
  9183. offline_for = time.time() - last_msg
  9184. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  9185. continue
  9186. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  9187. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  9188. continue
  9189. if not await check_port(client.ip_address, PORT_MQTT):
  9190. # Switched off, unplugged, or off the network. Paho's retry is
  9191. # the right handler; say so at debug level and move on.
  9192. logger.debug(
  9193. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  9194. "— leaving the reconnect to paho",
  9195. printer_id,
  9196. offline_for,
  9197. )
  9198. _connection_watchdog_last_attempt[printer_id] = now
  9199. continue
  9200. _connection_watchdog_last_attempt[printer_id] = now
  9201. recovered += 1
  9202. logger.warning(
  9203. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  9204. "rebuilding the client with a fresh session (last connect error: %s)",
  9205. printer_id,
  9206. offline_for,
  9207. PORT_MQTT,
  9208. client.last_connect_error or "none recorded",
  9209. )
  9210. # Async context, so this takes the hard-reset path: fresh client_id,
  9211. # paho's QoS 1 queue dropped. That matters — a project_file left
  9212. # unacked on the dead session would otherwise replay into the new
  9213. # one and trip 0500_4003 on the printer (#1136).
  9214. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  9215. except Exception as e:
  9216. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  9217. return recovered
  9218. async def _connection_watchdog_loop():
  9219. logger = logging.getLogger(__name__)
  9220. # Let the initial connects settle before judging anyone offline.
  9221. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  9222. while True:
  9223. try:
  9224. await _recover_dead_printer_sessions()
  9225. except asyncio.CancelledError:
  9226. break
  9227. except Exception as e:
  9228. logger.warning("Connection watchdog sweep failed: %s", e)
  9229. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  9230. def start_connection_watchdog():
  9231. global _connection_watchdog_task
  9232. if _connection_watchdog_task is None:
  9233. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  9234. logging.getLogger(__name__).info("Printer connection watchdog started")
  9235. def stop_connection_watchdog():
  9236. global _connection_watchdog_task
  9237. if _connection_watchdog_task:
  9238. _connection_watchdog_task.cancel()
  9239. _connection_watchdog_task = None
  9240. _connection_watchdog_last_attempt.clear()
  9241. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  9242. # Camera stream orphan cleanup
  9243. _camera_cleanup_task: asyncio.Task | None = None
  9244. CAMERA_CLEANUP_INTERVAL = 60
  9245. # Every this many camera cleanups (about an hour), the timelapse janitor too:
  9246. # kept frames of a failed stitch go after a day, not at the next restart.
  9247. TIMELAPSE_CLEANUP_EVERY = 60
  9248. async def _camera_cleanup_loop():
  9249. """Periodically clean up orphaned ffmpeg processes and timelapse leftovers."""
  9250. from backend.app.api.routes.camera import cleanup_orphaned_streams
  9251. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9252. rounds = 0
  9253. while True:
  9254. try:
  9255. rounds += 1
  9256. await cleanup_orphaned_streams()
  9257. except asyncio.CancelledError:
  9258. break
  9259. except Exception as e:
  9260. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  9261. try:
  9262. if rounds % TIMELAPSE_CLEANUP_EVERY == 0:
  9263. await asyncio.to_thread(cleanup_orphaned_timelapse_sessions)
  9264. except asyncio.CancelledError:
  9265. break
  9266. except Exception as e:
  9267. logging.getLogger(__name__).warning("Timelapse frames cleanup failed: %s", e)
  9268. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  9269. def start_camera_cleanup():
  9270. global _camera_cleanup_task
  9271. if _camera_cleanup_task is None:
  9272. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  9273. logging.getLogger(__name__).info("Camera stream cleanup started")
  9274. def stop_camera_cleanup():
  9275. global _camera_cleanup_task
  9276. if _camera_cleanup_task:
  9277. _camera_cleanup_task.cancel()
  9278. _camera_cleanup_task = None
  9279. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  9280. # ---------------------------------------------------------------------------
  9281. # Expected-print TTL eviction
  9282. # ---------------------------------------------------------------------------
  9283. def _evict_stale_expected_prints() -> None:
  9284. """Remove entries from _expected_prints / _expected_print_creators that are
  9285. older than _EXPECTED_PRINT_TTL_SECONDS.
  9286. This prevents unbounded growth when a print is registered (via
  9287. register_expected_print) but on_print_start never fires — e.g. because the
  9288. printer disconnects, the app restarts, or the print is started directly from
  9289. the printer panel without going through the queue.
  9290. """
  9291. # Use monotonic time so the TTL is unaffected by system clock adjustments
  9292. # (e.g. NTP sync, DST changes).
  9293. # A print that ended without its archive being found at completion leaves
  9294. # its id here; only running prints are owned.
  9295. _owned_print_archive_ids.intersection_update(_active_prints.values())
  9296. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  9297. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  9298. if not stale_keys:
  9299. return
  9300. evicted_archive_ids: set[int] = set()
  9301. for key in stale_keys:
  9302. archive_id = _expected_prints.pop(key, None)
  9303. if archive_id is not None:
  9304. evicted_archive_ids.add(archive_id)
  9305. _expected_print_creators.pop(key, None)
  9306. _expected_print_registered_at.pop(key, None)
  9307. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  9308. # that have no remaining live keys in _expected_prints (all variants
  9309. # were just evicted) and are not printing right now. Print start pops
  9310. # only the names the printer reported, so the "<base>.gcode" variant
  9311. # outlives it; without the printing check its eviction two hours after
  9312. # dispatch threw away a running print's plate, AMS mapping and cost
  9313. # centre, which completion still reads (#3275).
  9314. live_archive_ids = set(_expected_prints.values()) | set(_active_prints.values())
  9315. for archive_id in evicted_archive_ids:
  9316. if archive_id not in live_archive_ids:
  9317. _print_ams_mappings.pop(archive_id, None)
  9318. _print_cost_center_ids.pop(archive_id, None)
  9319. _print_plate_ids.pop(archive_id, None)
  9320. logging.getLogger(__name__).info(
  9321. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  9322. )
  9323. async def _expected_prints_cleanup_loop() -> None:
  9324. """Background task: periodically evict stale expected-print entries."""
  9325. while True:
  9326. try:
  9327. _evict_stale_expected_prints()
  9328. except asyncio.CancelledError:
  9329. raise
  9330. except Exception as e:
  9331. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  9332. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  9333. def start_expected_prints_cleanup() -> None:
  9334. global _expected_prints_cleanup_task
  9335. if _expected_prints_cleanup_task is None:
  9336. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  9337. logging.getLogger(__name__).info("Expected prints cleanup started")
  9338. def stop_expected_prints_cleanup() -> None:
  9339. global _expected_prints_cleanup_task
  9340. if _expected_prints_cleanup_task:
  9341. _expected_prints_cleanup_task.cancel()
  9342. _expected_prints_cleanup_task = None
  9343. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  9344. # ---------------------------------------------------------------------------
  9345. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  9346. # ---------------------------------------------------------------------------
  9347. _auth_cleanup_task: asyncio.Task | None = None
  9348. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  9349. async def _run_auth_cleanup() -> None:
  9350. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  9351. from backend.app.core.database import async_session
  9352. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  9353. from backend.app.models.user_totp import UserTOTP
  9354. now = datetime.now(timezone.utc)
  9355. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  9356. try:
  9357. async with async_session() as db:
  9358. stale_cutoff = now - timedelta(hours=1)
  9359. result = await db.execute(
  9360. select(UserTOTP).where(
  9361. UserTOTP.is_enabled.is_(False),
  9362. UserTOTP.created_at < stale_cutoff,
  9363. )
  9364. )
  9365. stale_records = result.scalars().all()
  9366. if stale_records:
  9367. for rec in stale_records:
  9368. await db.delete(rec)
  9369. await db.commit()
  9370. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  9371. except Exception as e:
  9372. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  9373. # Remove expired revoked-JTI entries (they are no longer needed once the
  9374. # original token's exp has passed — the token would be rejected by JWT
  9375. # signature verification regardless).
  9376. try:
  9377. async with async_session() as db:
  9378. await db.execute(
  9379. delete(AuthEphemeralToken).where(
  9380. AuthEphemeralToken.token_type == "revoked_jti",
  9381. AuthEphemeralToken.expires_at < now,
  9382. )
  9383. )
  9384. await db.commit()
  9385. except Exception as e:
  9386. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  9387. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  9388. # Events outside this window can never affect rate-limit decisions — they only
  9389. # consume DB space. Use the same window constant as the rate limiter so the
  9390. # two are always in sync.
  9391. try:
  9392. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  9393. async with async_session() as db:
  9394. await db.execute(
  9395. delete(AuthRateLimitEvent).where(
  9396. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  9397. )
  9398. )
  9399. await db.commit()
  9400. except Exception as e:
  9401. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  9402. async def _auth_cleanup_loop() -> None:
  9403. """Periodic background task: run auth cleanup every hour."""
  9404. while True:
  9405. try:
  9406. await _run_auth_cleanup()
  9407. except asyncio.CancelledError:
  9408. break
  9409. except Exception as e:
  9410. logging.warning("Auth cleanup loop error: %s", e)
  9411. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  9412. def start_auth_cleanup() -> None:
  9413. global _auth_cleanup_task
  9414. if _auth_cleanup_task is None:
  9415. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  9416. logging.getLogger(__name__).info("Auth periodic cleanup started")
  9417. def stop_auth_cleanup() -> None:
  9418. global _auth_cleanup_task
  9419. if _auth_cleanup_task:
  9420. _auth_cleanup_task.cancel()
  9421. _auth_cleanup_task = None
  9422. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  9423. @asynccontextmanager
  9424. async def lifespan(app: FastAPI):
  9425. # Startup
  9426. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  9427. # anything else can spawn tasks that might trip it.
  9428. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  9429. install_proactor_reset_filter()
  9430. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  9431. # what turned descriptor exhaustion into a corrupted database (#2883).
  9432. from backend.app.core.fd_limit import raise_open_file_limit
  9433. raise_open_file_limit()
  9434. # Before init_db, so the warning is near the top of the log rather than
  9435. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  9436. warn_if_running_on_uvloop()
  9437. await init_db()
  9438. # Browser download tokens expire after five minutes. Remove abandoned
  9439. # prepared ZIPs at startup as well as before each new preparation so a
  9440. # quiet appliance cannot retain an unusable bundle indefinitely.
  9441. try:
  9442. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  9443. await prune_stale_printer_file_bundles()
  9444. except Exception as exc:
  9445. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  9446. # After migrations, so the is_env_managed column exists. Never raises --
  9447. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  9448. # startup (see apply_env_oidc_provider).
  9449. from backend.app.core.oidc_env import apply_env_oidc_provider
  9450. async with async_session() as oidc_db:
  9451. await apply_env_oidc_provider(oidc_db)
  9452. # Close out batches that finished before `completed` was a reachable status
  9453. # (#342). Without this the Batches tab opens on every batch created since
  9454. # the feature shipped, all still marked active. Never blocks startup.
  9455. try:
  9456. from backend.app.services.print_batch import backfill_batch_statuses
  9457. async with async_session() as batch_db:
  9458. await backfill_batch_statuses(batch_db)
  9459. except Exception as exc:
  9460. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  9461. # Register an app-scoped httpx client for Bambu Cloud services so
  9462. # per-request BambuCloudService instances reuse the same connection pool
  9463. # (important for routes like /cloud/filament-info that chain many
  9464. # get_setting_detail calls). The shared client stores no region/token
  9465. # state, so the per-request ownership pattern that fixed the region-bleed
  9466. # bug is preserved.
  9467. import httpx as _httpx
  9468. from backend.app.services.bambu_cloud import set_shared_http_client
  9469. from backend.app.services.model_providers.makerworld.service import (
  9470. set_shared_http_client as set_shared_makerworld_http_client,
  9471. )
  9472. from backend.app.services.orca_cloud import (
  9473. set_shared_http_client as set_shared_orca_http_client,
  9474. )
  9475. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  9476. set_shared_http_client(_shared_cloud_http_client)
  9477. # Reuse the same connection pool for MakerWorld — different host, same
  9478. # keep-alive pool saves a TLS handshake per request.
  9479. set_shared_makerworld_http_client(_shared_cloud_http_client)
  9480. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  9481. # each spun up (and never closed) its own client, leaking sockets.
  9482. set_shared_orca_http_client(_shared_cloud_http_client)
  9483. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  9484. # This can happen when a print was cancelled mid-print on versions before this fix.
  9485. try:
  9486. async with async_session() as db:
  9487. from backend.app.models.print_queue import PrintQueueItem
  9488. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  9489. aborted_items = result.scalars().all()
  9490. if aborted_items:
  9491. for item in aborted_items:
  9492. item.status = "cancelled"
  9493. await db.commit()
  9494. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  9495. except Exception as e:
  9496. logging.warning("Failed to fix aborted queue items: %s", e)
  9497. # Restore debug logging state from previous session
  9498. await init_debug_logging()
  9499. # Set up printer manager callbacks
  9500. loop = asyncio.get_event_loop()
  9501. printer_manager.set_event_loop(loop)
  9502. printer_manager.set_status_change_callback(on_printer_status_change)
  9503. printer_manager.set_print_start_callback(on_print_start)
  9504. printer_manager.set_print_complete_callback(on_print_complete)
  9505. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  9506. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  9507. printer_manager.set_ams_change_callback(on_ams_change)
  9508. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  9509. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  9510. await printer_manager.load_awaiting_plate_clear_from_db()
  9511. # Layer change callback for external camera timelapse
  9512. async def on_layer_change(printer_id: int, layer_num: int):
  9513. """Capture timelapse frame on layer change + first layer notification."""
  9514. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  9515. await tl_layer_change(printer_id, layer_num)
  9516. # #1867: bank a recent in-print frame so the finish-photo path has a
  9517. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  9518. # #2547 added `on_print_progress` as a second driver — this one alone
  9519. # stops firing once the final layer begins.
  9520. await _maybe_bank_inprint_frame(printer_id, layer_num)
  9521. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  9522. # Gate on actual printing state — Bambu firmware ticks layer_num during
  9523. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  9524. # nozzle clean), so a bare layer_num check can fire minutes before the
  9525. # first real extrusion. We require gcode_state == RUNNING and
  9526. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  9527. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  9528. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  9529. # edge fires later; _first_layer_notified stays clear until we actually send
  9530. # so a deferred re-evaluation can win. See issue #1837.
  9531. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  9532. client = printer_manager.get_client(printer_id)
  9533. state = client.state if client else None
  9534. if not state or state.state != "RUNNING":
  9535. return
  9536. if state.mc_print_sub_stage not in (None, 0):
  9537. return
  9538. _first_layer_notified[printer_id] = True
  9539. try:
  9540. async with async_session() as db:
  9541. from backend.app.models.printer import Printer
  9542. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9543. printer = result.scalar_one_or_none()
  9544. if not printer:
  9545. return
  9546. printer_name = printer.name
  9547. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  9548. total_layers = state.total_layers if state else 0
  9549. image_data = await _capture_snapshot_for_notification(
  9550. printer_id, printer, logging.getLogger(__name__)
  9551. )
  9552. await notification_service.on_first_layer_complete(
  9553. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  9554. )
  9555. except Exception as e:
  9556. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  9557. printer_manager.set_layer_change_callback(on_layer_change)
  9558. async def on_print_progress(printer_id: int, percent: int):
  9559. """#2547: keep the in-print frame bank fresh through the final layer.
  9560. `on_layer_change` stops the moment the last layer starts, which on the
  9561. H2C capture that closed #2547 left the bank stale for the three minutes
  9562. that layer took. Progress is the only field that keeps advancing there,
  9563. and it freezes before the End G-code runs — so banking on it stays
  9564. inside the print and never sees a swapped plate.
  9565. """
  9566. client = printer_manager.get_client(printer_id)
  9567. state = client.state if client else None
  9568. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  9569. printer_manager.set_print_progress_callback(on_print_progress)
  9570. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  9571. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  9572. waiter = _bed_cool_waiters.get(printer_id)
  9573. if not waiter:
  9574. return
  9575. threshold = waiter["threshold"]
  9576. if bed_temp > threshold:
  9577. return
  9578. # Bed is at or below threshold — fire notification and remove waiter
  9579. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  9580. if not waiter_info:
  9581. return # Another callback already handled it
  9582. bed_cool_logger = logging.getLogger(__name__)
  9583. bed_cool_logger.info(
  9584. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  9585. bed_temp,
  9586. printer_id,
  9587. threshold,
  9588. )
  9589. try:
  9590. printer_info = printer_manager.get_printer(printer_id)
  9591. p_name = printer_info.name if printer_info else "Unknown"
  9592. async with async_session() as db:
  9593. await notification_service.on_bed_cooled(
  9594. printer_id=printer_id,
  9595. printer_name=p_name,
  9596. bed_temp=bed_temp,
  9597. threshold=threshold,
  9598. filename=waiter_info["filename"],
  9599. db=db,
  9600. )
  9601. except Exception as e:
  9602. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  9603. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  9604. async def on_drying_complete(printer_id: int, ams_id: int):
  9605. """Smart-plug auto-off-after-drying trigger (#1349).
  9606. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  9607. manager walks all plugs linked to this printer and turns off only
  9608. the ones with ``auto_off_after_drying`` enabled, after their
  9609. per-plug delay. Multiple AMS units finishing close together (e.g. a
  9610. dual-AMS dry that ends within the same MQTT push) call this once
  9611. per unit — the manager's ``_cancel_pending_off`` collapses
  9612. repeated scheduling on the same plug to one timer, so duplicate
  9613. fires are safe.
  9614. """
  9615. try:
  9616. async with async_session() as db:
  9617. await smart_plug_manager.on_drying_complete(printer_id, db)
  9618. except Exception as e:
  9619. logging.getLogger(__name__).warning(
  9620. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  9621. printer_id,
  9622. ams_id,
  9623. e,
  9624. )
  9625. printer_manager.set_drying_complete_callback(on_drying_complete)
  9626. async def on_drying_cycle_end(printer_id: int, cycle):
  9627. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  9628. from backend.app.services.spool_drying import record_drying_cycle
  9629. try:
  9630. async with async_session() as db:
  9631. await record_drying_cycle(db, printer_id, cycle)
  9632. except Exception as e:
  9633. logging.getLogger(__name__).warning(
  9634. "Failed to record drying for printer %d (AMS %d): %s",
  9635. printer_id,
  9636. cycle.ams_id,
  9637. e,
  9638. )
  9639. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  9640. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  9641. """Surface the read-back result of a spool assignment to the UI (#2582).
  9642. The MQTT client confirms (or fails to confirm) that the tray telemetry
  9643. echoed back the filament id we pushed. We relay that as a websocket
  9644. event so the frontend can toast "loaded" / "assignment didn't take"
  9645. instead of the historic silent fire-and-forget, which made the
  9646. AMS→Studio hand-off feel random to users.
  9647. """
  9648. try:
  9649. from backend.app.services.spool_assignment_notifications import (
  9650. _slot_label_from_global_tray,
  9651. )
  9652. if ams_id == 255:
  9653. global_id = 254 + tray_id
  9654. elif ams_id >= 128:
  9655. global_id = ams_id
  9656. else:
  9657. global_id = ams_id * 4 + tray_id
  9658. slot_label = _slot_label_from_global_tray(global_id)
  9659. printer_info = printer_manager.get_printer(printer_id)
  9660. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  9661. await ws_manager.broadcast(
  9662. {
  9663. "type": "spool_assignment_verified",
  9664. "printer_id": printer_id,
  9665. "printer_name": printer_name,
  9666. "ams_id": ams_id,
  9667. "tray_id": tray_id,
  9668. "slot": slot_label,
  9669. "verified": verified,
  9670. # Present on success: False means the filament setting landed
  9671. # but the K-profile (cali_idx) did not — the reporter's exact
  9672. # "loaded but no flow profile" symptom.
  9673. "kprofile_applied": detail.get("kprofile_applied", True),
  9674. # Present on failure: whether any tray telemetry was seen in
  9675. # the window (distinguishes "printer silent" from "printer
  9676. # stored something else").
  9677. "saw_tray": detail.get("saw_tray", False),
  9678. }
  9679. )
  9680. except Exception as e:
  9681. logging.getLogger(__name__).warning(
  9682. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  9683. printer_id,
  9684. ams_id,
  9685. tray_id,
  9686. e,
  9687. )
  9688. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  9689. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  9690. """Persist a mid-print tray change for completion-time attribution.
  9691. AMS filament backup switches trays without telling the slicer, so the
  9692. tray-change log is the only record of which spool fed which layers.
  9693. Keeping it only in memory meant a restart mid-print charged everything
  9694. to the tray that finished the job.
  9695. """
  9696. try:
  9697. from backend.app.services.usage_tracker import record_tray_change
  9698. async with async_session() as db:
  9699. await record_tray_change(db, printer_id, tray_global, layer_num)
  9700. except Exception as e:
  9701. logging.getLogger(__name__).warning(
  9702. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  9703. printer_id,
  9704. tray_global,
  9705. layer_num,
  9706. e,
  9707. )
  9708. printer_manager.set_tray_change_callback(on_tray_change)
  9709. # Initialize MQTT relay from settings
  9710. async with async_session() as db:
  9711. from backend.app.api.routes.settings import get_setting
  9712. mqtt_settings = {
  9713. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  9714. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  9715. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  9716. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  9717. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  9718. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  9719. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  9720. }
  9721. await mqtt_relay.configure(mqtt_settings)
  9722. # Restore MQTT smart plug subscriptions
  9723. if mqtt_settings.get("mqtt_enabled"):
  9724. from backend.app.models.smart_plug import SmartPlug
  9725. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  9726. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  9727. mqtt_plugs = result.scalars().all()
  9728. restored = 0
  9729. for plug in mqtt_plugs:
  9730. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  9731. restored += 1
  9732. if restored:
  9733. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  9734. # Connect to all active printers
  9735. async with async_session() as db:
  9736. await init_printer_connections(db)
  9737. # Auto-connect to Spoolman if enabled
  9738. async with async_session() as db:
  9739. from backend.app.api.routes.settings import get_setting
  9740. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  9741. spoolman_url = await get_setting(db, "spoolman_url")
  9742. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  9743. try:
  9744. client = await init_spoolman_client(spoolman_url)
  9745. if await client.health_check():
  9746. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  9747. # Ensure the 'tag' extra field exists for RFID/UUID storage
  9748. field_ok = await client.ensure_tag_extra_field()
  9749. if not field_ok:
  9750. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  9751. # Register the BambuStudio slicer-preset fields used by the
  9752. # spool-edit / assign flow. Spoolman rejects PATCHes with
  9753. # unknown extra keys, so these must exist before any update
  9754. # that touches them.
  9755. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  9756. if not await client.ensure_extra_field(field_name):
  9757. logging.warning(
  9758. "Spoolman extra field %r registration failed — "
  9759. "spool slicer-preset edits will return 502",
  9760. field_name,
  9761. )
  9762. else:
  9763. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  9764. except Exception as e:
  9765. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  9766. # Start the print scheduler
  9767. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  9768. # Start the smart plug scheduler for time-based on/off
  9769. smart_plug_manager.start_scheduler()
  9770. # Start the Home Assistant sensor poller (#1148)
  9771. ha_sensor_manager.start()
  9772. location_ha_sensor_manager.start()
  9773. # Resume any pending auto-offs that were interrupted by restart
  9774. await smart_plug_manager.resume_pending_auto_offs()
  9775. # Start the notification digest scheduler
  9776. notification_service.start_digest_scheduler()
  9777. notify_live_activities.start()
  9778. notify_widgets.start()
  9779. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  9780. # provider in reactions/both mode; the notification routes resync them.
  9781. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  9782. # until the next provider save, not the whole startup.
  9783. try:
  9784. await telegram_reaction_poller.start()
  9785. except Exception as e:
  9786. logging.warning("Telegram reaction poller did not start: %s", e)
  9787. # Start the GitHub backup scheduler
  9788. await github_backup_service.start_scheduler()
  9789. # Start the local backup scheduler
  9790. await local_backup_service.start_scheduler()
  9791. await obico_detection_service.start()
  9792. # Start the library trash sweeper (#1008)
  9793. await library_trash_service.start_scheduler()
  9794. # Start the archive auto-purge sweeper (#1008 follow-up)
  9795. await archive_purge_service.start_scheduler()
  9796. # Start AMS history recording
  9797. start_ams_history_recording()
  9798. # Start printer sensor (nozzle / bed / chamber) history recording
  9799. start_printer_sensor_history_recording()
  9800. # Start printer runtime tracking
  9801. start_runtime_tracking()
  9802. # Start SpoolBuddy device watchdog
  9803. start_spoolbuddy_watchdog()
  9804. # Start camera stream orphan cleanup
  9805. start_camera_cleanup()
  9806. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  9807. start_connection_watchdog()
  9808. # One-shot sweep for timelapse session directories orphaned by a crash
  9809. # or restart that happened mid-print (in-memory session tracking can't
  9810. # survive that, and nothing else reaps the leftover frames/output file)
  9811. try:
  9812. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9813. removed = cleanup_orphaned_timelapse_sessions()
  9814. if removed:
  9815. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  9816. except Exception as e:
  9817. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  9818. # Start expected-print TTL eviction (prevents memory leak when prints are
  9819. # registered but on_print_start never fires)
  9820. start_expected_prints_cleanup()
  9821. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  9822. start_auth_cleanup()
  9823. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  9824. from backend.app.services import announcements as announcements_service
  9825. announcements_service.start()
  9826. from backend.app.services.printer_media import start_printer_download_cleanup
  9827. start_printer_download_cleanup()
  9828. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  9829. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  9830. from backend.app.services.loop_watchdog import start_loop_watchdog
  9831. start_loop_watchdog()
  9832. # Initialize virtual printer manager and sync from DB
  9833. from backend.app.services.virtual_printer import virtual_printer_manager
  9834. virtual_printer_manager.set_session_factory(async_session)
  9835. virtual_printer_manager.set_printer_manager(printer_manager)
  9836. try:
  9837. await virtual_printer_manager.sync_from_db()
  9838. logging.info("Virtual printer manager synced from database")
  9839. except Exception as e:
  9840. logging.warning("Failed to sync virtual printers: %s", e)
  9841. yield
  9842. # Shutdown
  9843. print_scheduler.stop()
  9844. smart_plug_manager.stop_scheduler()
  9845. ha_sensor_manager.stop()
  9846. location_ha_sensor_manager.stop()
  9847. notification_service.stop_digest_scheduler()
  9848. await notify_live_activities.close()
  9849. await notify_widgets.close()
  9850. await telegram_reaction_poller.aclose()
  9851. github_backup_service.stop_scheduler()
  9852. local_backup_service.stop_scheduler()
  9853. library_trash_service.stop_scheduler()
  9854. archive_purge_service.stop_scheduler()
  9855. obico_detection_service.stop()
  9856. stop_ams_history_recording()
  9857. stop_printer_sensor_history_recording()
  9858. stop_runtime_tracking()
  9859. stop_spoolbuddy_watchdog()
  9860. stop_camera_cleanup()
  9861. stop_connection_watchdog()
  9862. from backend.app.services.loop_watchdog import stop_loop_watchdog
  9863. stop_loop_watchdog()
  9864. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  9865. # cleanly rather than waiting on a queue that nothing will ever fill.
  9866. try:
  9867. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  9868. await shutdown_all_broadcasters()
  9869. except Exception as e:
  9870. logging.warning("Failed to shut down camera broadcasters: %s", e)
  9871. stop_expected_prints_cleanup()
  9872. stop_auth_cleanup()
  9873. from backend.app.services import announcements as announcements_service
  9874. announcements_service.stop()
  9875. from backend.app.services.printer_media import stop_printer_download_cleanup
  9876. await stop_printer_download_cleanup()
  9877. printer_manager.disconnect_all()
  9878. slot_unlink_grace.reset()
  9879. await close_spoolman_client()
  9880. # Stop all virtual printer services
  9881. await virtual_printer_manager.stop_all()
  9882. await mqtt_smart_plug_service.disconnect(timeout=2)
  9883. await mqtt_relay.disconnect(timeout=2)
  9884. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  9885. set_shared_http_client(None)
  9886. set_shared_makerworld_http_client(None)
  9887. set_shared_orca_http_client(None)
  9888. await _shared_cloud_http_client.aclose()
  9889. # Checkpoint WAL (SQLite only) and close all database connections
  9890. from backend.app.core.db_dialect import is_sqlite
  9891. if is_sqlite():
  9892. try:
  9893. async with engine.begin() as conn:
  9894. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  9895. logging.info("WAL checkpoint completed")
  9896. except Exception as e:
  9897. logging.warning("WAL checkpoint failed: %s", e)
  9898. await engine.dispose()
  9899. app = FastAPI(
  9900. title=app_settings.app_name,
  9901. description="Archive and manage Bambu Lab 3MF files",
  9902. version=APP_VERSION,
  9903. lifespan=lifespan,
  9904. )
  9905. # Added first so it sits innermost, next to the routes: a refused header's value
  9906. # (often a stored token) masked in every JSON body. See core.response_redaction.
  9907. app.add_middleware(RefusedHeaderResponseMask)
  9908. def _json_safe(value):
  9909. """The validation errors with every non-finite number written as text."""
  9910. if isinstance(value, float) and not math.isfinite(value):
  9911. return str(value)
  9912. if isinstance(value, dict):
  9913. return {key: _json_safe(item) for key, item in value.items()}
  9914. if isinstance(value, list | tuple):
  9915. return [_json_safe(item) for item in value]
  9916. return value
  9917. @app.exception_handler(RequestValidationError)
  9918. async def _validation_error(_request, exc: RequestValidationError) -> JSONResponse:
  9919. """FastAPI's own 422, except that it survives a non-finite number.
  9920. A body may carry ``Infinity`` or ``NaN`` (Python's JSON reader accepts
  9921. them), and the default handler echoes the input back in its errors,
  9922. which JSON cannot hold: the request ended in an error instead of a 422.
  9923. """
  9924. return JSONResponse(status_code=422, content={"detail": _json_safe(jsonable_encoder(exc.errors()))})
  9925. # =============================================================================
  9926. # Authentication Middleware - Secures ALL API routes by default
  9927. # =============================================================================
  9928. # Public routes that don't require authentication even when auth is enabled
  9929. PUBLIC_API_ROUTES = {
  9930. # Auth routes needed before/during login
  9931. "/api/v1/auth/status",
  9932. "/api/v1/auth/login",
  9933. "/api/v1/auth/setup", # Needed for initial setup and recovery
  9934. # Advanced auth status needed for login page
  9935. "/api/v1/auth/advanced-auth/status",
  9936. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  9937. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  9938. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  9939. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  9940. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  9941. # OIDC routes that must be reachable without a JWT
  9942. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  9943. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  9944. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  9945. # Connected apps: the app's server swaps a code for the user's identity,
  9946. # authenticated by its client secret rather than a login token.
  9947. "/api/v1/connect/token",
  9948. # Version check for updates (no sensitive data)
  9949. "/api/v1/updates/version",
  9950. # Metrics endpoint handles its own prometheus_token authentication
  9951. "/api/v1/metrics",
  9952. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  9953. # this BEFORE a JWT is available to pick up the firstboot wizard's
  9954. # hostname / timezone / locale and the chrony NTP-gate state. The
  9955. # response contains user-set defaults and a public sync flag — no
  9956. # secrets. Without this entry the global auth middleware returns 401
  9957. # before the route handler runs, regardless of the route's own
  9958. # "no auth required" intent.
  9959. "/api/v1/system/appliance",
  9960. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  9961. # authenticates with a long-lived ``camwall``-scoped token in the query
  9962. # string — exactly like the camera streams two lists below, and for the same
  9963. # reason (no header to put a JWT in). "Public" here only means the middleware
  9964. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  9965. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  9966. # plain ``camera_stream`` token does NOT open this door.
  9967. "/api/v1/camwall/printers",
  9968. # Overlay branding: the route enforces overlay-scoped token authentication.
  9969. "/api/v1/overlay-branding/logo",
  9970. }
  9971. # Route prefixes that are public (for routes with dynamic segments)
  9972. PUBLIC_API_PREFIXES = [
  9973. # WebSocket connections handle their own auth
  9974. "/api/v1/ws",
  9975. # OIDC authorize redirects — include provider_id in path
  9976. "/api/v1/auth/oidc/authorize/",
  9977. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  9978. # a phone with no session, so no header can carry a JWT — the single-use
  9979. # capability token in the path IS the credential (same reasoning as the
  9980. # /dl/ slicer downloads below). The route grants nothing beyond writing
  9981. # good/reject on the one archive the token was minted for.
  9982. "/api/v1/archives/confirm/",
  9983. ]
  9984. # Route patterns that are public (read-only display data)
  9985. # These are checked with "in path" - needed because browsers load images/videos
  9986. # via <img src> and <video src> which don't include Authorization headers
  9987. PUBLIC_API_PATTERNS = [
  9988. # Thumbnails
  9989. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  9990. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  9991. # Images and media
  9992. "/photos/", # /archives/{id}/photos/{filename}
  9993. "/project-image/", # /archives/{id}/project-image/{path}
  9994. "/qrcode", # /archives/{id}/qrcode
  9995. "/timelapse", # /archives/{id}/timelapse (video)
  9996. "/cover", # /printers/{id}/cover
  9997. "/icon", # /external-links/{id}/icon
  9998. # Camera (streams loaded via <img> tag)
  9999. "/camera/stream", # /printers/{id}/camera/stream
  10000. "/camera/snapshot", # /printers/{id}/camera/snapshot
  10001. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  10002. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  10003. # string (same reasoning as the camera streams above — no header to carry a
  10004. # JWT). "Public" only means the middleware steps aside; the route still runs
  10005. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  10006. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  10007. "/overlay-status", # /printers/{id}/overlay-status
  10008. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  10009. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  10010. # download token in the URL path instead.
  10011. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  10012. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  10013. # and these patterns match by substring. Without its own entry the middleware
  10014. # 401s the slicer's header-less request before the route's token check runs,
  10015. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  10016. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  10017. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  10018. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  10019. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  10020. ]
  10021. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  10022. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  10023. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  10024. Format: comma-separated list of ``scheme://host[:port]`` origins.
  10025. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  10026. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  10027. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  10028. Invalid entries are dropped with a warning rather than failing startup, so
  10029. a typo in one origin doesn't take the whole deployment down.
  10030. """
  10031. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  10032. if not raw:
  10033. return ()
  10034. valid: list[str] = []
  10035. for item in raw.split(","):
  10036. candidate = item.strip()
  10037. if not candidate:
  10038. continue
  10039. try:
  10040. parsed = urlparse(candidate)
  10041. except ValueError as e:
  10042. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  10043. continue
  10044. if parsed.scheme not in ("http", "https"):
  10045. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  10046. continue
  10047. if not parsed.netloc:
  10048. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  10049. continue
  10050. if parsed.path and parsed.path != "/":
  10051. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  10052. continue
  10053. if parsed.query or parsed.fragment:
  10054. _security_headers_logger.warning(
  10055. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  10056. )
  10057. continue
  10058. if "*" in parsed.netloc:
  10059. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  10060. continue
  10061. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  10062. if valid:
  10063. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  10064. return tuple(valid)
  10065. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  10066. def _frame_ancestors(default_value: str) -> str:
  10067. """Compose the ``frame-ancestors`` CSP directive (#1191).
  10068. ``default_value`` is the strict directive used when the operator has not
  10069. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  10070. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  10071. Settings URL builder's preview). When trusted origins
  10072. are configured, ``'self'`` is always included so same-origin embedding never
  10073. breaks even if an operator forgets to add their own origin to the list.
  10074. """
  10075. if _TRUSTED_FRAME_ORIGINS:
  10076. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  10077. return f"frame-ancestors {default_value};"
  10078. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  10079. # patterns are anchored on the exact emitted name so the relaxed policies
  10080. # below can never apply to any other asset.
  10081. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  10082. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  10083. # -> /assets/pdf.worker.min-<hash>.js
  10084. # Vite also emits a one-line chunk under the second name that only exports the
  10085. # worker's URL. The page imports it as a module, and a module script is run
  10086. # under the importing document's policy, never its own response's, so it
  10087. # matching as well changes nothing.
  10088. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  10089. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  10090. @app.middleware("http")
  10091. async def security_headers_middleware(request, call_next):
  10092. """Add standard HTTP security headers to every response."""
  10093. # Per-request nonce stamped into `script-src` (#1460). On its own this
  10094. # changes nothing for Bambuddy's own pages — index.html has no inline
  10095. # scripts since the SW registration moved to /sw-register.js. The reason
  10096. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  10097. # script injected into the HTML on the edge, with a fresh hash on every
  10098. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  10099. # it clones the same nonce onto its injected <script>, and the inline
  10100. # script passes the policy without us needing 'unsafe-inline'. See
  10101. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  10102. csp_nonce = secrets.token_urlsafe(16)
  10103. # Routes that render their own HTML need it too, or their inline script is
  10104. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  10105. # one that does: it submits its own form so a verdict still costs one tap.
  10106. request.state.csp_nonce = csp_nonce
  10107. response = await call_next(request)
  10108. response.headers["X-Content-Type-Options"] = "nosniff"
  10109. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  10110. # browsers honour CSP frame-ancestors instead, and the legacy
  10111. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  10112. # When operators have explicitly allowlisted trusted frame origins (#1191
  10113. # — typically Home Assistant on a different port), drop X-Frame-Options
  10114. # and let the CSP-side frame-ancestors directive govern embedding.
  10115. if not _TRUSTED_FRAME_ORIGINS:
  10116. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  10117. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  10118. # Content-Security-Policy for the React SPA.
  10119. # Notes:
  10120. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  10121. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  10122. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  10123. # - media-src blob:: timelapse video player uses Blob URLs.
  10124. # - font-src data:: some icon fonts are embedded as data URIs.
  10125. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  10126. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  10127. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  10128. # default CSP would render a blank page.
  10129. response.headers["Content-Security-Policy"] = (
  10130. "default-src 'self'; "
  10131. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  10132. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  10133. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  10134. "connect-src 'self'; "
  10135. "font-src 'self' data: https://fonts.gstatic.com; "
  10136. "worker-src 'self' blob:; "
  10137. "object-src 'none'; "
  10138. "base-uri 'self'; " + _frame_ancestors("'none'")
  10139. )
  10140. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  10141. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  10142. # its emscripten/embind glue generates invoker functions with `new
  10143. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  10144. # worker is governed by the policy delivered with the WORKER SCRIPT's
  10145. # own response — not the document's — so relaxing it here confines
  10146. # eval to that DOM-less worker context. The document policy below
  10147. # stays nonce-strict, and this response header has no effect when the
  10148. # file is merely fetched (a fetch's CSP is enforced against the
  10149. # requesting document, not the resource's own headers).
  10150. response.headers["Content-Security-Policy"] = (
  10151. "default-src 'self'; "
  10152. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  10153. "connect-src 'self'; "
  10154. "object-src 'none'; "
  10155. "base-uri 'self'; " + _frame_ancestors("'none'")
  10156. )
  10157. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  10158. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  10159. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  10160. # rule as the STEP worker above: the policy that governs a dedicated
  10161. # worker is the one delivered with its own script, so the wasm compile
  10162. # has to be permitted here rather than on the document. Unlike the STEP
  10163. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  10164. response.headers["Content-Security-Policy"] = (
  10165. "default-src 'self'; "
  10166. "script-src 'self' 'wasm-unsafe-eval'; "
  10167. "connect-src 'self'; "
  10168. "object-src 'none'; "
  10169. "base-uri 'self'; " + _frame_ancestors("'none'")
  10170. )
  10171. else:
  10172. # The streaming overlay is embedded same-origin by the URL builder's
  10173. # preview in Settings (#1422), so this branch allows 'self'.
  10174. # Embedding from anywhere else is still refused: 'self'
  10175. # only permits a framer on this origin, which is Bambuddy's own UI, so
  10176. # a clickjacking page on another host is blocked exactly as before.
  10177. # (The overlay draws status over a camera feed and its only interactive
  10178. # element is the logo link, so there is nothing to bait a click into
  10179. # even from a same-origin framer.) Cross-origin embedding of the
  10180. # overlay — Home Assistant on another port — remains what
  10181. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  10182. # allowlist in.
  10183. #
  10184. # The connected-app consent page (/connect/authorize) gets the same
  10185. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  10186. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  10187. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  10188. # requires every ancestor to be this origin, so a foreign page -- a
  10189. # sidebar link's site included -- still cannot frame the consent
  10190. # screen to bait a click.
  10191. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  10192. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  10193. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  10194. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  10195. # the policy served with their own script, so each gets it in its own
  10196. # branch above and the document policy stays as strict as it was.
  10197. response.headers["Content-Security-Policy"] = (
  10198. "default-src 'self'; "
  10199. f"script-src 'self' 'nonce-{csp_nonce}'; "
  10200. "style-src 'self' 'unsafe-inline'; "
  10201. "img-src 'self' data: blob:; "
  10202. "media-src 'self' blob:; "
  10203. "connect-src 'self' ws: wss:; "
  10204. "font-src 'self' data:; "
  10205. "object-src 'none'; "
  10206. "base-uri 'self'; "
  10207. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  10208. )
  10209. if request.url.scheme == "https":
  10210. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  10211. return response
  10212. @app.middleware("http")
  10213. async def auth_middleware(request, call_next):
  10214. """Enforce authentication on all API routes when auth is enabled.
  10215. This middleware provides defense-in-depth by checking auth at the API gateway level,
  10216. regardless of whether individual routes have auth dependencies.
  10217. """
  10218. from starlette.responses import JSONResponse
  10219. path = request.url.path
  10220. # Only apply to API routes
  10221. if not path.startswith("/api/"):
  10222. return await call_next(request)
  10223. # Allow public routes
  10224. if path in PUBLIC_API_ROUTES:
  10225. return await call_next(request)
  10226. # Allow public prefixes
  10227. for prefix in PUBLIC_API_PREFIXES:
  10228. if path.startswith(prefix):
  10229. return await call_next(request)
  10230. # Allow public patterns (read-only display data like thumbnails)
  10231. for pattern in PUBLIC_API_PATTERNS:
  10232. if pattern in path:
  10233. return await call_next(request)
  10234. # Check if auth is enabled. Fail CLOSED on any exception during the
  10235. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  10236. # an attacker who could force a DB exception (e.g. file-descriptor
  10237. # exhaustion via login flood) bypass auth on every protected endpoint.
  10238. # Only the probe is guarded: the request itself runs outside the try, so an
  10239. # error in a route surfaces as the 500 it is rather than as an auth outage.
  10240. try:
  10241. async with async_session() as db:
  10242. from backend.app.core.auth import is_auth_enabled
  10243. auth_enabled = await is_auth_enabled(db)
  10244. except Exception:
  10245. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  10246. return JSONResponse(
  10247. status_code=503,
  10248. content={"detail": "Authentication service temporarily unavailable"},
  10249. )
  10250. if not auth_enabled:
  10251. # Auth disabled, allow all requests
  10252. return await call_next(request)
  10253. # Auth is enabled - require valid token
  10254. auth_header = request.headers.get("Authorization")
  10255. x_api_key = request.headers.get("X-API-Key")
  10256. # Check for API key auth first
  10257. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  10258. # API key authentication - let the request through to be validated by route handler
  10259. # API keys are validated per-route since they have different permission levels
  10260. return await call_next(request)
  10261. # Check for JWT auth
  10262. if not auth_header or not auth_header.startswith("Bearer "):
  10263. return JSONResponse(
  10264. status_code=401,
  10265. content={"detail": "Authentication required"},
  10266. headers={"WWW-Authenticate": "Bearer"},
  10267. )
  10268. # Validate JWT token
  10269. import jwt
  10270. try:
  10271. from backend.app.core.auth import (
  10272. ALGORITHM,
  10273. SECRET_KEY,
  10274. _is_token_fresh,
  10275. get_user_by_username,
  10276. is_jti_revoked,
  10277. )
  10278. token = auth_header.replace("Bearer ", "")
  10279. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  10280. username = payload.get("sub")
  10281. if not username:
  10282. raise ValueError("No username in token")
  10283. jti = payload.get("jti")
  10284. if not jti:
  10285. raise ValueError("No jti in token")
  10286. iat = payload.get("iat")
  10287. # Verify user exists, is active, and token is still fresh (L-R8-A).
  10288. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  10289. # this session so the gateway adds a single pooled checkout, not two (#2572).
  10290. async with async_session() as db:
  10291. if await is_jti_revoked(jti, db):
  10292. return JSONResponse(
  10293. status_code=401,
  10294. content={"detail": "Token has been revoked"},
  10295. headers={"WWW-Authenticate": "Bearer"},
  10296. )
  10297. user = await get_user_by_username(db, username)
  10298. if not user or not user.is_active:
  10299. return JSONResponse(
  10300. status_code=401,
  10301. content={"detail": "User not found or inactive"},
  10302. headers={"WWW-Authenticate": "Bearer"},
  10303. )
  10304. if not _is_token_fresh(iat, user):
  10305. return JSONResponse(
  10306. status_code=401,
  10307. content={"detail": "Token no longer valid"},
  10308. headers={"WWW-Authenticate": "Bearer"},
  10309. )
  10310. except jwt.ExpiredSignatureError:
  10311. return JSONResponse(
  10312. status_code=401,
  10313. content={"detail": "Token has expired"},
  10314. headers={"WWW-Authenticate": "Bearer"},
  10315. )
  10316. except (jwt.InvalidTokenError, ValueError):
  10317. return JSONResponse(
  10318. status_code=401,
  10319. content={"detail": "Invalid token"},
  10320. headers={"WWW-Authenticate": "Bearer"},
  10321. )
  10322. except Exception:
  10323. # Not a bad token but a failure checking it (database, pool): refuse,
  10324. # as for the probe above, rather than answer 401 -- the frontend reads
  10325. # a 401 from /auth/me as final and signs the user out.
  10326. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  10327. return JSONResponse(
  10328. status_code=503,
  10329. content={"detail": "Authentication service temporarily unavailable"},
  10330. )
  10331. return await call_next(request)
  10332. @app.middleware("http")
  10333. async def trace_id_middleware(request, call_next):
  10334. """Stamp every HTTP request with a trace ID and echo it back.
  10335. Decorated AFTER auth_middleware on purpose: Starlette stacks
  10336. @app.middleware decorators LIFO, so the last-decorated runs first
  10337. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  10338. which means auth-middleware log lines (and every line emitted on the
  10339. way down to and back from the route handler) all carry the same
  10340. trace ID. If we put it before auth, auth's logs would be stamped
  10341. with the *previous* request's ID — useless for correlation.
  10342. Honours an inbound ``X-Trace-Id`` header so callers running their
  10343. own tracing can correlate their span IDs with our log lines, but
  10344. only if the value passes the whitelist gate in
  10345. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  10346. rejected (too long, contains control chars, etc.) silently triggers
  10347. a freshly minted server-side ID rather than failing the request.
  10348. The minted (or echoed) ID is set on a ContextVar so that every log
  10349. record emitted during the request — application logs *and* uvicorn's
  10350. access log — carries it via TraceIDFilter, and is also written to
  10351. the ``X-Trace-Id`` response header so clients can pin a server-side
  10352. log search to the exact request they made.
  10353. """
  10354. from backend.app.core.trace import (
  10355. generate_trace_id,
  10356. normalise_inbound_trace_id,
  10357. trace_id_var,
  10358. )
  10359. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  10360. trace_id = inbound if inbound is not None else generate_trace_id()
  10361. token = trace_id_var.set(trace_id)
  10362. try:
  10363. response = await call_next(request)
  10364. finally:
  10365. # Reset the ContextVar so a record emitted in a totally
  10366. # unrelated background task that just happens to inherit this
  10367. # context doesn't keep referencing this request's ID forever.
  10368. # In practice ContextVar.reset is best-effort under asyncio
  10369. # task-spawn semantics, but the cost is one attribute write so
  10370. # we may as well do it.
  10371. trace_id_var.reset(token)
  10372. response.headers["X-Trace-Id"] = trace_id
  10373. return response
  10374. # API routes
  10375. app.include_router(auth.router, prefix=app_settings.api_prefix)
  10376. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  10377. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  10378. app.include_router(users.router, prefix=app_settings.api_prefix)
  10379. app.include_router(groups.router, prefix=app_settings.api_prefix)
  10380. app.include_router(printers.router, prefix=app_settings.api_prefix)
  10381. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  10382. app.include_router(archives.router, prefix=app_settings.api_prefix)
  10383. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  10384. app.include_router(finance.router, prefix=app_settings.api_prefix)
  10385. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  10386. app.include_router(labels.router, prefix=app_settings.api_prefix)
  10387. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  10388. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  10389. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  10390. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  10391. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  10392. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  10393. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  10394. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  10395. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  10396. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  10397. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  10398. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  10399. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  10400. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  10401. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  10402. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  10403. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  10404. app.include_router(updates.router, prefix=app_settings.api_prefix)
  10405. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  10406. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  10407. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  10408. app.include_router(camera.router, prefix=app_settings.api_prefix)
  10409. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  10410. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  10411. app.include_router(projects.router, prefix=app_settings.api_prefix)
  10412. app.include_router(library.router, prefix=app_settings.api_prefix)
  10413. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  10414. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  10415. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  10416. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  10417. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  10418. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  10419. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  10420. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  10421. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  10422. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  10423. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  10424. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  10425. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  10426. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  10427. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  10428. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  10429. app.include_router(system.router, prefix=app_settings.api_prefix)
  10430. app.include_router(support.router, prefix=app_settings.api_prefix)
  10431. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  10432. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  10433. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  10434. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  10435. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  10436. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  10437. app.include_router(obico.router, prefix=app_settings.api_prefix)
  10438. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  10439. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  10440. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  10441. # Serve static files (React build)
  10442. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  10443. # Compressed, and cached for good where Vite hashed the name (#3175).
  10444. app.mount(
  10445. "/assets",
  10446. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  10447. name="assets",
  10448. )
  10449. if (app_settings.static_dir / "img").exists():
  10450. app.mount(
  10451. "/img",
  10452. StaticFiles(directory=app_settings.static_dir / "img"),
  10453. name="img",
  10454. )
  10455. if (app_settings.static_dir / "icons").exists():
  10456. app.mount(
  10457. "/icons",
  10458. StaticFiles(directory=app_settings.static_dir / "icons"),
  10459. name="icons",
  10460. )
  10461. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  10462. # falls through to the SPA catch-all and returns index.html, which the
  10463. # browser's font sanitizer rejects ("downloadable font: rejected by
  10464. # sanitizer").
  10465. if (app_settings.static_dir / "fonts").exists():
  10466. app.mount(
  10467. "/fonts",
  10468. StaticFiles(directory=app_settings.static_dir / "fonts"),
  10469. name="fonts",
  10470. )
  10471. @app.get("/")
  10472. async def serve_frontend():
  10473. """Serve the React frontend."""
  10474. index_file = app_settings.static_dir / "index.html"
  10475. if index_file.exists():
  10476. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10477. return {
  10478. "message": "Bambuddy API",
  10479. "docs": "/docs",
  10480. "frontend": "Build and place React app in /static directory",
  10481. }
  10482. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  10483. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  10484. # forever, but the HTML wrapping it is the only file that knows which hash
  10485. # is current. Without explicit cache-control headers Chromium decides
  10486. # heuristically (typically 10% of the time since Last-Modified) and on
  10487. # long-running kiosks happily serves stale HTML across browser restarts.
  10488. # That stale HTML references an old bundle hash, the old bundle is also
  10489. # in the disk cache, and the user ends up running pre-update JS forever
  10490. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  10491. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  10492. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  10493. @app.get("/health")
  10494. async def health_check():
  10495. """Health check endpoint."""
  10496. return {"status": "healthy"}
  10497. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  10498. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  10499. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  10500. # in deployment debugging.
  10501. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  10502. async def serve_manifest():
  10503. """Serve PWA manifest."""
  10504. manifest_file = app_settings.static_dir / "manifest.json"
  10505. if manifest_file.exists():
  10506. return FileResponse(manifest_file, media_type="application/manifest+json")
  10507. return {"error": "Manifest not found"}
  10508. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  10509. async def serve_service_worker():
  10510. """Serve service worker."""
  10511. sw_file = app_settings.static_dir / "sw.js"
  10512. if sw_file.exists():
  10513. return FileResponse(
  10514. sw_file,
  10515. media_type="application/javascript",
  10516. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  10517. )
  10518. return {"error": "Service worker not found"}
  10519. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  10520. async def serve_sw_register():
  10521. """Serve the service-worker registration bootstrap script.
  10522. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  10523. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  10524. """
  10525. reg_file = app_settings.static_dir / "sw-register.js"
  10526. if reg_file.exists():
  10527. return FileResponse(reg_file, media_type="application/javascript")
  10528. return {"error": "sw-register.js not found"}
  10529. # ── GCode viewer static files ────────────────────────────────────────────────
  10530. # Catch-all route for React Router (must be last)
  10531. @app.get("/{full_path:path}")
  10532. async def serve_spa(full_path: str):
  10533. """Serve React app for client-side routing."""
  10534. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  10535. if full_path.startswith("api/"):
  10536. from fastapi import HTTPException
  10537. raise HTTPException(status_code=404, detail="Not found")
  10538. index_file = app_settings.static_dir / "index.html"
  10539. if index_file.exists():
  10540. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10541. return {"error": "Frontend not built"}