main.py 637 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132
  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 shutil
  10. import time
  11. from contextlib import asynccontextmanager
  12. from datetime import datetime, timedelta, timezone
  13. from logging.handlers import RotatingFileHandler
  14. from pathlib import Path, PurePosixPath
  15. from typing import cast
  16. from urllib.parse import urlparse
  17. from fastapi import FastAPI
  18. from fastapi.encoders import jsonable_encoder
  19. from fastapi.exceptions import RequestValidationError
  20. from fastapi.responses import FileResponse, JSONResponse
  21. from fastapi.staticfiles import StaticFiles
  22. from sqlalchemy import delete, func, inspect as sa_inspect, or_, select, text, update
  23. from sqlalchemy.engine import CursorResult
  24. from sqlalchemy.exc import IntegrityError
  25. from sqlalchemy.orm.exc import StaleDataError
  26. from backend.app.api.routes import (
  27. ams_history,
  28. announcements,
  29. api_keys,
  30. archive_purge,
  31. archives,
  32. auth,
  33. bug_report,
  34. bulk,
  35. camera,
  36. camwall,
  37. cloud,
  38. connected_apps,
  39. discovery,
  40. external_links,
  41. filaments,
  42. finance,
  43. firmware,
  44. github_backup,
  45. groups,
  46. ha_sensors,
  47. inventory,
  48. kprofiles,
  49. label_templates,
  50. labels,
  51. library,
  52. library_tags,
  53. library_trash,
  54. library_variants,
  55. local_backup,
  56. local_presets,
  57. location_ha_sensors,
  58. maintenance,
  59. makerworld,
  60. manyfold,
  61. metrics,
  62. mfa,
  63. notification_templates,
  64. notifications,
  65. obico,
  66. orca_cloud,
  67. overlay_branding,
  68. pending_uploads,
  69. pipeline_runs,
  70. print_log,
  71. print_queue,
  72. printer_locations,
  73. printer_sensor_history,
  74. printers,
  75. projects,
  76. scheduled_dryings,
  77. settings as settings_routes,
  78. slice_jobs,
  79. slicer_pipelines,
  80. slicer_presets,
  81. smart_plugs,
  82. sponsor_prompt,
  83. spoolbuddy,
  84. spoolman,
  85. spoolman_inventory,
  86. support,
  87. system,
  88. updates,
  89. user_notifications,
  90. users,
  91. virtual_printers,
  92. webhook,
  93. websocket,
  94. )
  95. from backend.app.api.routes.maintenance import (
  96. _get_printer_maintenance_internal,
  97. ensure_default_types,
  98. maintenance_alert_values,
  99. )
  100. from backend.app.api.routes.support import init_debug_logging
  101. from backend.app.core.config import APP_VERSION, settings as app_settings
  102. from backend.app.core.database import async_session, engine, init_db
  103. from backend.app.core.static_assets import AssetStaticFiles
  104. from backend.app.core.tasks import spawn_background_task
  105. from backend.app.core.websocket import ws_manager
  106. from backend.app.services import kprofile_drift, pause_eta, print_dispatch_context, slot_unlink_grace
  107. from backend.app.services.ams_assignment_lock import get_ams_assignment_lock
  108. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  109. from backend.app.services.archive_cost_estimate import (
  110. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  111. settle_archive_cost_estimate as _settle_archive_cost_estimate,
  112. )
  113. from backend.app.services.archive_purge import archive_purge_service
  114. from backend.app.services.bambu_ftp import (
  115. RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  116. FileNotOnPrinterError,
  117. cache_3mf_download,
  118. clear_3mf_cache,
  119. download_file_async,
  120. download_file_try_paths_async,
  121. ftps_handshake_blocked,
  122. get_cached_3mf,
  123. get_ftp_retry_settings,
  124. normalize_3mf_name,
  125. with_ftp_retry,
  126. )
  127. from backend.app.services.bambu_mqtt import PrinterState
  128. from backend.app.services.camera_light import camera_light
  129. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  130. from backend.app.services.github_backup import github_backup_service
  131. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  132. from backend.app.services.library_trash import library_trash_service
  133. from backend.app.services.local_backup import local_backup_service
  134. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  135. from backend.app.services.mqtt_relay import mqtt_relay
  136. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  137. from backend.app.services.notification_service import notification_service
  138. from backend.app.services.notify_live_activities import notify_live_activities
  139. from backend.app.services.notify_widgets import notify_widgets
  140. from backend.app.services.obico_detection import obico_detection_service
  141. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  142. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  143. from backend.app.services.print_scheduler import scheduler as print_scheduler
  144. from backend.app.services.print_storage import (
  145. REASON_FTP_TRANSFER_FAILED,
  146. REASON_FTPS_COOLOFF,
  147. external_storage_present,
  148. ftp_probe_paths,
  149. print_file_reachable_over_ftp,
  150. )
  151. from backend.app.services.printer_manager import (
  152. init_printer_connections,
  153. parse_plate_id,
  154. printer_manager,
  155. printer_state_to_dict,
  156. resolve_plate_id,
  157. )
  158. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  159. from backend.app.services.slot_nozzle import (
  160. nozzle_diameter_for_extruder,
  161. nozzle_flow_for_extruder,
  162. )
  163. from backend.app.services.smart_plug_manager import smart_plug_manager
  164. from backend.app.services.spool_assignment_notifications import (
  165. notify_missing_spool_assignments_on_print_start,
  166. )
  167. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  168. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  169. from backend.app.services.spoolman_tracking import (
  170. cleanup_tracking as _cleanup_spoolman_tracking,
  171. release_archived_slot_rows as _release_archived_spoolman_slots,
  172. report_usage as _report_spoolman_usage,
  173. store_print_data as _store_spoolman_print_data,
  174. )
  175. from backend.app.services.telegram_reactions import telegram_reaction_poller
  176. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  177. from backend.app.utils.ams_humidity import ams_humidity_percent
  178. from backend.app.utils.filament_types import printer_filament_type
  179. from backend.app.utils.fts_routing import extruder_for_inlet
  180. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  181. from backend.app.utils.print_jobs import is_internal_printer_job
  182. # =============================================================================
  183. # Dependency Check - runs before other imports to give helpful error messages
  184. # =============================================================================
  185. def _start_error_server(missing_packages: list):
  186. """Start a minimal HTTP server to display dependency errors in browser."""
  187. import os
  188. import signal
  189. from http.server import BaseHTTPRequestHandler, HTTPServer
  190. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  191. html = f"""<!DOCTYPE html>
  192. <html>
  193. <head>
  194. <title>Bambuddy - Setup Required</title>
  195. <style>
  196. body {{
  197. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  198. background: #0f172a; color: #e2e8f0;
  199. display: flex; justify-content: center; align-items: center;
  200. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  201. }}
  202. .container {{
  203. background: #1e293b; border-radius: 12px; padding: 40px;
  204. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  205. }}
  206. h1 {{ color: #f87171; margin-bottom: 10px; }}
  207. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  208. .packages {{
  209. background: #0f172a; border-radius: 8px; padding: 20px;
  210. margin: 20px 0; text-align: left;
  211. }}
  212. .packages ul {{ margin: 0; padding-left: 20px; }}
  213. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  214. .command {{
  215. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  216. margin: 15px 0; font-family: monospace; color: #4ade80;
  217. text-align: left; overflow-x: auto;
  218. }}
  219. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  220. </style>
  221. </head>
  222. <body>
  223. <div class="container">
  224. <h1>Setup Required</h1>
  225. <h2>Missing Python packages</h2>
  226. <div class="packages"><ul>{packages_html}</ul></div>
  227. <p>To fix, run this command on your server:</p>
  228. <div class="command">pip install -r requirements.lock</div>
  229. <p>Or if using a virtual environment:</p>
  230. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  231. <p class="note">After installing, restart Bambuddy:<br>
  232. <code>sudo systemctl restart bambuddy</code></p>
  233. </div>
  234. </body>
  235. </html>"""
  236. class ErrorHandler(BaseHTTPRequestHandler):
  237. def do_GET(self):
  238. self.send_response(503)
  239. self.send_header("Content-type", "text/html")
  240. self.end_headers()
  241. self.wfile.write(html.encode())
  242. def log_message(self, format, *args):
  243. print(f"[Error Server] {args[0]}")
  244. port = int(os.environ.get("PORT", 8000))
  245. print(f"\nStarting error server on http://0.0.0.0:{port}")
  246. print("Visit this URL in your browser to see the error details.\n")
  247. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  248. def shutdown(signum, frame):
  249. print("\nShutting down error server...")
  250. raise SystemExit(0)
  251. signal.signal(signal.SIGTERM, shutdown)
  252. signal.signal(signal.SIGINT, shutdown)
  253. server.serve_forever()
  254. def check_dependencies():
  255. """Check that all required packages are installed."""
  256. missing = []
  257. # Map of import name -> package name (for pip install)
  258. required = {
  259. "jwt": "PyJWT",
  260. "fastapi": "fastapi",
  261. "uvicorn": "uvicorn",
  262. "sqlalchemy": "sqlalchemy",
  263. "aiosqlite": "aiosqlite",
  264. "pydantic": "pydantic",
  265. "paho.mqtt": "paho-mqtt",
  266. }
  267. for module, package in required.items():
  268. try:
  269. __import__(module)
  270. except ImportError:
  271. missing.append(package)
  272. if missing:
  273. print("\n" + "=" * 60)
  274. print("ERROR: Missing required Python packages!")
  275. print("=" * 60)
  276. print(f"\nMissing packages: {', '.join(missing)}")
  277. print("\nTo fix, run:")
  278. print(" pip install -r requirements.lock")
  279. print("\nOr if using a virtual environment:")
  280. print(" ./venv/bin/pip install -r requirements.lock")
  281. print("=" * 60 + "\n")
  282. _start_error_server(missing)
  283. check_dependencies()
  284. # =============================================================================
  285. # Import settings first for logging configuration
  286. # Configure logging based on settings
  287. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  288. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  289. log_level = getattr(logging, log_level_str, logging.INFO)
  290. # Trace ID column ([-] when no request scope is active — startup, MQTT
  291. # callbacks, scheduled tasks not chained from a request — so the column
  292. # stays visually aligned and missing values are obvious in grep). See
  293. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  294. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  295. # Create root logger
  296. root_logger = logging.getLogger()
  297. root_logger.setLevel(log_level)
  298. # Trace-ID injection: this filter populates record.trace_id from the
  299. # per-request ContextVar so the format string above can reference it.
  300. # Attached to each HANDLER (not the root logger) because Python's
  301. # logging semantics only invoke a logger's filters on records that
  302. # *originated* at that logger — records propagated up from child
  303. # loggers (every named logger in the app) never trigger root's filter.
  304. # Putting it on the handlers means every record any handler emits gets
  305. # trace_id injected just before the formatter runs, regardless of which
  306. # logger created the record. Without this, the formatter raises
  307. # KeyError on every child-logger record and the record is silently
  308. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  309. # partially" bug we hit. See backend/app/core/trace.py for the
  310. # ContextVar the filter reads.
  311. from backend.app.core.logging_filters import RefusedHeaderRedactFilter
  312. from backend.app.core.response_redaction import RefusedHeaderResponseMask
  313. from backend.app.core.trace import TraceIDFilter
  314. _trace_id_filter = TraceIDFilter()
  315. # Console handler - always enabled
  316. console_handler = logging.StreamHandler()
  317. console_handler.setLevel(log_level)
  318. console_handler.setFormatter(logging.Formatter(log_format))
  319. console_handler.addFilter(_trace_id_filter)
  320. # A refused header's value (often a token) masked before the line is written.
  321. _refused_header_filter = RefusedHeaderRedactFilter()
  322. console_handler.addFilter(_refused_header_filter)
  323. root_logger.addHandler(console_handler)
  324. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  325. """Send uvicorn's own loggers to bambuddy.log as well.
  326. Neither reaches the root handler: uvicorn.access has propagate=False, and
  327. uvicorn.error propagates only to "uvicorn", which has propagate=False.
  328. uvicorn.access is the record of which endpoint changed server state;
  329. uvicorn.error is where an unhandled route error is logged with its
  330. traceback ("Exception in ASGI application").
  331. """
  332. for name in ("uvicorn.access", "uvicorn.error"):
  333. logging.getLogger(name).addHandler(handler)
  334. # File handler - only in production or if explicitly enabled
  335. if app_settings.log_to_file:
  336. log_file = app_settings.log_dir / "bambuddy.log"
  337. file_handler = RotatingFileHandler(
  338. log_file,
  339. maxBytes=app_settings.log_max_bytes,
  340. backupCount=app_settings.log_backup_count,
  341. encoding="utf-8",
  342. )
  343. file_handler.setLevel(log_level)
  344. file_handler.setFormatter(logging.Formatter(log_format))
  345. file_handler.addFilter(_trace_id_filter)
  346. file_handler.addFilter(_refused_header_filter)
  347. root_logger.addHandler(file_handler)
  348. logging.info("Logging to file: %s", log_file)
  349. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  350. # access logger with propagate=False by default, so without this attach
  351. # there is no on-disk record of which endpoint triggered a server-state
  352. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  353. # for exactly this reason. Filtered to write methods only
  354. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  355. # frontend don't churn the rotation window faster than it's useful.
  356. from backend.app.core.logging_filters import (
  357. CancelledPoolNoiseFilter,
  358. WriteRequestsOnlyFilter,
  359. )
  360. _attach_file_handler_to_uvicorn(file_handler)
  361. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  362. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  363. # Uvicorn's access logger has propagate=False (its own default), so the
  364. # root-attached TraceIDFilter never sees these records. Attach a
  365. # second instance directly so HTTP access lines carry the same trace
  366. # ID column as the application logs they correlate with.
  367. uvicorn_access_logger.addFilter(TraceIDFilter())
  368. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  369. # BaseHTTPMiddleware cancelling the inner task scope on client
  370. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  371. # underlying transaction leak; this filter only suppresses the residual
  372. # log records that pre-existing pools still emit during their cleanup.
  373. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  374. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  375. # handler (console included), whether or not file logging is on.
  376. from backend.app.core.logging_filters import ( # noqa: E402
  377. QueryTokenRedactFilter,
  378. ShutdownCancelledRequestFilter,
  379. )
  380. # First, so the traceback of a stream cancelled at shutdown is dropped before
  381. # the filters below render it.
  382. logging.getLogger("uvicorn.error").addFilter(ShutdownCancelledRequestFilter())
  383. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  384. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  385. logging.getLogger(_uvicorn_logger).addFilter(_refused_header_filter)
  386. # These stay at WARNING even in debug mode: at INFO/DEBUG httpx/httpcore log
  387. # full request URLs, and some carry credentials (bot tokens, webhook URLs, API
  388. # keys in the query). Same as the runtime log-level toggle in support.py.
  389. logging.getLogger("httpcore").setLevel(logging.WARNING)
  390. logging.getLogger("httpx").setLevel(logging.WARNING)
  391. # aiosqlite logs every statement with its parameters at DEBUG.
  392. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  393. # Reduce noise from third-party libraries in production
  394. if not app_settings.debug:
  395. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  396. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  397. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  398. # Track active prints: {(printer_id, filename): archive_id}
  399. _active_prints: dict[tuple[int, str], int] = {}
  400. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  401. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  402. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  403. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  404. # instead of running its own grab-now chain when present, so the finish photo
  405. # captures the better-framed pre-bed-drop moment without us having to force
  406. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  407. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  408. #
  409. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  410. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  411. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  412. # bank and the others are not — so the consumer can't tell them apart and
  413. # must not rotate again.
  414. _stage22_finish_frames: dict[int, bytes] = {}
  415. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  416. # `finally` block (whether it captured a frame or not). The consumer in
  417. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  418. # so the FINISH-state fallback path — where moment and completion are dispatched
  419. # back-to-back — doesn't race past the producer with an empty pop, and the
  420. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  421. # grab (Bambu printers allow only one RTSP client at a time).
  422. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  423. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  424. # layer-change and on print-progress advances (#2547) while the model is still
  425. # printing, then consumed by the FINISH-state finish-photo path when the
  426. # dispatcher recorded that it injected End G-code into this print. Bambu
  427. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  428. # plate-swap) has run, so a live grab there would capture the swapped/empty
  429. # plate.
  430. #
  431. # The load-bearing property: both drivers are print telemetry that stops before
  432. # the End G-code executes — no further layer_num increases, and mc_percent
  433. # freezes — so the last banked frame is always the finished print before the
  434. # swap. Anything added as a third driver must hold that same property.
  435. _inprint_frame_bank: dict[int, bytes] = {}
  436. # Monotonic timestamp of the last banked frame per printer — throttles banking
  437. # so tall prints don't add a camera grab on every layer.
  438. _inprint_frame_bank_ts: dict[int, float] = {}
  439. # Minimum seconds between banked frames, except the final object layer which
  440. # always refreshes for the best framing.
  441. _INPRINT_BANK_MIN_INTERVAL = 25.0
  442. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  443. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  444. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  445. # the first connected status update for that connection; transitions back
  446. # to False whenever we observe `state.connected = False` so the next
  447. # reconnect re-arms reconciliation. Keyed by printer_id.
  448. _printer_reconciled_since_connect: dict[int, bool] = {}
  449. # Same edge, same keying, for priming the printer's calibration table exactly
  450. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  451. # is otherwise filled only when someone opens the Profiles page or Configure
  452. # Slot, when a GitHub backup runs, or when the printer happens to answer
  453. # somebody else's query on the report topic. Until then the AMS slot card has
  454. # no K value to show on the printers whose trays carry none of their own
  455. # (#2854 — H2-series report cali_idx and nothing more).
  456. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  457. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  458. # {(printer_id, filename): archive_id}
  459. _expected_prints: dict[tuple[int, str], int] = {}
  460. # Archives of the running prints Bambuddy dispatched itself: adopted from an
  461. # expected print, or found with Bambuddy's dispatch marker. _active_prints holds
  462. # every print on_print_start archived, those started from Bambu Studio, Handy or
  463. # the printer's screen included, so it is no proof of ownership on its own.
  464. _owned_print_archive_ids: set[int] = set()
  465. # What a dispatch registered for its print, keyed (printer_id, archive_id):
  466. # plates of one archive print on two printers at once, each with its own.
  467. # Track AMS mapping for prints: {(printer_id, archive_id): [global_tray_id_per_slot]}
  468. # Used by usage tracker to map 3MF slots to physical AMS trays
  469. _print_ams_mappings: dict[tuple[int, int], list[int]] = {}
  470. # Track cost center selection for the current print run: {(printer_id, archive_id): cost_center_id}
  471. _print_cost_center_ids: dict[tuple[int, int], int] = {}
  472. # Track plate_id for prints from multi-plate 3MFs: {(printer_id, archive_id): plate_id}
  473. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  474. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  475. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  476. # for the queue path. Cleared on print completion or TTL eviction.
  477. _print_plate_ids: dict[tuple[int, int], int] = {}
  478. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  479. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  480. _last_progress_milestone: dict[int, int] = {}
  481. # Track whether first layer complete notification has been sent for current print
  482. _first_layer_notified: dict[int, bool] = {}
  483. # Track whether we already sent a kill-switch stop for the current unauthorized print
  484. _unauthorized_print_kill_sent: set[int] = set()
  485. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  486. # lookup briefly so an unknown active print does not query the database on
  487. # every status frame. A short TTL keeps settings changes responsive.
  488. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  489. _kill_switch_setting_cache: tuple[bool, float] | None = None
  490. # Provider notification started when the kill switch stops a print. The later
  491. # MQTT print-complete callback awaits this task and only sends its regular
  492. # provider notification when the immediate attempt failed.
  493. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  494. # HMS faults already notified, with when each was last seen:
  495. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  496. # fault that flickers beside a held notice was forgotten on every gap and
  497. # notified on every return (#3226). The window is long because the measured
  498. # gaps reach 64 s.
  499. _notified_hms_errors: dict[int, dict[str, float]] = {}
  500. _HMS_CLEAR_GRACE_SECONDS = 600.0
  501. # The print state each printer was last seen in, and the faults recorded before
  502. # it last changed, which are forgotten as soon as they are gone (see
  503. # _take_new_hms_faults).
  504. _hms_print_state: dict[int, str] = {}
  505. _hms_forget_when_gone: dict[int, set[str]] = {}
  506. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  507. # Used for snapshot-diff detection at print completion
  508. _timelapse_baselines: dict[int, set[str]] = {}
  509. # Printers whose baseline above was taken off a card that could not be read,
  510. # so it is empty without the card being empty (#3412).
  511. _timelapse_baselines_unread: set[int] = set()
  512. # Track printers waiting for bed to cool after print completion.
  513. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  514. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  515. _bed_cool_waiters: dict[int, dict] = {}
  516. # Track printers where the user explicitly stopped the print from the queue UI.
  517. # When on_print_complete fires with status "failed" for these printers we treat it
  518. # as "cancelled" (stopped by user) so the correct notification email is sent.
  519. _user_stopped_printers: set[int] = set()
  520. # Printers whose running print the kill switch stopped. Their completion is a
  521. # cancel with the reason "killSwitch", not the "failed" the printer reports.
  522. _kill_switch_stopped: set[int] = set()
  523. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  524. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  525. # holds the previous observation so we only fire on the True → False edge (a
  526. # False → False repeat doesn't notify; an initial False at startup doesn't
  527. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  528. # holds the per-printer pending asyncio task that fires the notification
  529. # after a debounce window — cancelled if the printer reconnects before the
  530. # window elapses, so transient MQTT blips don't flood the user.
  531. _printer_last_connected: dict[int, bool] = {}
  532. # Printers whose relay offline event went out, so the reconnect publishes the
  533. # matching online event and a blip shorter than the debounce publishes neither.
  534. _printer_offline_published: set[int] = set()
  535. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  536. # Debounce: a printer must stay offline this long before we notify. Sized
  537. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  538. # so a single stale-trigger cooldown isn't enough to fire — only a real
  539. # offline that survives one reconnect attempt notifies.
  540. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  541. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  542. # when status="failed" to label the print's failure_reason in archives.
  543. #
  544. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  545. # which is wrong on two counts:
  546. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  547. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  548. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  549. # the public wiki) as part of its user-cancel sequence. Matching on the module
  550. # alone caused user-cancellations to be archived as "Layer shift" failures.
  551. # We now match by full short code only — anything not in this map leaves
  552. # failure_reason=None rather than guessing.
  553. # Values are the canonical camelCase failure-reason keys, NOT display labels
  554. # (issue #2974). The vocabulary is enforced on writes by
  555. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  556. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  557. # Statistics breakdown. Storing a label here instead put a second spelling of
  558. # the same cause into one column: the Failure Analysis widget groups on the raw
  559. # value, so a print the backend classified and an identical one a user
  560. # classified counted as two different reasons, and the label form could never
  561. # be translated because there was no key for ``t()`` to resolve.
  562. _HMS_FAILURE_REASONS: dict[str, str] = {
  563. # Layer shift / step loss
  564. "0300_4057": "layerShift",
  565. "0300_4068": "layerShift",
  566. "0300_800C": "layerShift",
  567. # Filament runout (printer-side & per-AMS-slot)
  568. "0300_8004": "filamentRunout",
  569. "0700_8011": "filamentRunout",
  570. "0701_8011": "filamentRunout",
  571. "0702_8011": "filamentRunout",
  572. "0703_8011": "filamentRunout",
  573. "0704_8011": "filamentRunout",
  574. "0705_8011": "filamentRunout",
  575. "0706_8011": "filamentRunout",
  576. "0707_8011": "filamentRunout",
  577. "07FF_8011": "filamentRunout",
  578. # Clogged nozzle / extruder
  579. "0300_4006": "cloggedNozzle",
  580. "0300_8016": "cloggedNozzle",
  581. "0300_801C": "cloggedNozzle",
  582. "0700_8003": "cloggedNozzle",
  583. "0700_8007": "cloggedNozzle",
  584. "0700_8013": "cloggedNozzle",
  585. "0701_8003": "cloggedNozzle",
  586. "0701_8007": "cloggedNozzle",
  587. "0701_8013": "cloggedNozzle",
  588. "0702_8003": "cloggedNozzle",
  589. # AI print monitoring — spaghetti / the model coming off the plate.
  590. # `spaghettiDetached` is a key the archive editor already offers for this
  591. # failure mode, not a new one, so a derived reason opens the dropdown on
  592. # that option rather than blank — and survives the next save, which clears
  593. # any value the editor does not recognise.
  594. #
  595. # A module-0x0C row is safe here despite the warning above: that warning is
  596. # about matching on the module alone, and 0C00_8042 is a full short code
  597. # with a documented meaning ("The AI print monitor has detected a spaghetti
  598. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  599. # cannot collide.
  600. #
  601. # 0300_8003's own text ends "before continuing your print", but on an X2D
  602. # it arrives with the print already paused, offering only
  603. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  604. #
  605. # Two neighbours are left out on purpose, so this does not get re-derived:
  606. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  607. # reads as a warning about a print that is still running, not a halt.
  608. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  609. # the waste chute. That is not the print failing.
  610. #
  611. # That line is drawn from the text, not from `severity`, because severity
  612. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  613. # module/error word with no level in it, and bambu_mqtt.py gives every
  614. # print_error entry a flat severity=3. Matching on the short code alone is
  615. # the right shape for derive_failure_reason, not an omission.
  616. "0300_8003": "spaghettiDetached",
  617. "0C00_8042": "spaghettiDetached",
  618. }
  619. def _hms_short_code(attr: int, code: int | str) -> str:
  620. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  621. if isinstance(code, str):
  622. code_int = int(code.replace("0x", ""), 16) if code else 0
  623. else:
  624. code_int = int(code or 0)
  625. attr_int = int(attr or 0)
  626. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  627. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  628. """Derive the failure_reason key for an archived print.
  629. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  630. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  631. no HMS code matches (don't guess — null is honest). The keys are the
  632. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  633. translated at render time.
  634. """
  635. if status in ("aborted", "cancelled"):
  636. return "userCancelled"
  637. if status != "failed":
  638. return None
  639. for err in hms_errors or []:
  640. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  641. if short_code in _HMS_FAILURE_REASONS:
  642. return _HMS_FAILURE_REASONS[short_code]
  643. return None
  644. # Track created_by_id for expected prints so the user email can be sent even when
  645. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  646. # {(printer_id, filename): created_by_id}
  647. _expected_print_creators: dict[tuple[int, str], int] = {}
  648. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  649. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  650. # tag tuple changes for the slot. Cleared when the slot is reported empty
  651. # so remove + reinsert reliably re-prompts the UI.
  652. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  653. async def _broadcast_unknown_tag(
  654. *,
  655. printer_id: int,
  656. ams_id: int,
  657. tray_id: int,
  658. tag_uid: str,
  659. tray_uuid: str,
  660. tray_type: str | None = None,
  661. tray_color: str | None = None,
  662. tray_sub_brands: str | None = None,
  663. tray_count: int | None = None,
  664. ) -> None:
  665. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  666. _logger = logging.getLogger(__name__)
  667. slot_key = (ams_id, tray_id)
  668. tag_key = (tag_uid or "", tray_uuid or "")
  669. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  670. if per_printer.get(slot_key) == tag_key:
  671. _logger.debug(
  672. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  673. printer_id,
  674. ams_id,
  675. tray_id,
  676. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  677. )
  678. return
  679. _logger.info(
  680. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  681. printer_id,
  682. ams_id,
  683. tray_id,
  684. tray_type,
  685. tray_color,
  686. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  687. )
  688. # Broadcast first; only commit the dedup if the WS write succeeds.
  689. # If broadcast raises, the next MQTT push retries instead of being
  690. # permanently silenced by a poisoned dedup entry.
  691. await ws_manager.broadcast(
  692. {
  693. "type": "unknown_tag",
  694. "printer_id": printer_id,
  695. "ams_id": ams_id,
  696. "tray_id": tray_id,
  697. "tag_uid": tag_uid,
  698. "tray_uuid": tray_uuid,
  699. "tray_type": tray_type,
  700. "tray_color": tray_color,
  701. "tray_sub_brands": tray_sub_brands,
  702. "tray_count": tray_count,
  703. }
  704. )
  705. per_printer[slot_key] = tag_key
  706. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  707. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  708. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  709. if per_printer is None:
  710. return
  711. per_printer.pop((ams_id, tray_id), None)
  712. # TTL for expected-print entries: evict registrations older than this to prevent
  713. # unbounded growth when a print is registered but never starts (e.g. printer
  714. # disconnect, app restart, print started from the printer panel).
  715. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  716. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  717. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  718. # Cleanup loop interval
  719. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  720. _expected_prints_cleanup_task: asyncio.Task | None = None
  721. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  722. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  723. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  724. possible_keys: list[tuple[int, str]] = []
  725. filename = (state.gcode_file or state.current_print or "").strip()
  726. subtask_name = (state.subtask_name or "").strip()
  727. if subtask_name:
  728. possible_keys.append((printer_id, subtask_name))
  729. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  730. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  731. if filename:
  732. base_name = filename.rsplit("/", 1)[-1]
  733. if base_name.endswith(".gcode.3mf"):
  734. root_name = base_name[: -len(".gcode.3mf")]
  735. possible_keys.append((printer_id, root_name))
  736. possible_keys.append((printer_id, base_name))
  737. possible_keys.append((printer_id, f"{root_name}.gcode"))
  738. possible_keys.append((printer_id, f"{root_name}.3mf"))
  739. elif base_name.endswith(".3mf"):
  740. root_name = base_name[: -len(".3mf")]
  741. possible_keys.append((printer_id, root_name))
  742. possible_keys.append((printer_id, base_name))
  743. elif base_name.endswith(".gcode"):
  744. root_name = base_name[: -len(".gcode")]
  745. possible_keys.append((printer_id, root_name))
  746. possible_keys.append((printer_id, f"{root_name}.3mf"))
  747. possible_keys.append((printer_id, base_name))
  748. else:
  749. possible_keys.append((printer_id, base_name))
  750. possible_keys.append((printer_id, f"{base_name}.3mf"))
  751. return possible_keys
  752. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  753. """The id of who started the print, unless that user has been deleted since.
  754. Deleting a user forgets them in printer_manager, but a print that ended a
  755. moment before still holds them.
  756. """
  757. if not print_user or print_user.get("user_id") is None:
  758. return None
  759. from backend.app.models.user import User
  760. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  761. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  762. """Check the cheap, process-local print ownership signals."""
  763. if printer_manager.get_current_print_user(printer_id):
  764. return True
  765. return any(
  766. key in _expected_prints or _active_prints.get(key) in _owned_print_archive_ids
  767. for key in _build_status_print_keys(printer_id, state)
  768. )
  769. def _reported_print_names(printer_id: int, state: PrinterState) -> set[str]:
  770. """The names the printer reports for its print, as it echoes them (spaces become underscores)."""
  771. return {_normalise_subtask_name(name) for _pid, name in _build_status_print_keys(printer_id, state)} - {""}
  772. async def _printing_archive_without_job_id(
  773. db, printer_id: int, reported: set[str], *, dispatched_only: bool, live_only: bool = False
  774. ):
  775. """The newest printing archive on ``printer_id`` of a print that reported no job id, under a reported name.
  776. An archive with a real id of its own is a print that reported one: a "0"
  777. print is not it, even under the same name (one whose completion was missed
  778. would otherwise cover it). ``dispatched_only`` keeps to archives carrying
  779. Bambuddy's dispatch marker; ``live_only`` leaves out deleted ones.
  780. """
  781. from backend.app.models.archive import PrintArchive
  782. query = select(PrintArchive).where(
  783. PrintArchive.printer_id == printer_id,
  784. PrintArchive.status == "printing",
  785. or_(PrintArchive.subtask_id.is_(None), PrintArchive.subtask_id.in_(("", "0"))),
  786. )
  787. if dispatched_only:
  788. query = query.where(or_(PrintArchive.billing_run_id.is_not(None), PrintArchive.created_by_id.is_not(None)))
  789. if live_only:
  790. query = query.where(PrintArchive.deleted_at.is_(None))
  791. archives = await db.execute(query.order_by(PrintArchive.created_at.desc()))
  792. return next((a for a in archives.scalars() if _archive_name_forms(a) & reported), None)
  793. async def running_print_archive(db, printer_id: int, state: PrinterState, *, printing_only: bool, by_name: bool):
  794. """The archive of the print running on ``printer_id``, or None (#3327).
  795. By the print's subtask_id first, which the firmware mints per print; with
  796. ``printing_only`` only an archive that is still printing (a leftover row of
  797. a completion never seen must not stand in for another job). A print
  798. started outside the cloud (Bambu Studio over LAN, Handy, the printer's
  799. screen) reports subtask_id "0", which links it to nothing: the archive
  800. Bambuddy bound to the running print comes next, the one completion charges
  801. and photographs. A restart forgets that binding and rebinds only Bambuddy's
  802. own prints, so with ``by_name`` a "0" print last falls back to its printing
  803. archive under the name the printer reports. That can be an earlier run of
  804. the same name whose completion was missed while Bambuddy was down: good
  805. enough for a plate label or a cover, not for which objects skip-objects
  806. offers, so those callers leave it off. None until the archive exists, and
  807. never a deleted one.
  808. """
  809. from backend.app.models.archive import PrintArchive
  810. from backend.app.services.print_log import open_run_on_printer
  811. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  812. if subtask_id not in ("", "0"):
  813. # The run open on the printer for this job: the archive row is shared
  814. # by every plate of it, its printer and job id the latest start's.
  815. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  816. if run is not None and run.archive_id is not None:
  817. archive = await db.scalar(
  818. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  819. )
  820. if archive is not None:
  821. return archive
  822. query = select(PrintArchive).where(
  823. PrintArchive.printer_id == printer_id,
  824. PrintArchive.subtask_id == subtask_id,
  825. PrintArchive.deleted_at.is_(None),
  826. )
  827. if printing_only:
  828. query = query.where(PrintArchive.status == "printing")
  829. archive = await db.scalar(query.order_by(PrintArchive.created_at.desc()).limit(1))
  830. if archive is not None:
  831. return archive
  832. bound = next(
  833. (_active_prints[key] for key in _build_status_print_keys(printer_id, state) if key in _active_prints),
  834. None,
  835. )
  836. if bound is not None:
  837. return await db.scalar(select(PrintArchive).where(PrintArchive.id == bound, PrintArchive.deleted_at.is_(None)))
  838. if not by_name or subtask_id != "0":
  839. return None
  840. reported = _reported_print_names(printer_id, state)
  841. if not reported:
  842. return None
  843. return await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=False, live_only=True)
  844. def _bind_active_print(
  845. printer_id: int,
  846. archive_id: int,
  847. archive_filename: str | None,
  848. filename: str | None = None,
  849. subtask_name: str | None = None,
  850. ) -> None:
  851. """Track a running print under every name its completion may report.
  852. One set for every path that binds a print (new archive, expected print,
  853. restart resume, fallback): the archive's file name, the name the printer
  854. reported, and the subtask with and without ``.3mf``. Paths that registered
  855. fewer names lost the bound archive at completion, and with it the plate
  856. restore's height (#3240), whenever MQTT reported a name they had left out.
  857. """
  858. for name in {archive_filename, filename, f"{subtask_name}.3mf" if subtask_name else None, subtask_name}:
  859. if name:
  860. _active_prints[(printer_id, name)] = archive_id
  861. async def _archive_of_open_run(printer_id: int, subtask_id: str | None = None) -> int | None:
  862. """The archive of the run open on the printer, if it is still there.
  863. With ``subtask_id``, only a run of that job."""
  864. try:
  865. from backend.app.models.archive import PrintArchive
  866. from backend.app.services.print_log import open_run_on_printer
  867. async with async_session() as db:
  868. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  869. if run is None or run.archive_id is None:
  870. return None
  871. return await db.scalar(
  872. select(PrintArchive.id).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  873. )
  874. except Exception as e:
  875. logging.getLogger(__name__).warning("[RUN] Could not read the open run of printer %s: %s", printer_id, e)
  876. return None
  877. async def _announce_discarded_runs(discarded, printer_id: int) -> None:
  878. """Publish the runs ``discard_open_runs`` dropped (archive redesign):
  879. each announced by run/started, now gone without an end."""
  880. if not discarded:
  881. return
  882. try:
  883. from backend.app.models.printer import Printer
  884. async with async_session() as db:
  885. printer = (
  886. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  887. ).first()
  888. if printer is not None:
  889. for run in discarded:
  890. await mqtt_relay.on_run_discarded(run, printer.serial_number, printer.name)
  891. except Exception as e:
  892. logging.getLogger(__name__).debug("[RUN] Could not announce discarded runs on printer %s: %s", printer_id, e)
  893. async def _publish_run_completed(run_id: int | None, printer_id: int) -> None:
  894. """Publish the run a print's end just wrote on the MQTT relay (archive
  895. redesign); nothing without one. Never in the way of the completion."""
  896. if run_id is None:
  897. return
  898. try:
  899. from backend.app.models.archive import PrintArchive
  900. from backend.app.models.print_log import PrintLogEntry
  901. from backend.app.models.printer import Printer
  902. async with async_session() as db:
  903. run = await db.get(PrintLogEntry, run_id)
  904. printer = (
  905. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  906. ).first()
  907. archive = await db.get(PrintArchive, run.archive_id) if run is not None and run.archive_id else None
  908. if run is not None and printer is not None:
  909. await mqtt_relay.on_run_completed(run, archive, printer.serial_number, printer.name)
  910. except Exception as e:
  911. logging.getLogger(__name__).debug("[RUN] Could not publish the end of run %s: %s", run_id, e)
  912. async def _open_run_for(archive_id: int, printer_id: int, subtask_id: str | None = None) -> None:
  913. """Write the run of the print that just started on the archive (archive
  914. redesign). In a session of its own and never in the way of the print
  915. start: until its readers move over, the archive still carries the print.
  916. The archive's start must be committed before. ``subtask_id`` is the
  917. printer's job, which finds the run again at a resume."""
  918. try:
  919. from backend.app.models.archive import PrintArchive
  920. from backend.app.models.printer import Printer
  921. from backend.app.services.print_log import open_run, open_run_on_printer, run_snapshot
  922. async with async_session() as db:
  923. archive = await db.get(PrintArchive, archive_id)
  924. if archive is None:
  925. return
  926. printer = (
  927. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  928. ).first()
  929. printer_name = printer.name if printer is not None else None
  930. already = await open_run_on_printer(db, printer_id)
  931. before = run_snapshot(already) if already is not None else None
  932. run = await open_run(
  933. db,
  934. archive,
  935. printer_id=printer_id,
  936. printer_name=printer_name,
  937. plate_id=_print_plate_ids.get((printer_id, archive_id)),
  938. subtask_id=subtask_id,
  939. )
  940. await db.commit()
  941. # Once per print: a resume or a repeated start finds the run it opened.
  942. # A new one replaced the run still open there (open_run): that one's
  943. # print ended unseen.
  944. # Compared by start too: SQLite can give the new run the id of the one
  945. # it replaced.
  946. replaced = (
  947. run is not None and before is not None and (before.id != run.id or before.started_at != run.started_at)
  948. )
  949. if run is not None and printer is not None and (before is None or replaced):
  950. if replaced:
  951. await _announce_discarded_runs([before], printer_id)
  952. try:
  953. await mqtt_relay.on_run_started(run, archive, printer.serial_number, printer_name)
  954. except Exception:
  955. pass # Don't fail the print start if MQTT fails
  956. except Exception as e:
  957. logging.getLogger(__name__).warning("[RUN] Could not open the run of archive %s: %s", archive_id, e)
  958. async def _drop_replaced_plate_videos(
  959. db, archive_id: int, plate_id: int | None, stale_relpath: str | None, logger: logging.Logger
  960. ) -> None:
  961. """Delete the videos a reprint of a plate replaces: ``stale_relpath``, the
  962. one the archive showed (when print start judged it this plate's), and
  963. those of the archive's earlier runs of the same plate. A plate keeps one
  964. video, as when the archive held the only one; another plate's stays. The
  965. runs that held them lose them. Commits."""
  966. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, PrintLogEntry
  967. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  968. runs = select(PrintLogEntry).where(
  969. PrintLogEntry.archive_id == archive_id, PrintLogEntry.timelapse_path.is_not(None)
  970. )
  971. with_video = list(await db.scalars(runs.execution_options(**{INCLUDE_OPEN_RUNS: True})))
  972. paths = {stale_relpath} if stale_relpath else set()
  973. if plate_id is not None:
  974. paths |= {r.timelapse_path for r in with_video if r.plate_id == plate_id}
  975. # A video another plate's run holds is that plate's.
  976. paths -= {r.timelapse_path for r in with_video if r.plate_id is not None and r.plate_id != plate_id}
  977. if not paths:
  978. return
  979. for run in with_video:
  980. if run.timelapse_path in paths:
  981. run.timelapse_path = None
  982. await db.commit()
  983. for relpath in sorted(p for p in paths if p):
  984. try:
  985. stale_path = safe_join_under(app_settings.base_dir, relpath, http=False)
  986. if stale_path.is_file():
  987. stale_path.unlink()
  988. logger.info("Deleted stale timelapse %s on reprint of archive %s", relpath, archive_id)
  989. except (OSError, PathTraversalError) as e:
  990. logger.warning("Failed to delete stale timelapse %s on reprint: %s", relpath, e)
  991. def _mark_owned_if_dispatched(archive) -> None:
  992. """Remember a running print's archive as Bambuddy's when it carries a
  993. dispatch marker Bambuddy writes itself: ``billing_run_id`` (minted per
  994. dispatch in the scheduler) or ``created_by_id`` (from the queue item)."""
  995. if archive.billing_run_id is not None or archive.created_by_id is not None:
  996. _owned_print_archive_ids.add(archive.id)
  997. async def _is_printer_kill_switch_enabled_cached() -> bool:
  998. """Return the kill-switch setting without querying on every MQTT frame."""
  999. global _kill_switch_setting_cache
  1000. now = time.monotonic()
  1001. if _kill_switch_setting_cache is not None:
  1002. enabled, expires_at = _kill_switch_setting_cache
  1003. if now < expires_at:
  1004. return enabled
  1005. async with async_session() as db:
  1006. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  1007. enabled = await is_printer_kill_switch_enabled(db)
  1008. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  1009. return enabled
  1010. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  1011. """Resolve whether the current print was started by Bambuddy.
  1012. ``None`` means identity is not yet safe to decide. The kill switch must
  1013. defer in that case: stopping a print is irreversible, and the first status
  1014. frames after a restart may arrive before all subtask fields are populated.
  1015. """
  1016. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1017. return True
  1018. # The printer's built-in calibration runs (Bambuddy's Calibrate, the
  1019. # printer's screen) play gcode from its read-only system partition, where no
  1020. # user file can be. Only that path counts: a calibration *name* proves
  1021. # nothing, since Bambu Studio's pressure-advance print reports a user-style
  1022. # path, and any print can be given that name.
  1023. if str(getattr(state, "gcode_file", "") or "").startswith("/usr/"):
  1024. return True
  1025. # A1, A1 Mini, P1 and A2L report the same calibration as a bare file name,
  1026. # which nothing distinguishes from a user's file given that name, so it is
  1027. # not exempt: with the kill switch on, calibrate on those printers with the
  1028. # switch off.
  1029. possible_keys = _build_status_print_keys(printer_id, state)
  1030. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  1031. # is on disk. subtask_id is minted per print and pins the answer to the job
  1032. # actually running, rather than to an unrelated one that reuses a filename.
  1033. raw_subtask_id = getattr(state, "subtask_id", None)
  1034. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  1035. if subtask_id == "":
  1036. # Not reported yet: the first frames after a restart can lack it.
  1037. return None
  1038. from backend.app.models.archive import PrintArchive
  1039. if subtask_id == "0":
  1040. # A print started outside the cloud from Bambu Studio, Handy or the
  1041. # printer's screen reports "0", so there is no id to match: one of
  1042. # Bambuddy's printing archives on this printer under the name the
  1043. # printer reports, compared as the printer echoes names (spaces become
  1044. # underscores). Nothing reported to compare yet: wait.
  1045. reported = _reported_print_names(printer_id, state)
  1046. if not reported:
  1047. return None
  1048. archive = await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=True)
  1049. else:
  1050. from backend.app.services.print_log import open_run_on_printer
  1051. # This job's run open on the printer: the archive is shared by every
  1052. # plate of it, and its status, printer and job id are the latest
  1053. # start's, which may be another printer's.
  1054. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  1055. archive = await db.get(PrintArchive, run.archive_id) if run is not None and run.archive_id else None
  1056. if archive is None:
  1057. result = await db.execute(
  1058. select(PrintArchive)
  1059. .where(
  1060. PrintArchive.printer_id == printer_id,
  1061. PrintArchive.status == "printing",
  1062. PrintArchive.subtask_id == subtask_id,
  1063. )
  1064. .order_by(PrintArchive.created_at.desc())
  1065. .limit(1)
  1066. )
  1067. archive = result.scalar_one_or_none()
  1068. # An archive row on its own proves nothing: `on_print_start` archives every
  1069. # print it observes, including ones started from Bambu Studio or Handy, and
  1070. # stamps them with the same status and subtask_id. Authorizing on its mere
  1071. # existence would disable the kill switch the moment the 3MF finishes
  1072. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  1073. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  1074. # (carried over from the queue item that started it).
  1075. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  1076. # Rehydrate the fast in-memory path for subsequent status frames. Include
  1077. # both the archive filename and every normalized key reported by MQTT.
  1078. _owned_print_archive_ids.add(archive.id)
  1079. _active_prints[(printer_id, archive.filename)] = archive.id
  1080. for key in possible_keys:
  1081. _active_prints[key] = archive.id
  1082. return True
  1083. # No dispatch marker. Before calling this someone else's print, check whether
  1084. # Bambuddy has a job of its own running on this printer: a library-file
  1085. # dispatch has no archive at send time, and an archive created seconds later
  1086. # by `on_print_start` carries neither marker. The queue row, which the
  1087. # scheduler commits to status="printing" before the MQTT send, is the one
  1088. # durable record every Bambuddy print has. It cannot be tied to this
  1089. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  1090. # print is irreversible, and refusing to act costs nothing but a log line.
  1091. from backend.app.models.print_queue import PrintQueueItem
  1092. dispatched_here = await db.scalar(
  1093. select(PrintQueueItem.id)
  1094. .where(
  1095. PrintQueueItem.printer_id == printer_id,
  1096. PrintQueueItem.status == "printing",
  1097. )
  1098. .limit(1)
  1099. )
  1100. if dispatched_here is not None:
  1101. return None
  1102. return False
  1103. async def _send_kill_switch_provider_notification(
  1104. printer_id: int,
  1105. printer_name: str,
  1106. data: dict,
  1107. ) -> bool:
  1108. """Send the immediate print-stopped provider notification.
  1109. Returning a success flag lets the normal MQTT completion path retry when
  1110. this early notification could not be delivered.
  1111. """
  1112. logger = logging.getLogger(__name__)
  1113. try:
  1114. async with async_session() as db:
  1115. from backend.app.services.print_log import open_run_on_printer
  1116. # The print it stopped, for {archive_id} / {run_id}: the completion
  1117. # that would name them skips its notification after this one.
  1118. run = await open_run_on_printer(db, printer_id)
  1119. await notification_service.on_print_complete(
  1120. printer_id,
  1121. printer_name,
  1122. "stopped",
  1123. data,
  1124. db,
  1125. archive_data={"archive_id": run.archive_id, "run_id": run.id} if run is not None else None,
  1126. )
  1127. return True
  1128. except Exception as e:
  1129. logger.warning(
  1130. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  1131. printer_id,
  1132. e,
  1133. )
  1134. return False
  1135. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  1136. """Wait for an immediate kill-switch notification, if one was scheduled."""
  1137. if task is None:
  1138. return False
  1139. try:
  1140. return await task
  1141. except Exception as e:
  1142. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  1143. return False
  1144. async def _run_needs_energy_start(archive, printer_id: int, db) -> bool:
  1145. """At a resume: whether the print's run still lacks its energy start
  1146. reading. The archive's may be an earlier print's. Commits a reading
  1147. found on the archive for this run onto it."""
  1148. try:
  1149. from backend.app.services.print_log import run_needs_energy_start
  1150. needs = await run_needs_energy_start(db, archive, printer_id=printer_id)
  1151. await db.commit()
  1152. return needs
  1153. except Exception as e:
  1154. logging.getLogger(__name__).warning("[RUN] Energy start of archive %s's run not checked: %s", archive.id, e)
  1155. return archive.energy_start_kwh is None
  1156. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  1157. """Capture the smart plug lifetime counter on the archive at print start.
  1158. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  1159. tracking survives a backend restart mid-print. The print-end handler reads
  1160. this value back from the DB and computes the delta against the current
  1161. plug counter.
  1162. """
  1163. _logger = logging.getLogger(__name__)
  1164. try:
  1165. candidates = await energy_plug_candidates(db, printer_id)
  1166. if not candidates:
  1167. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  1168. return False
  1169. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  1170. if selected is None:
  1171. # Naming the plugs matters here: with several linked to one printer
  1172. # this is the difference between "the meter is offline" and "you
  1173. # linked only accessories" (#2859).
  1174. _logger.warning(
  1175. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  1176. printer_id,
  1177. archive.id,
  1178. ", ".join(plug.name for plug in candidates),
  1179. )
  1180. return False
  1181. plug, energy = selected
  1182. archive.energy_start_kwh = float(energy["total"])
  1183. # With the plug's snapshots, what lets the cost follow the price over
  1184. # the print rather than take the price at its end (#1251). A price that
  1185. # can't be had must not cost the print its energy reading.
  1186. archive.energy_start_at = utcnow_naive()
  1187. archive.energy_start_plug_id = plug.id
  1188. try:
  1189. from backend.app.services.energy_price import current_price
  1190. archive.energy_start_price = await current_price(db)
  1191. except Exception as e:
  1192. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  1193. archive.energy_start_price = None
  1194. try:
  1195. from backend.app.services.print_log import mirror_energy_start
  1196. await mirror_energy_start(db, archive, printer_id=printer_id)
  1197. except Exception as e:
  1198. _logger.warning("[RUN] Energy start not copied onto the run of archive %s: %s", archive.id, e)
  1199. await db.commit()
  1200. _logger.info(
  1201. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  1202. f" ({context})" if context else "",
  1203. archive.id,
  1204. plug.name,
  1205. energy["total"],
  1206. )
  1207. return True
  1208. except Exception as e:
  1209. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  1210. return False
  1211. def forget_print_creator(user_id: int) -> None:
  1212. """The print-start emails of a deleted user's jobs go to nobody, not to
  1213. whoever is given the id next (SQLite reuses it)."""
  1214. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  1215. del _expected_print_creators[key]
  1216. async def forget_printer(printer_id: int) -> None:
  1217. """Drop what is kept for a deleted printer's id, here and in the services.
  1218. SQLite used to give the id to the next printer created, which inherited it
  1219. all: the running print's owner (its prints passed the kill switch and were
  1220. billed to that user), the plate-clear gate, pending and suppressed
  1221. notifications, the camera feed, the plate references. Ids are no longer
  1222. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  1223. stay. Called after the delete is committed, and again by work that was in
  1224. flight and wrote state back.
  1225. Every printer-keyed map of this module is listed here or, with the reason,
  1226. in tests/unit/test_forget_printer.py.
  1227. """
  1228. from backend.app.api.routes import camera
  1229. from backend.app.services import (
  1230. bambu_ftp,
  1231. kprofile_drift,
  1232. layer_timelapse,
  1233. plate_detection,
  1234. print_dispatch_context,
  1235. usage_tracker,
  1236. )
  1237. from backend.app.services.notify_live_activities import notify_live_activities
  1238. from backend.app.services.obico_detection import obico_detection_service
  1239. from backend.app.services.printer_file_cache import printer_file_cache
  1240. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  1241. archive_ids = set()
  1242. for tracked in (_active_prints, _expected_prints):
  1243. for key in [key for key in tracked if key[0] == printer_id]:
  1244. archive_ids.add(tracked.pop(key))
  1245. for archive_id in archive_ids:
  1246. _owned_print_archive_ids.discard(archive_id)
  1247. for registered in (_print_ams_mappings, _print_cost_center_ids, _print_plate_ids):
  1248. for key in [key for key in registered if key[0] == printer_id]:
  1249. del registered[key]
  1250. for tracked in (_expected_print_creators, _expected_print_registered_at):
  1251. for key in [key for key in tracked if key[0] == printer_id]:
  1252. del tracked[key]
  1253. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  1254. _ams_index_only_logged.discard(key)
  1255. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  1256. del _ams_alarm_cooldown[key]
  1257. # Pending work that would act on the id: an offline notice, a 3MF retry.
  1258. # A kill-switch notice is about a stop that happened and is left to finish.
  1259. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  1260. task = tasks.pop(printer_id, None)
  1261. if task is not None:
  1262. task.cancel()
  1263. for keyed in (
  1264. _stage22_finish_frames,
  1265. _stage22_finish_in_flight,
  1266. _inprint_frame_bank,
  1267. _inprint_frame_bank_ts,
  1268. _printer_reconciled_since_connect,
  1269. _printer_kprofiles_primed_since_connect,
  1270. _last_progress_milestone,
  1271. _first_layer_notified,
  1272. _kill_switch_notification_tasks,
  1273. _notified_hms_errors,
  1274. _hms_print_state,
  1275. _hms_forget_when_gone,
  1276. _timelapse_baselines,
  1277. _bed_cool_waiters,
  1278. _printer_last_connected,
  1279. _unknown_tag_last_broadcast,
  1280. _last_status_broadcast,
  1281. _connection_watchdog_last_attempt,
  1282. ):
  1283. keyed.pop(printer_id, None)
  1284. for marked in (
  1285. _unauthorized_print_kill_sent,
  1286. _user_stopped_printers,
  1287. _kill_switch_stopped,
  1288. _printer_offline_published,
  1289. _nozzle_count_updated,
  1290. _runtime_seen_connected,
  1291. _timelapse_baselines_unread,
  1292. ):
  1293. marked.discard(printer_id)
  1294. printer_manager.forget_printer(printer_id)
  1295. printer_file_cache.forget_printer(printer_id)
  1296. print_dispatch_context.clear(printer_id)
  1297. kprofile_drift.forget_printer(printer_id, deleted=True)
  1298. layer_timelapse.cancel_session(printer_id)
  1299. usage_tracker.forget_printer(printer_id)
  1300. obico_detection_service.forget_printer(printer_id)
  1301. bambu_ftp.clear_3mf_cache(printer_id)
  1302. await camera.forget_printer(printer_id)
  1303. printers.clear_cover_cache(printer_id)
  1304. print_scheduler.forget_printer(printer_id)
  1305. notify_live_activities.forget_printer(printer_id)
  1306. plate_detection.remove_printer_references(printer_id)
  1307. def register_expected_print(
  1308. printer_id: int,
  1309. filename: str,
  1310. archive_id: int,
  1311. ams_mapping: list[int] | None = None,
  1312. created_by_id: int | None = None,
  1313. cost_center_id: int | None = None,
  1314. plate_id: int | None = None,
  1315. ):
  1316. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1317. # Store with multiple filename variations to catch different naming patterns
  1318. _expected_prints[(printer_id, filename)] = archive_id
  1319. # Also store without .3mf extension if present
  1320. if filename.endswith(".3mf"):
  1321. base = filename[:-4]
  1322. _expected_prints[(printer_id, base)] = archive_id
  1323. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1324. # Store AMS mapping for usage tracking at print completion, and plate_id for
  1325. # a single-plate dispatch from a multi-plate 3MF — without it, the direct-Print
  1326. # path attributes the whole file's filament total to the spool instead of just
  1327. # the printed plate (#1697). They describe this dispatch: one that has none
  1328. # drops what an earlier dispatch of the archive left (sent, never started),
  1329. # unless a plate of the archive is printing now and still needs them.
  1330. dispatch = (printer_id, archive_id)
  1331. archive_printing = _printing_here(printer_id, archive_id)
  1332. if ams_mapping is not None:
  1333. _print_ams_mappings[dispatch] = ams_mapping
  1334. elif not archive_printing:
  1335. _print_ams_mappings.pop(dispatch, None)
  1336. if cost_center_id is not None:
  1337. _print_cost_center_ids[dispatch] = cost_center_id
  1338. elif not archive_printing:
  1339. _print_cost_center_ids.pop(dispatch, None)
  1340. if plate_id is not None:
  1341. _print_plate_ids[dispatch] = plate_id
  1342. elif not archive_printing:
  1343. _print_plate_ids.pop(dispatch, None)
  1344. # Store created_by_id so the user start email can be sent even when the archive
  1345. # itself has no created_by_id (e.g. library-file-based queue prints)
  1346. if created_by_id is not None:
  1347. _expected_print_creators[(printer_id, filename)] = created_by_id
  1348. if filename.endswith(".3mf"):
  1349. base = filename[:-4]
  1350. _expected_print_creators[(printer_id, base)] = created_by_id
  1351. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1352. # Record registration time for TTL-based eviction
  1353. _registered_at = time.monotonic()
  1354. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1355. if filename.endswith(".3mf"):
  1356. base = filename[:-4]
  1357. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1358. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1359. logging.getLogger(__name__).info(
  1360. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1361. )
  1362. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1363. """Undo :func:`register_expected_print` when the print never went out.
  1364. Registration has to happen *before* the MQTT print command, because the
  1365. printer can report the print before the line after the send executes. So
  1366. every path that registers and then fails to send — a cancel winning the
  1367. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1368. between — leaves an expectation for a print that will never arrive.
  1369. The TTL sweep evicts those after two hours, which is far longer than it
  1370. takes a user to react to a failed dispatch by pressing print again: that
  1371. reprint would be folded into the *old* archive and take the stale
  1372. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1373. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1374. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1375. are keyed by printer and archive, not by file, so they may only be dropped
  1376. once no live key of the printer still points at that archive.
  1377. """
  1378. keys = [(printer_id, filename)]
  1379. if filename.endswith(".3mf"):
  1380. base = filename[:-4]
  1381. keys.append((printer_id, base))
  1382. keys.append((printer_id, f"{base}.gcode"))
  1383. removed = False
  1384. for key in keys:
  1385. if _expected_prints.pop(key, None) is not None:
  1386. removed = True
  1387. _expected_print_creators.pop(key, None)
  1388. _expected_print_registered_at.pop(key, None)
  1389. # Still needed by another expected print of the archive on the printer,
  1390. # or a plate of it printing there, as in the sweep.
  1391. if not _expected_or_printing_here(printer_id, archive_id):
  1392. _drop_dispatch(printer_id, archive_id)
  1393. if removed:
  1394. logging.getLogger(__name__).info(
  1395. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1396. printer_id,
  1397. filename,
  1398. archive_id,
  1399. )
  1400. def _compute_run_filament_grams(
  1401. status: str,
  1402. archive_filament_used_grams: float | None,
  1403. progress: float | int | None,
  1404. usage_results: list[dict] | None,
  1405. ) -> float | None:
  1406. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1407. Priority for every status:
  1408. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1409. weight delta — same source that drives "Total Consumed" on the
  1410. Inventory page, so Stats and Inventory totals stay aligned).
  1411. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1412. back to the canonical "this print used X" value).
  1413. 3. For partial statuses: ``estimate * progress%``.
  1414. 4. ``None`` if nothing is known.
  1415. """
  1416. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1417. if tracked_grams > 0:
  1418. return round(tracked_grams, 1)
  1419. if status == "completed":
  1420. return archive_filament_used_grams
  1421. if archive_filament_used_grams:
  1422. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1423. if scale > 0:
  1424. return round(archive_filament_used_grams * scale, 1)
  1425. return None
  1426. def _printing_here(printer_id: int, archive_id: int) -> bool:
  1427. """Whether a plate of the archive is printing on the printer."""
  1428. return any(key[0] == printer_id and bound == archive_id for key, bound in _active_prints.items())
  1429. def _expected_or_printing_here(printer_id: int, archive_id: int) -> bool:
  1430. """Whether a print of the archive is expected or printing on the printer."""
  1431. return _printing_here(printer_id, archive_id) or any(
  1432. key[0] == printer_id and expected == archive_id for key, expected in _expected_prints.items()
  1433. )
  1434. def _drop_dispatch(printer_id: int, archive_id: int) -> None:
  1435. """Forget what the dispatch of the archive to the printer registered."""
  1436. dispatch = (printer_id, archive_id)
  1437. _print_ams_mappings.pop(dispatch, None)
  1438. _print_cost_center_ids.pop(dispatch, None)
  1439. _print_plate_ids.pop(dispatch, None)
  1440. def _get_start_ams_mapping(data: dict, printer_id: int, archive_id: int | None) -> list[int] | None:
  1441. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1442. stored_ams_mapping = data.get("ams_mapping")
  1443. if not stored_ams_mapping and archive_id:
  1444. stored_ams_mapping = _print_ams_mappings.get((printer_id, archive_id))
  1445. return stored_ams_mapping
  1446. def _get_start_plate_id(printer_id: int, archive_id: int | None) -> int | None:
  1447. """Resolve plate_id for print start without consuming stored direct-Print state.
  1448. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1449. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1450. read it back at print-start without popping (the entry is popped on print
  1451. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1452. """
  1453. if archive_id is None:
  1454. return None
  1455. return _print_plate_ids.get((printer_id, archive_id))
  1456. def _run_print_time_seconds(archive, printer_id: int) -> int | None:
  1457. """The slicer's time for the plate this print prints, for its start
  1458. notification (#3375): ``archive.print_time_seconds`` adds every plate of
  1459. the file up (#1593). The plate is the dispatch's, else the archive's. The
  1460. whole file's time when its plates are not known; None for a plate not
  1461. known of several, and the notification takes the printer's remaining
  1462. time."""
  1463. from backend.app.services.print_cost_estimate import run_estimate
  1464. plate_id = _print_plate_ids.get((printer_id, archive.id), archive.plate_id)
  1465. estimate = run_estimate(archive, plate_id)
  1466. return estimate.seconds if estimate is not None else None
  1467. _plate_estimates_task: asyncio.Task | None = None
  1468. async def _fill_plate_estimates() -> None:
  1469. from backend.app.services.print_cost_estimate import fill_plate_estimates
  1470. try:
  1471. filled = await fill_plate_estimates(async_session)
  1472. except asyncio.CancelledError:
  1473. raise
  1474. except Exception as exc:
  1475. logging.getLogger(__name__).warning("[ARCHIVE] Reading plate estimates failed: %s", exc)
  1476. return
  1477. if filled:
  1478. logging.getLogger(__name__).info("[ARCHIVE] Read the plate estimates of %d archive(s)", filled)
  1479. def _partial_progress_scale(progress: int | float | None) -> float:
  1480. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1481. Used by every site that multiplies a "would-have-used" slicer estimate
  1482. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1483. so the three sites in ``_background_notifications`` (and the per-plate
  1484. override helper) can't drift apart on the coercion shape.
  1485. """
  1486. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1487. def _scope_notification_archive_data_to_plate(
  1488. archive_data: dict,
  1489. archive_file_path: str | None,
  1490. plate_id: int | None,
  1491. print_status: str,
  1492. progress: int | float | None,
  1493. base_dir: Path,
  1494. ) -> dict:
  1495. """Override summed-across-plates totals in ``archive_data`` with the values
  1496. for ``plate_id`` so the completion notification reports what was actually
  1497. printed, not the whole project (#1785).
  1498. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1499. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1500. the archive card's "whole project" headline, wrong for the completion
  1501. notification of a single-plate print. The queue UI already re-reads the
  1502. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1503. notification payload (filament grams, time estimate, per-slot breakdown).
  1504. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1505. no per-plate values — in every fail case the original ``archive_data`` is
  1506. returned unchanged so the notification still sends.
  1507. """
  1508. if plate_id is None or not archive_file_path:
  1509. return archive_data
  1510. from backend.app.utils.threemf_tools import (
  1511. extract_filament_usage_from_3mf,
  1512. extract_print_time_from_3mf,
  1513. )
  1514. archive_path = base_dir / archive_file_path
  1515. if not archive_path.exists():
  1516. return archive_data
  1517. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1518. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1519. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1520. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1521. if plate_time:
  1522. archive_data["print_time_seconds"] = plate_time
  1523. # Gate both the grams headline AND the per-slot breakdown on the same
  1524. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1525. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1526. # to the project-level grams the archive columns already provide rather
  1527. # than ship a project-level headline next to an all-zero per-plate
  1528. # breakdown.
  1529. if plate_grams > 0:
  1530. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1531. archive_data["filament_slots"] = [
  1532. {
  1533. "slot_id": s.get("slot_id"),
  1534. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1535. "type": s.get("type", ""),
  1536. "color": s.get("color", ""),
  1537. }
  1538. for s in plate_slots
  1539. ]
  1540. return archive_data
  1541. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1542. """Best-effort filament metadata from the MQTT print-start snapshot.
  1543. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1544. file during print, see #1533) so the fallback PrintArchive still has
  1545. enough filament info to support the inventory views and AMS-expansion
  1546. planning the operator opens it for. Returns a dict with optional
  1547. ``filament_type`` and ``filament_color`` keys in the same
  1548. comma-separated format the 3MF extractor produces, so the rest of the
  1549. codebase treats the fallback archive identically to a normal one.
  1550. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1551. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1552. entries). When supplied, only the slots actually consumed by this
  1553. print contribute. Without it the function falls back to every loaded
  1554. AMS slot — less accurate but still useful.
  1555. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1556. that the unit tests pass directly, AND the on_print_start callback
  1557. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1558. bambu_mqtt service hands to main.py at runtime. The original
  1559. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1560. handled the inner shape and silently returned ``{}`` for every real
  1561. print start, leaving fallback archives' filament fields NULL — the
  1562. exact regression the fix was meant to close. Reported with a log
  1563. proving the AMS state was right there at
  1564. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1565. """
  1566. result: dict[str, str] = {}
  1567. # Look at the on_print_start wrapper first, then the inner shape.
  1568. raw_data = (data or {}).get("raw_data")
  1569. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1570. if not isinstance(ams_root, dict):
  1571. ams_root = (data or {}).get("ams") or {}
  1572. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1573. if not isinstance(ams_units, list) or not ams_units:
  1574. return result
  1575. from backend.app.services.print_scheduler import _global_tray_id
  1576. # Map global tray id → (type, color), addressed as the print's ams_mapping
  1577. # is: unit * 4 + tray, or the bare unit id for an AMS-HT (from 128).
  1578. loaded: dict[int, tuple[str, str]] = {}
  1579. for unit in ams_units:
  1580. if not isinstance(unit, dict):
  1581. continue
  1582. try:
  1583. unit_id = int(unit.get("id", 0))
  1584. except (TypeError, ValueError):
  1585. continue
  1586. for tray in unit.get("tray") or []:
  1587. if not isinstance(tray, dict):
  1588. continue
  1589. try:
  1590. tray_id = int(tray.get("id", 0))
  1591. except (TypeError, ValueError):
  1592. continue
  1593. ttype = (tray.get("tray_type") or "").strip()
  1594. # RRGGBBAA from the printer, stored as the 3MF path stores it:
  1595. # "#RRGGBB" (the Archives page's swatches and colour filter).
  1596. hex_color = (tray.get("tray_color") or "").strip().upper()[:6]
  1597. tcolor = f"#{hex_color}" if re.fullmatch(r"[0-9A-F]{6}", hex_color) else ""
  1598. if not ttype:
  1599. continue # Empty / unloaded slot.
  1600. loaded[_global_tray_id(unit_id, tray_id)] = (ttype, tcolor)
  1601. if not loaded:
  1602. return result
  1603. if ams_mapping:
  1604. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1605. filaments = [loaded[g] for g in used_ids if g in loaded]
  1606. if not filaments:
  1607. return result # Mapping points entirely at slots we have no data for.
  1608. else:
  1609. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1610. types_joined = ",".join(f[0] for f in filaments)
  1611. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1612. # Column limits per backend/app/models/archive.py: filament_type=50,
  1613. # filament_color=200.
  1614. if types_joined:
  1615. result["filament_type"] = types_joined[:50]
  1616. if colors_joined:
  1617. result["filament_color"] = colors_joined[:200]
  1618. return result
  1619. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1620. """Start a layer-timelapse session for *archive_id* when the printer has
  1621. an external camera configured. Returns True if a session was started.
  1622. Three call sites in on_print_start (expected-archive promotion, fallback
  1623. archive creation, fresh-archive creation) used to inline this same
  1624. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1625. on the first pass). Centralising the conditional + call here makes the
  1626. contract testable in isolation and keeps the three sites locked in step.
  1627. """
  1628. if not (printer.external_camera_enabled and printer.external_camera_url):
  1629. return False
  1630. from backend.app.services.layer_timelapse import start_session
  1631. start_session(
  1632. printer_id,
  1633. archive_id,
  1634. printer.external_camera_url,
  1635. printer.external_camera_type or "mjpeg",
  1636. snapshot_url=printer.external_camera_snapshot_url,
  1637. rotation=getattr(printer, "camera_rotation", 0),
  1638. )
  1639. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1640. return True
  1641. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1642. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1643. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1644. — since #2926 — the description the parser already resolved, which is preferred
  1645. when present so the queue's failure reason reads the same as the status
  1646. response. The short code still produces the bracketed label, and still
  1647. resolves the sentence for a caller whose entries predate the field. An entry
  1648. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1649. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1650. label when no description is on file. Returns None for an empty list so
  1651. callers can leave error_message unset.
  1652. """
  1653. if not hms_errors:
  1654. return None
  1655. from backend.app.services.hms_errors import get_error_description
  1656. parts: list[str] = []
  1657. for err in hms_errors:
  1658. try:
  1659. # `_hms_short_code` rather than a local derivation: this one used to
  1660. # format the error without masking it to 16 bits, so an `hms[]` entry
  1661. # whose code carries an alert-level group produced a five-digit label
  1662. # like "0500_3000A" — not a code the user can look up, and never a
  1663. # catalogue key, so the sentence was lost with it.
  1664. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1665. except (TypeError, ValueError):
  1666. continue
  1667. description = err.get("description") or get_error_description(short_code)
  1668. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1669. # groups and is not a code anyone can look up; its full code in the
  1670. # printer screen's four groups is (#2728).
  1671. full_code = str(err.get("full_code") or "")
  1672. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1673. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1674. return "; ".join(parts) if parts else None
  1675. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1676. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1677. print completes successfully. Gated to status=='completed': failed, cancelled
  1678. and aborted prints do not count as usage. Caller is responsible for committing
  1679. the session. No-op when the queue item has no linked library file (e.g. reprints
  1680. from an archive). See #1008."""
  1681. if queue_status != "completed" or item.library_file_id is None:
  1682. return
  1683. from backend.app.models.library import LibraryFile
  1684. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1685. if lib_file is None:
  1686. return
  1687. lib_file.print_count = (lib_file.print_count or 0) + 1
  1688. lib_file.last_printed_at = datetime.now(timezone.utc)
  1689. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1690. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1691. When on_print_complete fires with status 'failed' for a printer in this set we
  1692. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1693. rather than a 'print failed' notification.
  1694. """
  1695. _user_stopped_printers.add(printer_id)
  1696. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1697. _last_status_broadcast: dict[int, str] = {}
  1698. # Track printers where we've updated nozzle_count
  1699. _nozzle_count_updated: set[int] = set()
  1700. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1701. """Wait the debounce window then fire `on_printer_offline` if the printer
  1702. is still offline.
  1703. Scheduled by `on_printer_status_change` on the connected → disconnected
  1704. edge (#1752). Cancelled by the same handler if the printer reconnects
  1705. before the window elapses, so a single MQTT blip + recovery doesn't
  1706. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1707. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1708. route through the same status-change callback, so this covers both.
  1709. """
  1710. logger = logging.getLogger(__name__)
  1711. try:
  1712. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1713. still_offline = not printer_manager.is_connected(printer_id)
  1714. logger.info(
  1715. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1716. printer_id,
  1717. still_offline,
  1718. )
  1719. if not still_offline:
  1720. return
  1721. async with async_session() as db:
  1722. from backend.app.models.printer import Printer
  1723. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1724. printer = result.scalar_one_or_none()
  1725. if not printer:
  1726. logger.warning(
  1727. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1728. printer_id,
  1729. )
  1730. return
  1731. # Recorded only when the relay can publish it, so the reconnect's
  1732. # online event always has an offline before it.
  1733. if mqtt_relay.enabled and mqtt_relay.connected:
  1734. _printer_offline_published.add(printer_id)
  1735. try:
  1736. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1737. except Exception as e:
  1738. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1739. logger.info(
  1740. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1741. printer_id,
  1742. printer.name,
  1743. )
  1744. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1745. except asyncio.CancelledError:
  1746. raise
  1747. except Exception as e:
  1748. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1749. finally:
  1750. _printer_offline_notify_tasks.pop(printer_id, None)
  1751. def _hms_notify_key(error) -> str:
  1752. """What identifies a fault for notification de-duplication.
  1753. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1754. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1755. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1756. and -0006 together) shared a key and only the first was ever notified. An
  1757. entry without a full code falls back to attr and code together.
  1758. """
  1759. full_code = getattr(error, "full_code", "") or ""
  1760. if full_code:
  1761. return full_code.upper()
  1762. return f"{error.attr:08X}:{error.code}"
  1763. def _hms_fault_counts(error) -> bool:
  1764. """Whether a fault counts as a problem: the same rule the frontend's
  1765. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1766. It counts when Bambu publishes text for it or it offers action buttons, and
  1767. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1768. no actions does not count: those are things like "the top cover is open" or
  1769. "the chamber is hot, fan speed increased", which a printer can hold through
  1770. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1771. it always has; those are prompts such as "unable to start drying" (#2728).
  1772. """
  1773. if error.severity < 1:
  1774. return False
  1775. has_actions = bool(getattr(error, "actions", None))
  1776. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1777. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1778. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1779. """The new faults that count (see ``_hms_fault_counts``).
  1780. These go to the MQTT relay; the caller also needs a description before it
  1781. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1782. used to read ``severity >= 2`` when severity held the part byte; on the real
  1783. level that would drop the task-stopping errors (#2728).
  1784. """
  1785. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1786. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1787. """The faults on this printer not notified yet, and record them as notified.
  1788. Tracking is updated before anything is sent, so concurrent status callbacks
  1789. cannot notify the same fault twice. A notified fault is forgotten once it
  1790. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1791. and on is notified once (#3226), while one that clears and comes back much
  1792. later is notified again.
  1793. When ``print_state`` changes (a print resumed, started or finished), every
  1794. fault recorded so far is forgotten the first time it is gone, without the
  1795. wait: a runout fixed before resuming must be notified if it happens again a
  1796. few minutes later, while the printer sits paused. Not only the faults gone
  1797. at the change itself, because the update that flips the state can still
  1798. carry the old fault (a ``print_error`` entry stays until a payload brings
  1799. ``hms``).
  1800. """
  1801. now = time.time()
  1802. current = {_hms_notify_key(e) for e in errors}
  1803. seen = _notified_hms_errors.setdefault(printer_id, {})
  1804. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1805. if print_state is not None:
  1806. print_state = print_state.upper()
  1807. if _hms_print_state.get(printer_id, print_state) != print_state:
  1808. forget_when_gone.update(seen)
  1809. _hms_print_state[printer_id] = print_state
  1810. for key, last_seen in list(seen.items()):
  1811. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1812. del seen[key]
  1813. forget_when_gone.discard(key)
  1814. new = current - seen.keys()
  1815. for key in current:
  1816. seen[key] = now
  1817. if not seen:
  1818. _notified_hms_errors.pop(printer_id, None)
  1819. if not forget_when_gone:
  1820. _hms_forget_when_gone.pop(printer_id, None)
  1821. return _hms_errors_to_notify(errors, new)
  1822. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1823. # "Printing", -1 and 255 are "no stage" (#3211).
  1824. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1825. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1826. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1827. Records it as notified. Called only for a printing state with progress above 0.
  1828. Progress before the first layer is not progress through the print (#3211).
  1829. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1830. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1831. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1832. 75% notification together with Print Started, and since 75 was then on
  1833. record, 25 and 50 could never fire. So nothing counts while the printer
  1834. reports a layer count but has not started layer 1.
  1835. Without a layer count -- a print whose first frame carried no
  1836. ``total_layer_num``, until the pushall that asks for it is answered
  1837. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1838. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1839. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1840. reports neither keeps the old behaviour rather than never notifying.
  1841. """
  1842. if (state.layer_num or 0) < 1:
  1843. if (state.total_layers or 0) > 0:
  1844. return None
  1845. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1846. return None
  1847. progress = state.progress or 0
  1848. current_milestone = 0
  1849. if progress >= 75:
  1850. current_milestone = 75
  1851. elif progress >= 50:
  1852. current_milestone = 50
  1853. elif progress >= 25:
  1854. current_milestone = 25
  1855. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1856. _last_progress_milestone[printer_id] = current_milestone
  1857. return current_milestone
  1858. return None
  1859. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1860. """Handle printer status changes - broadcast via WebSocket."""
  1861. try:
  1862. notify_live_activities.observe(printer_id, state)
  1863. except Exception:
  1864. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1865. try:
  1866. pause_eta.observe(printer_id, state)
  1867. except Exception:
  1868. logging.getLogger(__name__).exception("Pause heads-up check failed for printer %s", printer_id)
  1869. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1870. # transitions disconnected → connected — which covers both Bambuddy
  1871. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1872. # `reconcile_stale_active_prints` exactly once for this connection so
  1873. # any archive still in `status="printing"` that can't actually be
  1874. # running anymore (printer IDLE / different subtask / empty subtask)
  1875. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1876. # finished during a disconnect window + a smart-plug power cycle
  1877. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1878. # next boot. Reconciliation runs concurrently — it must not block the
  1879. # WebSocket dedup / broadcast logic below, and the connected edge is
  1880. # marked True BEFORE the await so concurrent status updates inside
  1881. # the same connection don't re-trigger reconciliation.
  1882. #
  1883. # Wait for a real push_status before reconciling (#1679): MQTT
  1884. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1885. # the connection, BEFORE `_request_push_all` round-trips. At that
  1886. # instant the `PrinterState` is still on construction defaults — most
  1887. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1888. # If reconcile spawns here, every in-flight archive falls through to
  1889. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1890. # creates a duplicate archive on the real PRINT COMPLETE and
  1891. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1892. # keeps the #1542 mechanism intact: once the first real push_status
  1893. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1894. # fires again with the flag still False — reconcile then runs against
  1895. # actual evidence.
  1896. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1897. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1898. _printer_reconciled_since_connect[printer_id] = True
  1899. spawn_background_task(
  1900. reconcile_stale_active_prints(printer_id),
  1901. name=f"reconcile-stale-prints-{printer_id}",
  1902. )
  1903. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1904. # Re-arm so the next reconnect triggers reconciliation again.
  1905. _printer_reconciled_since_connect[printer_id] = False
  1906. # Same edge, for the calibration table the AMS card reads its K values from.
  1907. #
  1908. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1909. # tables to ask for. A `state_known` gate alone is not enough: the first
  1910. # real push_status is what makes the state known, and the nozzle fields do
  1911. # not always arrive in it. Latching there would spend this connection's one
  1912. # attempt on a printer that could not yet say what was fitted.
  1913. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1914. if (
  1915. state.connected
  1916. and state_known
  1917. and nozzle_known
  1918. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1919. ):
  1920. _printer_kprofiles_primed_since_connect[printer_id] = True
  1921. spawn_background_task(
  1922. prime_kprofile_table(printer_id),
  1923. name=f"prime-kprofiles-{printer_id}",
  1924. )
  1925. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1926. _printer_kprofiles_primed_since_connect[printer_id] = False
  1927. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1928. # else in the AMS report changing -- a power cycle does it to every slot --
  1929. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1930. # while the printer is idle; needs_check is cheap and throttled per slot.
  1931. # Guarded: nothing here may stop the status broadcast below.
  1932. try:
  1933. if not state.connected:
  1934. kprofile_drift.forget_printer(printer_id)
  1935. elif kprofile_drift.needs_check(printer_id, state):
  1936. spawn_background_task(
  1937. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1938. name=f"reapply-kprofiles-{printer_id}",
  1939. )
  1940. except Exception:
  1941. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1942. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1943. # connected → disconnected. The "back online" channel is already covered
  1944. # by the print-failure notification (firmware reports gcode_state=FAILED
  1945. # on reconnect of an interrupted print), so there is no online
  1946. # notification. The MQTT relay gets both: offline after the debounce, and
  1947. # online on the reconnect that follows a published offline.
  1948. prev_connected = _printer_last_connected.get(printer_id)
  1949. _printer_last_connected[printer_id] = state.connected
  1950. if prev_connected is True and not state.connected:
  1951. existing = _printer_offline_notify_tasks.get(printer_id)
  1952. if existing is None or existing.done():
  1953. logging.getLogger(__name__).info(
  1954. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1955. printer_id,
  1956. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1957. )
  1958. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1959. _maybe_notify_printer_offline(printer_id),
  1960. name=f"printer-offline-notify-{printer_id}",
  1961. )
  1962. elif state.connected:
  1963. # Kept until the relay can actually send online: with its broker down
  1964. # now, the next status update after the reconnect sends it.
  1965. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1966. _printer_offline_published.discard(printer_id)
  1967. printer_info = printer_manager.get_printer(printer_id)
  1968. if printer_info:
  1969. try:
  1970. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1971. except Exception as e:
  1972. logging.getLogger(__name__).warning(
  1973. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1974. )
  1975. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1976. if pending is not None and not pending.done():
  1977. logging.getLogger(__name__).info(
  1978. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1979. printer_id,
  1980. )
  1981. pending.cancel()
  1982. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1983. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1984. temps = state.temperatures or {}
  1985. nozzle_temp = round(temps.get("nozzle", 0))
  1986. bed_temp = round(temps.get("bed", 0))
  1987. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1988. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1989. # Auto-detect dual-nozzle printers from MQTT temperature data
  1990. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1991. _nozzle_count_updated.add(printer_id)
  1992. # Update nozzle_count in database
  1993. async with async_session() as db:
  1994. from backend.app.models.printer import Printer
  1995. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1996. printer = result.scalar_one_or_none()
  1997. if printer and printer.nozzle_count != 2:
  1998. printer.nozzle_count = 2
  1999. await db.commit()
  2000. logging.getLogger(__name__).info(
  2001. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  2002. )
  2003. # Include target temps for heating phase detection
  2004. bed_target = round(temps.get("bed_target", 0))
  2005. nozzle_target = round(temps.get("nozzle_target", 0))
  2006. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  2007. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  2008. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  2009. #
  2010. # dry_countdown_stalled rides along because it is the one drying signal the
  2011. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  2012. # dry_time stopped moving, so on the frame that flips it every other member
  2013. # of this key is identical and the push would be deduplicated away. Mid-print
  2014. # a temperature would eventually break the tie, but a parked command on an
  2015. # idle machine changes nothing else at all — AMS temp and humidity are not in
  2016. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  2017. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  2018. ams_dry_key = (
  2019. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  2020. if state.raw_data
  2021. else ()
  2022. )
  2023. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  2024. #
  2025. # The filament identity fields are here because Configure Slot writes
  2026. # exactly those and nothing else. Re-configuring a slot from PLA to another
  2027. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  2028. # matched, this function returned before broadcasting, and the card kept
  2029. # showing the old filament until the 30s fallback poll or a page reload —
  2030. # even though the configure route asks the printer for a fresh pushall and
  2031. # that push does carry the new values. Reset always worked, because it
  2032. # clears tray_type.
  2033. #
  2034. # These fields only change when someone configures a slot or swaps a spool,
  2035. # so unlike temperature or progress they add no broadcast traffic mid-print.
  2036. ams_tray_key = (
  2037. tuple(
  2038. (
  2039. t.get("id"),
  2040. t.get("tray_type", ""),
  2041. t.get("state"),
  2042. t.get("tray_color", ""),
  2043. t.get("tray_info_idx", ""),
  2044. t.get("tray_sub_brands", ""),
  2045. t.get("cali_idx"),
  2046. )
  2047. for a in (state.raw_data.get("ams") or [])
  2048. for t in a.get("tray", [])
  2049. )
  2050. if state.raw_data
  2051. else ()
  2052. )
  2053. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  2054. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  2055. # in the AMS change-hash (tray fields only, and widening that would fire
  2056. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  2057. # screen changed no key at all and the card's inlet badges sat stale until a
  2058. # reload. Like the filament-backup flag, these only move when someone
  2059. # reconfigures the machine, so they add no mid-print broadcast traffic.
  2060. fts_key = (
  2061. state.fila_switch.installed if state.fila_switch else False,
  2062. tuple(sorted(state.ams_switch_inlet.items())),
  2063. # Which hotend holds which slot. Unlike the two above this does move
  2064. # mid-print, on every filament change — but only between discrete slots,
  2065. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  2066. # it live: it decides which hotend the Load dialog may offer and whether
  2067. # Unload has anything to act on.
  2068. tuple(
  2069. sorted(
  2070. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  2071. # Sort on the extruder id alone: the other members are nullable
  2072. # and comparing None with an int raises.
  2073. key=lambda entry: entry[0],
  2074. )
  2075. ),
  2076. )
  2077. status_key = (
  2078. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  2079. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  2080. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  2081. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  2082. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  2083. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  2084. )
  2085. # Fields that change only when the machine does (a nozzle swap, a firmware
  2086. # update, developer mode) or once per print (its AMS mapping): no traffic,
  2087. # but on an idle printer nothing else moves the key when they change.
  2088. machine_key = (
  2089. tuple((n.nozzle_type, n.nozzle_diameter) for n in (state.nozzles or [])),
  2090. state.firmware_version,
  2091. state.developer_mode,
  2092. tuple(state.print_ams_mapping) if isinstance(state.print_ams_mapping, list) else None,
  2093. # Cooling/heating, switched on the printer's screen too: on an idle
  2094. # printer nothing else moves the key (PSF-4).
  2095. state.airduct_mode,
  2096. )
  2097. status_key = f"{status_key}:{machine_key}"
  2098. is_active_print = state.state in _ACTIVE_PRINT_STATES
  2099. if not is_active_print:
  2100. _unauthorized_print_kill_sent.discard(printer_id)
  2101. elif printer_id in _unauthorized_print_kill_sent:
  2102. # stop_print() was already sent for this print; avoid all further
  2103. # ownership and settings work until the printer leaves an active state.
  2104. pass
  2105. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  2106. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  2107. _unauthorized_print_kill_sent.discard(printer_id)
  2108. else:
  2109. kill_switch_enabled = False
  2110. authorization: bool | None = None
  2111. status_logger = logging.getLogger(__name__)
  2112. try:
  2113. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  2114. if kill_switch_enabled:
  2115. async with async_session() as db:
  2116. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  2117. except Exception as e:
  2118. # Fail safe: a database/reconciliation error must never turn into an
  2119. # irreversible stop of a print whose ownership is still unknown.
  2120. authorization = None
  2121. status_logger.warning(
  2122. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  2123. )
  2124. if not kill_switch_enabled or authorization is True:
  2125. _unauthorized_print_kill_sent.discard(printer_id)
  2126. elif authorization is None:
  2127. _unauthorized_print_kill_sent.discard(printer_id)
  2128. status_logger.debug(
  2129. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  2130. printer_id,
  2131. )
  2132. else:
  2133. try:
  2134. stopped = printer_manager.stop_print(printer_id)
  2135. if stopped:
  2136. _unauthorized_print_kill_sent.add(printer_id)
  2137. _kill_switch_stopped.add(printer_id)
  2138. printer_info = printer_manager.get_printer(printer_id)
  2139. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  2140. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  2141. notification_data = {
  2142. "status": "stopped",
  2143. "filename": state.gcode_file or state.current_print or "",
  2144. "subtask_name": state.subtask_name or "",
  2145. "progress": state.progress,
  2146. "reason": "unauthorized_print",
  2147. }
  2148. status_logger.warning(
  2149. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  2150. printer_id,
  2151. state.state,
  2152. )
  2153. try:
  2154. await ws_manager.broadcast(
  2155. {
  2156. "type": "kill_switch_triggered",
  2157. "printer_id": printer_id,
  2158. "printer_name": printer_name,
  2159. "filename": filename,
  2160. "reason": "unauthorized_print",
  2161. }
  2162. )
  2163. except Exception as e:
  2164. status_logger.warning(
  2165. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  2166. )
  2167. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  2168. if previous_task is not None and not previous_task.done():
  2169. previous_task.cancel()
  2170. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  2171. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  2172. name=f"kill-switch-notification-{printer_id}",
  2173. )
  2174. else:
  2175. status_logger.warning(
  2176. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  2177. printer_id,
  2178. state.state,
  2179. )
  2180. except Exception as e:
  2181. status_logger.warning(
  2182. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  2183. )
  2184. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  2185. try:
  2186. printer_info = printer_manager.get_printer(printer_id)
  2187. if printer_info:
  2188. await mqtt_relay.on_printer_status(
  2189. printer_id,
  2190. state,
  2191. printer_info.name,
  2192. printer_info.serial_number,
  2193. printer_manager.is_awaiting_plate_clear(printer_id),
  2194. )
  2195. except Exception:
  2196. pass # Don't fail status callback if MQTT fails
  2197. if _last_status_broadcast.get(printer_id) == status_key:
  2198. return # No change, skip WebSocket broadcast
  2199. _last_status_broadcast[printer_id] = status_key
  2200. # Check for progress milestone notifications (25%, 50%, 75%)
  2201. progress = state.progress or 0
  2202. is_printing = state.state in ("RUNNING", "PRINTING")
  2203. if is_printing and progress > 0:
  2204. current_milestone = _progress_milestone_to_notify(printer_id, state)
  2205. if current_milestone is not None:
  2206. try:
  2207. from backend.app.models.printer import Printer
  2208. # Read the printer in a short session and release the connection
  2209. # BEFORE the ~15s camera snapshot below — holding it across the grab
  2210. # pinned a pooled connection per milestone, per printer (issue #2572).
  2211. async with async_session() as db:
  2212. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2213. printer = result.scalar_one_or_none()
  2214. printer_name = printer.name if printer else f"Printer {printer_id}"
  2215. filename = state.subtask_name or state.gcode_file or "Unknown"
  2216. # remaining_time is in minutes, convert to seconds for notification
  2217. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  2218. # Capture camera snapshot for notification image attachment (no DB held).
  2219. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  2220. # Notification send needs a session (provider/template lookups).
  2221. async with async_session() as db:
  2222. await notification_service.on_print_progress(
  2223. printer_id,
  2224. printer_name,
  2225. filename,
  2226. current_milestone,
  2227. db,
  2228. remaining_time_seconds,
  2229. image_data=image_data,
  2230. )
  2231. except Exception as e:
  2232. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  2233. elif progress < 5:
  2234. # Reset milestone tracking when print restarts or new print begins
  2235. _last_progress_milestone[printer_id] = 0
  2236. _first_layer_notified[printer_id] = False
  2237. # HMS error codes that should not trigger notifications even though they
  2238. # have known descriptions (e.g. user-initiated actions, not real errors).
  2239. _HMS_NOTIFICATION_SUPPRESS = {
  2240. "0500_400E", # Printing was cancelled (user action, not an error)
  2241. }
  2242. # Check for new HMS errors and send notifications
  2243. current_hms_errors = getattr(state, "hms_errors", []) or []
  2244. if current_hms_errors:
  2245. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  2246. if new_errors:
  2247. try:
  2248. from backend.app.models.printer import Printer
  2249. # Read the printer in a short session and release the connection
  2250. # BEFORE the ~15s camera snapshot below (issue #2572).
  2251. async with async_session() as db:
  2252. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2253. printer = result.scalar_one_or_none()
  2254. printer_name = printer.name if printer else f"Printer {printer_id}"
  2255. # Format error details for notification
  2256. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  2257. module_names = {
  2258. 0x03: "Print/Task",
  2259. 0x05: "Nozzle/Extruder",
  2260. 0x07: "AMS/Filament",
  2261. 0x0C: "Motion Controller",
  2262. 0x12: "Chamber",
  2263. }
  2264. # Capture camera snapshot once for all error notifications (no DB held).
  2265. error_image_data = await _capture_snapshot_for_notification(
  2266. printer_id, printer, logging.getLogger(__name__)
  2267. )
  2268. # Notification sends need a session (provider/template lookups).
  2269. async with async_session() as db:
  2270. sent_count = 0
  2271. for error in new_errors:
  2272. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  2273. # Build short code like "0700_8010"
  2274. # Mask to 16 bits to handle printers that send larger values
  2275. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  2276. error_code_masked = error_code_int & 0xFFFF
  2277. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  2278. # Only notify for errors Bambu publishes text for — printers
  2279. # send undocumented codes that aren't real errors, and Bambu
  2280. # lists some with empty text. Resolved at parse time (#2926);
  2281. # short_code is still needed for the suppression set below.
  2282. description = error.description
  2283. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  2284. continue
  2285. error_type = f"{module_name} Error"
  2286. error_detail = description
  2287. await notification_service.on_printer_error(
  2288. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  2289. )
  2290. sent_count += 1
  2291. if sent_count:
  2292. logging.getLogger(__name__).info(
  2293. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  2294. )
  2295. # Also publish to MQTT relay (no DB): every new fault that
  2296. # counts, with or without text, the same set the UI counts.
  2297. printer_info = printer_manager.get_printer(printer_id)
  2298. if printer_info:
  2299. errors_data = [
  2300. {
  2301. "code": e.code,
  2302. "attr": e.attr,
  2303. "module": e.module,
  2304. "severity": e.severity,
  2305. }
  2306. for e in new_errors
  2307. ]
  2308. await mqtt_relay.on_printer_error(
  2309. printer_id, printer_info.name, printer_info.serial_number, errors_data
  2310. )
  2311. except Exception as e:
  2312. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  2313. else:
  2314. # No HMS errors: nothing to send, but faults gone long enough (or gone
  2315. # across a print state change) are forgotten. Some codes, e.g. chamber
  2316. # temperature regulation during PETG prints, toggle every few seconds.
  2317. _take_new_hms_faults(printer_id, [], state.state)
  2318. await ws_manager.send_printer_status(
  2319. printer_id,
  2320. printer_state_to_dict(
  2321. state,
  2322. printer_id,
  2323. printer_manager.get_model(printer_id),
  2324. printer_manager.get_drying_targets(printer_id),
  2325. ),
  2326. )
  2327. def _is_bambu_uuid(tray_uuid: str) -> bool:
  2328. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  2329. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  2330. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  2331. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  2332. K-profiles are per-nozzle and the printer's calibration table is numbered
  2333. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  2334. switch's other inlet therefore silently invalidates every configured slot in
  2335. it: the index stays put and now resolves against the other nozzle's table.
  2336. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  2337. and 0.020 on the right kept the left profile after the move, and a manual
  2338. RFID re-read only re-asserted the same wrong one.
  2339. Configuring a slot is a deliberate preparation step, so this re-selects
  2340. rather than re-configures: only the calibration binding moves, and only for
  2341. slots whose spool already has a stored profile for the new nozzle. A slot
  2342. Bambuddy knows nothing about is left exactly as the operator left it.
  2343. """
  2344. logger = logging.getLogger(__name__)
  2345. target_extruder = extruder_for_inlet(inlet)
  2346. if target_extruder is None:
  2347. return
  2348. client = printer_manager.get_client(printer_id)
  2349. state = printer_manager.get_status(printer_id)
  2350. if not client or not state or not state.raw_data:
  2351. return
  2352. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  2353. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  2354. # the nozzle width, which changes both the K profile to select and the
  2355. # preset the slot should carry.
  2356. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  2357. ams_raw = state.raw_data.get("ams")
  2358. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2359. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  2360. if not unit:
  2361. return
  2362. try:
  2363. async with async_session() as db:
  2364. for tray in unit.get("tray", []):
  2365. tray_id = int(tray.get("id", -1))
  2366. if tray_id < 0 or not tray.get("tray_type"):
  2367. continue
  2368. current_idx = tray.get("cali_idx")
  2369. profile = await find_slot_kprofile_for_extruder(
  2370. db,
  2371. printer_id,
  2372. ams_id,
  2373. tray_id,
  2374. target_extruder,
  2375. nozzle_diameter,
  2376. printer_manager.get_model(printer_id),
  2377. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2378. )
  2379. if profile is None or profile.cali_idx is None:
  2380. continue
  2381. if current_idx == profile.cali_idx:
  2382. continue # Already on the right one.
  2383. logger.info(
  2384. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2385. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2386. printer_id,
  2387. ams_id,
  2388. tray_id,
  2389. inlet,
  2390. target_extruder,
  2391. profile.name,
  2392. current_idx,
  2393. profile.cali_idx,
  2394. profile.k_value,
  2395. )
  2396. client.extrusion_cali_sel(
  2397. ams_id=ams_id,
  2398. tray_id=tray_id,
  2399. cali_idx=profile.cali_idx,
  2400. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2401. nozzle_diameter=nozzle_diameter,
  2402. )
  2403. except Exception as e:
  2404. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2405. def _slot_feeds_print(printer_id: int, ams_id: int, tray_id: int) -> bool:
  2406. """Is this slot the one feeding the printer right now?
  2407. ``tray_now`` names one slot for the whole printer, so on a dual-nozzle
  2408. machine each extruder's own fed slot is asked as well. Only meaningful
  2409. while a print runs; the caller checks that.
  2410. """
  2411. status = printer_manager.get_status(printer_id)
  2412. if status is None:
  2413. return False
  2414. if ams_id == 255:
  2415. global_id = 254 + tray_id
  2416. elif ams_id >= 128:
  2417. global_id = ams_id
  2418. else:
  2419. global_id = ams_id * 4 + tray_id
  2420. if getattr(status, "tray_now", None) == global_id:
  2421. return True
  2422. slots = getattr(status, "extruder_slots", None) or {}
  2423. return any(slot.has_filament and slot.holds(ams_id, tray_id) for slot in slots.values())
  2424. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2425. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2426. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2427. from the delayed re-check -- which is why it takes the AMS data and print
  2428. state as arguments instead of reading them from the push (#3186).
  2429. """
  2430. logger = logging.getLogger(__name__)
  2431. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2432. # Auto-unlink spool assignments with stale fingerprints. Under the
  2433. # per-printer assignment lock since #3186: the held-removal re-check runs
  2434. # this outside any MQTT push, so it can now overlap one.
  2435. try:
  2436. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2437. from sqlalchemy.orm import selectinload
  2438. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2439. from backend.app.models.spool import Spool as _Spool
  2440. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2441. from backend.app.services.ams_slot_presence import spool_present
  2442. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2443. # Built-in assignments only. Since #2812 they survive a switch to
  2444. # Spoolman mode rather than being deleted by it, and this pass ends
  2445. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2446. # time as the AMS contents changed under the other mode, undoing the
  2447. # preservation more slowly but just as completely.
  2448. assignments = []
  2449. if not await spoolman_owns_assignments(db):
  2450. result = await db.execute(
  2451. select(SA)
  2452. .where(SA.printer_id == printer_id)
  2453. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2454. )
  2455. assignments = result.scalars().all()
  2456. # ``printing_now`` (top of this function) keeps a runout from
  2457. # unlinking the spool that fed the print — the next idle-time pass
  2458. # unlinks it if the user really did take it out.
  2459. stale = []
  2460. # Removals this pass is holding rather than unlinking (#3186).
  2461. held: set[tuple] = set()
  2462. for assignment in assignments:
  2463. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2464. if assignment.ams_id == 255:
  2465. ps = printer_manager.get_status(printer_id)
  2466. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2467. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2468. current_tray = None
  2469. for vt in vt_tray_raw:
  2470. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2471. current_tray = vt
  2472. break
  2473. if not current_tray:
  2474. # vt_tray data may not have arrived yet — keep assignment
  2475. continue
  2476. else:
  2477. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2478. if not current_tray:
  2479. if printing_now:
  2480. logger.info(
  2481. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2482. assignment.spool_id,
  2483. assignment.ams_id,
  2484. assignment.tray_id,
  2485. )
  2486. continue
  2487. # A whole AMS unit can drop out of one push and come back in
  2488. # the next; only a slot that stays gone is a removal (#3186).
  2489. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2490. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2491. held.add(hold_key)
  2492. logger.info(
  2493. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2494. "unlinking if it is still gone in %ds",
  2495. assignment.spool_id,
  2496. assignment.ams_id,
  2497. assignment.tray_id,
  2498. int(slot_unlink_grace.GRACE_SECONDS),
  2499. )
  2500. continue
  2501. logger.info(
  2502. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2503. assignment.spool_id,
  2504. assignment.ams_id,
  2505. assignment.tray_id,
  2506. )
  2507. stale.append(assignment) # Slot empty
  2508. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2509. # A Bambu Lab spool is in this slot — check if it's the same spool
  2510. # that's currently assigned. If yes, keep the assignment (avoids
  2511. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2512. # the printer's filament preset on every startup).
  2513. tray_uuid = current_tray.get("tray_uuid", "")
  2514. tag_uid = current_tray.get("tag_uid", "")
  2515. spool = assignment.spool
  2516. spool_matches = False
  2517. if spool:
  2518. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2519. spool.tag_uid
  2520. and tag_uid
  2521. and tag_uid != "0000000000000000"
  2522. and spool.tag_uid.upper() == tag_uid.upper()
  2523. ):
  2524. spool_matches = True
  2525. if spool_matches:
  2526. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2527. cur_color = current_tray.get("tray_color", "")
  2528. cur_type = current_tray.get("tray_type", "")
  2529. fp_color = assignment.fingerprint_color or ""
  2530. fp_type = assignment.fingerprint_type or ""
  2531. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2532. assignment.fingerprint_color = cur_color
  2533. assignment.fingerprint_type = cur_type
  2534. logger.debug(
  2535. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2536. assignment.spool_id,
  2537. assignment.ams_id,
  2538. assignment.tray_id,
  2539. )
  2540. continue
  2541. # Different BL spool or unrecognized — unlink so auto-assign can match
  2542. logger.info(
  2543. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2544. assignment.spool_id,
  2545. assignment.ams_id,
  2546. assignment.tray_id,
  2547. tray_uuid,
  2548. )
  2549. stale.append(assignment)
  2550. else:
  2551. cur_color = current_tray.get("tray_color", "")
  2552. cur_type = current_tray.get("tray_type", "")
  2553. cur_state = current_tray.get("state")
  2554. fp_color = assignment.fingerprint_color or ""
  2555. fp_type = assignment.fingerprint_type or ""
  2556. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2557. # the slot was empty when the user pre-assigned via SpoolBuddy
  2558. # (the firmware drops ams_filament_setting on empty slots, so
  2559. # MQTT was deferred). The moment any filament gets inserted
  2560. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2561. # reconfigured spool — fire the deferred configuration.
  2562. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2563. # extruder" code) OR, on firmwares that don't use the state
  2564. # enum meaningfully, a non-empty tray_type when state is
  2565. # NOT one of the firmware's explicit empty signals (9, 10).
  2566. # state-only was wrong for firmwares that never set 11 — A1
  2567. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2568. # always report state=3 — so the replay never fired for them
  2569. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2570. # explicit "empty" signals authoritative over any stale
  2571. # tray_type that might survive the relay's auto-clearing.
  2572. #
  2573. # tray_exist_bits comes first because that guard cannot tell
  2574. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2575. # writes state=9 when the bit is 0 and leaves it there when the
  2576. # bit returns. A non-RFID spool inserted into a pre-assigned
  2577. # slot brings no tray_type with it, so the stale 9 made this
  2578. # expression false forever and the deferred config never fired
  2579. # — the deadlock #1322 removed from the assign path, still in
  2580. # place here (#3084, #3100).
  2581. loaded = spool_present(current_tray) is True or (
  2582. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2583. )
  2584. # Not into the slot feeding a running print: the printer refuses
  2585. # the setting for it (``ams_filament_setting refused``), and a
  2586. # spool swapped in after a runout sat through one refused send
  2587. # per AMS change. Held, it fires on the first change once the
  2588. # print is over (#3434).
  2589. if (
  2590. not fp_type.strip()
  2591. and loaded
  2592. and assignment.spool
  2593. and printing_now
  2594. and _slot_feeds_print(printer_id, assignment.ams_id, assignment.tray_id)
  2595. ):
  2596. logger.debug(
  2597. "Pre-config held for spool %d AMS%d-T%d: the slot is feeding the print",
  2598. assignment.spool_id,
  2599. assignment.ams_id,
  2600. assignment.tray_id,
  2601. )
  2602. continue
  2603. if not fp_type.strip() and loaded and assignment.spool:
  2604. # The fingerprint ends this replay. Not recorded when nothing
  2605. # could be sent (no MQTT client while the printer reconnects),
  2606. # so the next AMS change tries again. An attempt that raised is
  2607. # recorded as before: it may have sent part of the commands and
  2608. # would raise again on every change, remain% steps included.
  2609. configured: bool | None = False
  2610. try:
  2611. from backend.app.api.routes.inventory import (
  2612. apply_spool_to_slot_via_mqtt,
  2613. )
  2614. configured = await apply_spool_to_slot_via_mqtt(
  2615. db=db,
  2616. current_user=None,
  2617. spool=assignment.spool,
  2618. printer_id=printer_id,
  2619. ams_id=assignment.ams_id,
  2620. tray_id=assignment.tray_id,
  2621. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2622. current_tray_type=cur_type,
  2623. current_tray_sub_brands=current_tray.get("tray_sub_brands", ""),
  2624. )
  2625. except Exception:
  2626. logger.exception(
  2627. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2628. assignment.spool_id,
  2629. printer_id,
  2630. assignment.ams_id,
  2631. assignment.tray_id,
  2632. )
  2633. configured = None
  2634. if configured is False:
  2635. logger.warning(
  2636. "Pre-config not sent for spool %d on printer %d AMS%d-T%d (no MQTT client); "
  2637. "retrying on the next AMS change",
  2638. assignment.spool_id,
  2639. printer_id,
  2640. assignment.ams_id,
  2641. assignment.tray_id,
  2642. )
  2643. else:
  2644. if configured:
  2645. logger.info(
  2646. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2647. assignment.spool_id,
  2648. printer_id,
  2649. assignment.ams_id,
  2650. assignment.tray_id,
  2651. )
  2652. assignment.fingerprint_color = cur_color
  2653. assignment.fingerprint_type = cur_type
  2654. continue
  2655. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2656. # Blank tray data mid-print is a runout, not a swap: the
  2657. # firmware clears colour and type when it unloads a spool
  2658. # it just emptied. Unlinking here would erase the record
  2659. # of which spool fed the print so far.
  2660. if printing_now and not cur_color.strip() and not cur_type.strip():
  2661. logger.info(
  2662. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2663. "(runout?)",
  2664. assignment.spool_id,
  2665. assignment.ams_id,
  2666. assignment.tray_id,
  2667. )
  2668. continue
  2669. # Same reasoning off the print, on firmware's own say-so:
  2670. # a blank tray report from a slot whose tray_exist_bits
  2671. # bit is set describes a spool the AMS cannot identify —
  2672. # a non-RFID one, or one whose slot was reset — not a
  2673. # spool that was taken out. Deleting the assignment there
  2674. # threw away the identity the user had supplied, which is
  2675. # the only place it existed (#3100). A slot the bit calls
  2676. # empty, or one that carries no bit at all, still unlinks.
  2677. #
  2678. # Unless the slot was reported empty first: a removal
  2679. # already held means a spool came out and another went
  2680. # in, so the blank report keeps the hold running below
  2681. # rather than cancelling it (#3186).
  2682. if (
  2683. spool_present(current_tray) is True
  2684. and not cur_color.strip()
  2685. and not cur_type.strip()
  2686. and not slot_unlink_grace.is_held(
  2687. printer_id,
  2688. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2689. )
  2690. ):
  2691. logger.info(
  2692. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2693. "tray reports no filament data yet",
  2694. assignment.spool_id,
  2695. assignment.ams_id,
  2696. assignment.tray_id,
  2697. )
  2698. continue
  2699. # A blank report the presence bit does not vouch for is
  2700. # still only one push. An idle X1C cleared a whole AMS
  2701. # unit's bits, colour and type for a moment and lost
  2702. # four saved assignments that way (#3186); unlink only
  2703. # if the slot is still blank after the grace period.
  2704. if not cur_color.strip() and not cur_type.strip():
  2705. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2706. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2707. held.add(hold_key)
  2708. logger.info(
  2709. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2710. "unlinking if it is still blank in %ds",
  2711. assignment.spool_id,
  2712. assignment.ams_id,
  2713. assignment.tray_id,
  2714. int(slot_unlink_grace.GRACE_SECONDS),
  2715. )
  2716. continue
  2717. # Fingerprint mismatch — but check if tray now matches the
  2718. # assigned spool (e.g. auto-configure changed the tray).
  2719. # Both sides are reduced to the type the slot can carry
  2720. # before comparing: the assign path writes that rather
  2721. # than the spool's raw material (#2902), so a spool whose
  2722. # material is a product line — "PLA+", "HTPLA" — reports
  2723. # back as "PLA" and would otherwise fail this check and
  2724. # be auto-unlinked from the slot it was just assigned to.
  2725. # Reducing the printer's side too keeps slots configured
  2726. # by an older Bambuddy, still reporting "PLA+", matching.
  2727. spool = assignment.spool
  2728. if spool:
  2729. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2730. # Two ways the assign path can have arrived at the
  2731. # slot's type, so both count as "we wrote this".
  2732. # The material column is one; the spool's preset is
  2733. # the other, and it outranks the material when the
  2734. # spool has one -- a spool whose material says PLA
  2735. # and whose preset is "Bambu PLA Aero" puts
  2736. # PLA-AERO in the slot (#2902). Read from the stored
  2737. # preset name rather than resolving the preset,
  2738. # because this runs on every AMS push and a cloud
  2739. # lookup here would be both slow and unavailable on
  2740. # the unauthenticated replay path.
  2741. spool_types = {printer_filament_type(spool.material).upper()}
  2742. if spool.slicer_filament_name:
  2743. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2744. # An imported local preset stores its type outright,
  2745. # which is what the assign path used -- and the name
  2746. # above may be unset. One keyed read, and only on a
  2747. # mismatch, which is rare.
  2748. #
  2749. # slicer_filament is free text up to fifty characters,
  2750. # so the digits have to be checked against the range
  2751. # of the integer primary key they are about to be
  2752. # compared with. Postgres raises on an out-of-range
  2753. # integer rather than simply not matching, and that
  2754. # would poison this session and abandon the rest of
  2755. # the cleanup pass.
  2756. lp_ref = (spool.slicer_filament or "").strip()
  2757. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2758. from backend.app.models.local_preset import LocalPreset as _LP
  2759. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2760. if lp_type:
  2761. spool_types.add(printer_filament_type(lp_type).upper())
  2762. if (
  2763. _colors_similar(cur_color, spool_color)
  2764. and printer_filament_type(cur_type).upper() in spool_types
  2765. ):
  2766. logger.info(
  2767. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2768. assignment.spool_id,
  2769. assignment.ams_id,
  2770. assignment.tray_id,
  2771. )
  2772. assignment.fingerprint_color = cur_color
  2773. assignment.fingerprint_type = cur_type
  2774. continue
  2775. logger.info(
  2776. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2777. assignment.spool_id,
  2778. assignment.ams_id,
  2779. assignment.tray_id,
  2780. cur_color,
  2781. cur_type,
  2782. fp_color,
  2783. fp_type,
  2784. spool.rgba if spool else "?",
  2785. spool.material if spool else "?",
  2786. )
  2787. stale.append(assignment) # Spool changed
  2788. slot_unlink_grace.settle(printer_id, "inventory", held)
  2789. # Snapshot slots before delete — ORM attribute access after the
  2790. # commit would refresh against a deleted row.
  2791. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2792. for a in stale:
  2793. await db.delete(a)
  2794. if stale:
  2795. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2796. # Commit any changes (stale deletions and/or fingerprint updates)
  2797. await db.commit()
  2798. # Tell open browsers the assignment is gone (#2575). Only the manual
  2799. # REST assign/unassign endpoints broadcast this event; without it the
  2800. # frontend's spool-assignments cache keeps rendering the unlinked
  2801. # spool on the slot until an unrelated refetch — which reads exactly
  2802. # like "the fix didn't work" (reporter verified: a browser refresh
  2803. # after the swap showed the correct state all along).
  2804. for ams_id, tray_id in unlinked_slots:
  2805. await ws_manager.broadcast(
  2806. {
  2807. "type": "spool_assignment_changed",
  2808. "printer_id": printer_id,
  2809. "ams_id": ams_id,
  2810. "tray_id": tray_id,
  2811. }
  2812. )
  2813. except Exception as e:
  2814. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2815. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2816. """Delete Spoolman slot rows whose held removal has run its grace period.
  2817. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2818. talks to Spoolman for every tray; this only needs the local rows, so it
  2819. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2820. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2821. not in a slot the presence bit calls occupied -- and nothing else.
  2822. """
  2823. logger = logging.getLogger(__name__)
  2824. try:
  2825. async with async_session() as db:
  2826. from backend.app.api.routes.settings import get_setting
  2827. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2828. from backend.app.services.ams_slot_presence import spool_present
  2829. enabled = await get_setting(db, "spoolman_enabled")
  2830. if not enabled or enabled.lower() != "true":
  2831. return
  2832. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2833. if sync_mode and sync_mode != "auto":
  2834. return
  2835. trays: dict[tuple[int, int], dict] = {}
  2836. for ams_unit in ams_data or []:
  2837. if not isinstance(ams_unit, dict):
  2838. continue
  2839. for tray in ams_unit.get("tray", []):
  2840. if isinstance(tray, dict):
  2841. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2842. rows = (
  2843. (
  2844. await db.execute(
  2845. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2846. )
  2847. )
  2848. .scalars()
  2849. .all()
  2850. )
  2851. held: set[tuple] = set()
  2852. expired: list[tuple[int, int]] = []
  2853. for row in rows:
  2854. tray = trays.get((row.ams_id, row.tray_id))
  2855. if tray is None or printing_now:
  2856. continue
  2857. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2858. continue
  2859. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2860. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2861. continue
  2862. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2863. expired.append((row.ams_id, row.tray_id))
  2864. else:
  2865. held.add(hold_key)
  2866. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2867. if not expired:
  2868. return
  2869. # A statement rather than ORM deletes, like the sync pass: the two
  2870. # can overlap, and a row the other already removed must not fail
  2871. # this commit.
  2872. for ams_id, tray_id in expired:
  2873. await db.execute(
  2874. delete(SpoolmanSlotAssignment).where(
  2875. SpoolmanSlotAssignment.printer_id == printer_id,
  2876. SpoolmanSlotAssignment.ams_id == ams_id,
  2877. SpoolmanSlotAssignment.tray_id == tray_id,
  2878. )
  2879. )
  2880. await db.commit()
  2881. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2882. for ams_id, tray_id in expired:
  2883. await ws_manager.broadcast(
  2884. {
  2885. "type": "spool_assignment_changed",
  2886. "printer_id": printer_id,
  2887. "ams_id": ams_id,
  2888. "tray_id": tray_id,
  2889. }
  2890. )
  2891. except Exception as e:
  2892. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2893. async def _recheck_held_unlinks(printer_id: int) -> None:
  2894. """Re-run just the slot cleanup against the printer's current AMS state.
  2895. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2896. passes otherwise run only when the AMS hash changes, and a slot that went
  2897. empty and stayed empty may never change it again.
  2898. """
  2899. status = printer_manager.get_status(printer_id)
  2900. # A disconnected printer's state is its last report, not a new one: acting
  2901. # on it would "confirm" a removal nobody has seen for the whole grace
  2902. # period. Leave the holds; the first push after reconnecting decides.
  2903. if status is None or not status.connected:
  2904. return
  2905. ams_raw = status.raw_data.get("ams")
  2906. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2907. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2908. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2909. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2910. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2911. async def on_ams_change(printer_id: int, ams_data: list):
  2912. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2913. logger = logging.getLogger(__name__)
  2914. # Snapshot BEFORE any await: if a print is active, or a finished one is
  2915. # still being charged, skip weight sync later. on_print_complete may pop
  2916. # _active_sessions during our awaits (#880).
  2917. from backend.app.services.usage_tracker import printer_is_charging
  2918. _print_active = printer_is_charging(printer_id)
  2919. # A slot that reports empty while a print is running is a filament runout,
  2920. # not a spool swap: the spool is still physically in the AMS, just
  2921. # consumed. Dropping either inventory backend's slot link there loses the
  2922. # only record of which spool fed the print, so the completion path can't
  2923. # charge the runout segment to anything. Both cleanup passes below consult
  2924. # this; computed once, up front, so neither depends on the other having run.
  2925. _unlink_state = printer_manager.get_status(printer_id)
  2926. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2927. # The session alone is not enough: a restart that finds a stale persisted
  2928. # session registers none for the print that is running.
  2929. _print_active = _print_active or printing_now
  2930. # MQTT relay - publish AMS change
  2931. try:
  2932. printer_info = printer_manager.get_printer(printer_id)
  2933. if printer_info:
  2934. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2935. except Exception:
  2936. pass # Don't fail AMS callback if MQTT fails
  2937. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2938. # This ensures frontend gets immediate updates when AMS slots are configured
  2939. try:
  2940. state = printer_manager.get_status(printer_id)
  2941. if state:
  2942. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2943. await ws_manager.send_printer_status(
  2944. printer_id,
  2945. printer_state_to_dict(
  2946. state,
  2947. printer_id,
  2948. printer_manager.get_model(printer_id),
  2949. printer_manager.get_drying_targets(printer_id),
  2950. ),
  2951. )
  2952. except Exception as e:
  2953. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2954. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2955. # Spools whose tag this pass assigned to a slot; their other slots are
  2956. # released below, once this printer's lock is let go (#3427).
  2957. rfid_assigned: list[tuple[int, tuple[int, int, int]]] = []
  2958. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2959. # Serialised per-printer via services/ams_assignment_lock: MQTT bursts can deliver
  2960. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2961. # "no existing assignment" for the same (printer, ams, tray) and race to
  2962. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2963. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2964. # bug stayed latent there. See services/ams_assignment_lock for details.
  2965. try:
  2966. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2967. from sqlalchemy.orm import selectinload
  2968. from backend.app.api.routes.settings import get_setting
  2969. from backend.app.models.spool import Spool
  2970. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2971. from backend.app.services.spool_tag_matcher import (
  2972. auto_assign_spool,
  2973. create_spool_from_tray,
  2974. find_matching_untagged_spool,
  2975. get_spool_by_tag,
  2976. is_bambu_tag,
  2977. is_valid_tag,
  2978. link_tag_to_inventory_spool,
  2979. tag_belongs_to_archived_spool,
  2980. )
  2981. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2982. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2983. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2984. if not _spoolman_on or _spoolman_on.lower() != "true":
  2985. for ams_unit in ams_data:
  2986. if not isinstance(ams_unit, dict):
  2987. continue
  2988. ams_id = int(ams_unit.get("id", 0))
  2989. for tray in ams_unit.get("tray", []):
  2990. if not isinstance(tray, dict):
  2991. continue
  2992. tray_id = int(tray.get("id", 0))
  2993. tag_uid = tray.get("tag_uid", "")
  2994. tray_uuid = tray.get("tray_uuid", "")
  2995. tray_info_idx = tray.get("tray_info_idx", "")
  2996. if not tray.get("tray_type"):
  2997. # Slot reported empty — drop any cached unknown-tag
  2998. # broadcast so reinserting the same spool re-prompts.
  2999. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  3000. continue # Empty slot
  3001. # Check if assignment already exists for this slot
  3002. existing = await db.execute(
  3003. select(SA)
  3004. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  3005. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  3006. )
  3007. existing_assignment = existing.scalar_one_or_none()
  3008. if existing_assignment:
  3009. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  3010. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  3011. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  3012. # Skip during active prints: the usage tracker handles deduction
  3013. # precisely via 3MF data on print completion. Without this guard the
  3014. # AMS remain% SET and the usage tracker ADD both fire from the same
  3015. # MQTT message, doubling the deduction (#880).
  3016. if _print_active:
  3017. continue
  3018. remain_raw = tray.get("remain")
  3019. if (
  3020. remain_raw is not None
  3021. and existing_assignment.spool
  3022. and not existing_assignment.spool.weight_locked
  3023. ):
  3024. try:
  3025. remain_val = int(remain_raw)
  3026. except (TypeError, ValueError):
  3027. remain_val = -1
  3028. if 1 <= remain_val <= 100:
  3029. lw = existing_assignment.spool.label_weight or 1000
  3030. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  3031. current_used = existing_assignment.spool.weight_used or 0
  3032. if new_used > current_used + 1:
  3033. # Rechecked in the statement: the spool was loaded
  3034. # before this, and a weight set by hand (or weighed)
  3035. # and locked since then must stay (WL-6).
  3036. result = cast(
  3037. CursorResult,
  3038. await db.execute(
  3039. update(Spool)
  3040. .where(
  3041. Spool.id == existing_assignment.spool_id,
  3042. Spool.weight_locked.is_not(True),
  3043. func.coalesce(Spool.weight_used, 0) < new_used - 1,
  3044. )
  3045. .values(weight_used=new_used)
  3046. ),
  3047. )
  3048. await db.commit()
  3049. if result.rowcount:
  3050. logger.info(
  3051. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  3052. existing_assignment.spool_id,
  3053. current_used,
  3054. new_used,
  3055. remain_val,
  3056. )
  3057. await ws_manager.broadcast({"type": "inventory_changed"})
  3058. # A K-profile the slot lost (the default K after a reset or
  3059. # power cycle) is put back by kprofile_drift on the next idle
  3060. # push; a different real profile was picked on purpose and
  3061. # stays (#3219, item 44).
  3062. continue
  3063. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  3064. # BL spool with RFID tag: auto-match → inventory match → auto-create
  3065. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  3066. # Only a spool already known by this tag is proven to be
  3067. # here; a material/colour match or a new spool is not
  3068. # grounds to take it out of other slots (#3427).
  3069. known_by_tag = spool is not None
  3070. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  3071. # An archived spool still in the AMS: the slot
  3072. # stays free rather than adopting its tag.
  3073. continue
  3074. if not spool:
  3075. # Try matching an untagged inventory spool (same material/color)
  3076. spool = await find_matching_untagged_spool(db, tray)
  3077. if spool:
  3078. await link_tag_to_inventory_spool(db, spool, tray)
  3079. elif _auto_add_unknown:
  3080. spool = await create_spool_from_tray(db, tray)
  3081. else:
  3082. # Auto-add disabled: surface the slot so the
  3083. # user can add it manually via the UI.
  3084. await _broadcast_unknown_tag(
  3085. printer_id=printer_id,
  3086. ams_id=ams_id,
  3087. tray_id=tray_id,
  3088. tag_uid=tag_uid,
  3089. tray_uuid=tray_uuid,
  3090. tray_type=tray.get("tray_type"),
  3091. tray_color=tray.get("tray_color"),
  3092. tray_sub_brands=tray.get("tray_sub_brands"),
  3093. tray_count=len(ams_unit.get("tray", [])),
  3094. )
  3095. continue
  3096. # Slot matched (existing tag, untagged inventory
  3097. # match, or freshly auto-created spool) — drop any
  3098. # stale dedup so a future tag swap re-prompts.
  3099. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  3100. await auto_assign_spool(
  3101. printer_id,
  3102. ams_id,
  3103. tray_id,
  3104. spool,
  3105. printer_manager,
  3106. db,
  3107. tray_info_idx=tray_info_idx,
  3108. )
  3109. await db.commit()
  3110. if known_by_tag:
  3111. rfid_assigned.append((spool.id, (printer_id, ams_id, tray_id)))
  3112. await ws_manager.broadcast(
  3113. {
  3114. "type": "spool_auto_assigned",
  3115. "printer_id": printer_id,
  3116. "ams_id": ams_id,
  3117. "tray_id": tray_id,
  3118. "spool_id": spool.id,
  3119. }
  3120. )
  3121. logger.info(
  3122. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  3123. spool.id,
  3124. printer_id,
  3125. ams_id,
  3126. tray_id,
  3127. )
  3128. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  3129. db, tag_uid, tray_uuid
  3130. ):
  3131. # Non-BL spool with some tag — let user choose (not
  3132. # an archived one's, whose slot stays free)
  3133. await _broadcast_unknown_tag(
  3134. printer_id=printer_id,
  3135. ams_id=ams_id,
  3136. tray_id=tray_id,
  3137. tag_uid=tag_uid,
  3138. tray_uuid=tray_uuid,
  3139. tray_type=tray.get("tray_type"),
  3140. tray_color=tray.get("tray_color"),
  3141. tray_sub_brands=tray.get("tray_sub_brands"),
  3142. tray_count=len(ams_unit.get("tray", [])),
  3143. )
  3144. # No-tag slots (generic non-RFID filament) are left alone:
  3145. # nothing to identify, prompting "+ Add" would just create
  3146. # ghost spools with empty tags on every confirm.
  3147. except Exception as e:
  3148. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  3149. if rfid_assigned:
  3150. from backend.app.services.spool_relocation import INTERNAL, release_other_slots
  3151. for spool_id, slot in rfid_assigned:
  3152. try:
  3153. await release_other_slots(INTERNAL, spool_id, slot)
  3154. except Exception as e:
  3155. logger.warning("Releasing spool %s from its other slots failed: %s", spool_id, e, exc_info=True)
  3156. try:
  3157. async with async_session() as db:
  3158. from backend.app.api.routes.settings import get_setting
  3159. from backend.app.models.printer import Printer
  3160. # Check if Spoolman is enabled
  3161. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  3162. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  3163. return
  3164. # Check sync mode
  3165. sync_mode = await get_setting(db, "spoolman_sync_mode")
  3166. if sync_mode and sync_mode != "auto":
  3167. return # Only sync on auto mode
  3168. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  3169. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  3170. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  3171. # always owned by per-print tracking, never by AMS auto-sync. The
  3172. # setting is still read by the settings UI for backwards compat but
  3173. # has no effect on the sync path here.
  3174. # Get Spoolman URL
  3175. spoolman_url = await get_setting(db, "spoolman_url")
  3176. if not spoolman_url:
  3177. return
  3178. # Get or create Spoolman client
  3179. client = await get_spoolman_client()
  3180. if not client:
  3181. try:
  3182. client = await init_spoolman_client(spoolman_url)
  3183. except ValueError as exc:
  3184. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  3185. return
  3186. # Check if Spoolman is reachable
  3187. if not await client.health_check():
  3188. logger.warning("Spoolman not reachable at %s", spoolman_url)
  3189. return
  3190. # Get printer name for location
  3191. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3192. printer = result.scalar_one_or_none()
  3193. printer_name = printer.name if printer else f"Printer {printer_id}"
  3194. # OPTIMIZATION: Fetch all spools once before processing trays
  3195. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  3196. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  3197. try:
  3198. cached_spools = await client.get_spools()
  3199. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  3200. except Exception as e:
  3201. logger.error(
  3202. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  3203. printer_id,
  3204. e,
  3205. )
  3206. return
  3207. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  3208. from sqlalchemy.orm import selectinload
  3209. from backend.app.models.spool_assignment import SpoolAssignment
  3210. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  3211. from backend.app.services.ams_slot_presence import spool_present
  3212. from backend.app.services.inventory_mode import spoolman_owns_assignments
  3213. # Built-in remaining weight, used by sync_ams_tray only when the
  3214. # firmware reports an unusable remain%/tray_weight for a slot.
  3215. #
  3216. # Left empty since #2812. This block runs in Spoolman mode only,
  3217. # and until then the built-in table was emptied on the switch, so
  3218. # there was never anything here to read and the fallback was inert.
  3219. # Preserving those rows makes it live again, and it is keyed by slot
  3220. # rather than by spool: after a mode switch the tray may well hold
  3221. # different filament, and ``create_spool`` writes ``remaining_weight``
  3222. # unconditionally, so a stale figure would be seeded into a brand new
  3223. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  3224. # intent survives for whoever revisits the cross-mode fallback.
  3225. inventory_weights: dict[tuple[int, int], float] = {}
  3226. if not await spoolman_owns_assignments(db):
  3227. try:
  3228. assign_result = await db.execute(
  3229. select(SpoolAssignment)
  3230. .options(selectinload(SpoolAssignment.spool))
  3231. .where(SpoolAssignment.printer_id == printer_id)
  3232. )
  3233. for assignment in assign_result.scalars().all():
  3234. spool = assignment.spool
  3235. if spool and spool.label_weight > 0:
  3236. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  3237. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  3238. except Exception as e:
  3239. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  3240. # Load existing Spoolman slot assignments for the no-RFID fallback path
  3241. spoolman_slot_map: dict[tuple[int, int], int] = {}
  3242. slot_map_read = False
  3243. try:
  3244. slot_result = await db.execute(
  3245. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  3246. )
  3247. for slot in slot_result.scalars().all():
  3248. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  3249. slot_map_read = True
  3250. except Exception as e:
  3251. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  3252. # Sync each AMS tray and collect slot changes for DB persistence
  3253. synced = 0
  3254. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  3255. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  3256. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  3257. for ams_unit in ams_data:
  3258. if not isinstance(ams_unit, dict):
  3259. continue
  3260. ams_id = int(ams_unit.get("id", 0))
  3261. trays = ams_unit.get("tray", [])
  3262. for tray_data in trays:
  3263. if not isinstance(tray_data, dict):
  3264. continue
  3265. tray_id_raw = int(tray_data.get("id", 0))
  3266. tray = client.parse_ams_tray(ams_id, tray_data)
  3267. if not tray:
  3268. # Empty tray slot — record for local assignment cleanup
  3269. # and drop any cached unknown-tag broadcast so a
  3270. # reinserted spool re-prompts.
  3271. #
  3272. # Not during a running print: a slot that empties there
  3273. # is a filament runout, and the spool is still in the
  3274. # AMS. `spoolman_slot_assignments` is how a tag-less
  3275. # spool assigned through the Bambuddy UI is resolved at
  3276. # completion (#1459), so deleting the row mid-print
  3277. # loses the runout segment's usage — the same failure
  3278. # the internal inventory's auto-unlink had.
  3279. #
  3280. # Nor when firmware's presence bit says the slot is
  3281. # occupied. parse_ams_tray calls a tray with no type or
  3282. # no colour empty, and a spool the AMS cannot read has
  3283. # neither until something configures it — so a tag-less
  3284. # spool assigned through the UI had its row deleted by
  3285. # the first idle push after it was inserted. Same
  3286. # deletion as the internal inventory's in #3100, same
  3287. # answer, so the two modes stay in step.
  3288. #
  3289. # And only once the slot has stayed empty for the grace
  3290. # period -- the internal inventory's #3186 answer, for
  3291. # the same one-push blank.
  3292. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  3293. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  3294. if not printing_now and (
  3295. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  3296. ):
  3297. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  3298. empty_slots.append((ams_id, tray_id_raw))
  3299. else:
  3300. spoolman_held.add(hold_key)
  3301. logger.info(
  3302. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  3303. "unlinking if it is still empty in %ds",
  3304. ams_id,
  3305. tray_id_raw,
  3306. linked_spool,
  3307. int(slot_unlink_grace.GRACE_SECONDS),
  3308. )
  3309. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  3310. continue
  3311. spool_tag = (
  3312. tray.tray_uuid
  3313. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  3314. else tray.tag_uid
  3315. )
  3316. # Provide the hint only when no RFID is available
  3317. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  3318. try:
  3319. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  3320. result = await client.sync_ams_tray(
  3321. tray,
  3322. printer_name,
  3323. db,
  3324. # Per-print tracking is the only weight writer (#1119).
  3325. # AMS auto-sync still maintains spool metadata / slot
  3326. # assignments but no longer touches remaining_weight.
  3327. disable_weight_sync=True,
  3328. cached_spools=cached_spools,
  3329. inventory_remaining=inv_remaining,
  3330. spoolman_spool_id_hint=hint,
  3331. auto_add_unknown_rfid=auto_add_unknown_rfid,
  3332. )
  3333. if result is None and spool_tag and not auto_add_unknown_rfid:
  3334. # Spoolman skipped auto-create per user setting — surface
  3335. # the slot so the UI can offer "+ Add to inventory".
  3336. await _broadcast_unknown_tag(
  3337. printer_id=printer_id,
  3338. ams_id=ams_id,
  3339. tray_id=tray.tray_id,
  3340. tag_uid=tray.tag_uid or "",
  3341. tray_uuid=tray.tray_uuid or "",
  3342. tray_type=tray.tray_type,
  3343. tray_color=tray.tray_color,
  3344. tray_sub_brands=tray.tray_sub_brands,
  3345. tray_count=len(trays),
  3346. )
  3347. elif result:
  3348. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  3349. if result:
  3350. synced += 1
  3351. if result.get("id"):
  3352. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  3353. # If a new spool was created, add it to the cache
  3354. # so subsequent trays can find it if they reference the same tag
  3355. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  3356. if not spool_exists:
  3357. cached_spools.append(result)
  3358. logger.debug(
  3359. "[Printer %s] Added newly created spool %s to cache",
  3360. printer_id,
  3361. result["id"],
  3362. )
  3363. # Reconcile slot_preset_mappings (the same row internal
  3364. # mode keeps in sync via inventory + spool_tag_matcher).
  3365. # Without this the slot card surfaces the previous spool's
  3366. # preset name — same bug shape, different inventory mode.
  3367. from backend.app.services.slot_preset_writer import (
  3368. upsert_slot_preset_for_spoolman_spool,
  3369. )
  3370. await upsert_slot_preset_for_spoolman_spool(
  3371. db=db,
  3372. spoolman_spool=result,
  3373. tray_info_idx=tray.tray_info_idx or "",
  3374. tray_sub_brands=tray.tray_sub_brands or "",
  3375. tray_type=tray.tray_type or "",
  3376. printer_id=printer_id,
  3377. ams_id=ams_id,
  3378. tray_id=tray.tray_id,
  3379. )
  3380. except Exception as e:
  3381. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3382. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3383. if synced > 0:
  3384. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3385. # Persist slot assignment changes to the local table: only slots
  3386. # whose spool this pass changed, and only while they still hold what
  3387. # it read before awaiting Spoolman, so a spool assigned by hand in
  3388. # between stays (SSA-3). The changed slots are announced: the slot
  3389. # card reads slot_preset_mappings (rewritten above) ahead of the live
  3390. # tray, so with no event it kept the previous spool's preset name.
  3391. if slot_changes or empty_slots:
  3392. from backend.app.services.spoolman_slot_sync import write_slot_results
  3393. try:
  3394. await write_slot_results(
  3395. db,
  3396. {(printer_id, a_id, t_id): spool_id for (a_id, t_id), spool_id in spoolman_slot_map.items()}
  3397. if slot_map_read
  3398. else None,
  3399. [(printer_id, a_id, t_id, spool_id) for a_id, t_id, spool_id in slot_changes],
  3400. [(printer_id, a_id, t_id) for a_id, t_id in empty_slots],
  3401. )
  3402. except Exception as e:
  3403. await db.rollback()
  3404. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3405. except Exception as e:
  3406. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3407. # Largest finish photo attached to a notification; a bigger one is still linked.
  3408. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3409. async def _finish_photo_for_notification(
  3410. db, archive, archive_id: int, filename: str
  3411. ) -> tuple[str | None, bytes | None]:
  3412. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3413. With authentication off the link is the archive's own photo route, as it
  3414. always was: it opens without a login and doesn't expire. With
  3415. authentication on that route needs a media token, which nothing tapping a
  3416. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3417. link only ever answered 401. The photo is then saved as a notification
  3418. photo as well (utils/notification_photos.py) and the link points there: an
  3419. unguessable name that opens this one photo and nothing else, for 3 days.
  3420. The link is relative when no External URL is set. Bytes over
  3421. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3422. ``(None, None)`` when the photo can't be found.
  3423. """
  3424. from backend.app.api.routes.settings import get_setting
  3425. from backend.app.core.auth import is_auth_enabled
  3426. from backend.app.utils.archive_paths import find_archive_photo
  3427. from backend.app.utils.notification_photos import save_notification_photo
  3428. log = logging.getLogger(__name__)
  3429. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3430. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3431. photo_bytes: bytes | None = None
  3432. try:
  3433. photo_path = find_archive_photo(archive, filename)
  3434. if photo_path is not None:
  3435. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3436. except Exception as e:
  3437. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3438. try:
  3439. auth_on = await is_auth_enabled(db)
  3440. except Exception:
  3441. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3442. if auth_on:
  3443. url = None
  3444. if photo_bytes:
  3445. try:
  3446. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3447. url = f"{base}/api/v1/notifications/photos/{name}"
  3448. except Exception as e:
  3449. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3450. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3451. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3452. return url, None
  3453. if photo_bytes:
  3454. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3455. return url, photo_bytes
  3456. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3457. """Capture a camera snapshot for notification image attachment.
  3458. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3459. Uses: external camera > buffered frame > fresh capture.
  3460. Turns the chamber light on for the picture when the printer asks for it
  3461. (#1655). ``light=False`` is for callers that capture all through a print,
  3462. where the light would flash with every frame.
  3463. """
  3464. if not printer:
  3465. return None
  3466. async with camera_light(printer if light else None):
  3467. return await _capture_snapshot_frame(printer_id, printer, logger)
  3468. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3469. """The capture behind ``_capture_snapshot_for_notification``."""
  3470. try:
  3471. from backend.app.api.routes.settings import get_setting
  3472. async with async_session() as db:
  3473. capture_enabled = await get_setting(db, "capture_finish_photo")
  3474. if capture_enabled is not None and capture_enabled.lower() != "true":
  3475. return None
  3476. # Try external camera first
  3477. if printer.external_camera_enabled and printer.external_camera_url:
  3478. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3479. from backend.app.api.routes.camera import live_frame_for_capture
  3480. from backend.app.services.external_camera import capture_frame
  3481. # An external camera allows one reader, so capturing while a viewer
  3482. # is attached fails (#2707). A None here falls through to the paths
  3483. # below exactly as a failed capture did.
  3484. defer, buffered = live_frame_for_capture(printer_id)
  3485. if defer:
  3486. frame_data = buffered
  3487. else:
  3488. frame_data = await capture_frame(
  3489. printer.external_camera_url,
  3490. printer.external_camera_type or "mjpeg",
  3491. snapshot_url=printer.external_camera_snapshot_url,
  3492. )
  3493. if frame_data and len(frame_data) <= 2_500_000:
  3494. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3495. return _apply_camera_rotation(frame_data, printer, logger)
  3496. # Try buffered frame from active stream
  3497. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3498. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3499. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3500. buffered_frame = get_buffered_frame(printer_id)
  3501. if (active_for_printer or active_chamber) and buffered_frame:
  3502. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3503. if len(buffered_frame) <= 2_500_000:
  3504. return _apply_camera_rotation(buffered_frame, printer, logger)
  3505. # Fresh capture from printer camera
  3506. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3507. from backend.app.services.camera import capture_camera_frame_bytes
  3508. frame_data = await capture_camera_frame_bytes(
  3509. printer.ip_address, printer.access_code, printer.model, timeout=15
  3510. )
  3511. if frame_data and len(frame_data) <= 2_500_000:
  3512. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3513. return _apply_camera_rotation(frame_data, printer, logger)
  3514. except Exception as e:
  3515. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3516. return None
  3517. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3518. """#1867: bank a recent in-print camera frame for the finish photo.
  3519. Called on every layer change and (#2547) on every print-progress advance.
  3520. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3521. path has a pre-End-G-code image for prints that end with a plate swap.
  3522. Both drivers are print telemetry that stops the instant printing ends: no
  3523. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3524. plate swap) executes. So the last banked frame is always the finished print,
  3525. never the swapped plate — that property is what the #1867 path relies on and
  3526. it must survive any change to the throttle below.
  3527. Layer changes alone were not enough: they stop when the *final* layer
  3528. begins, which on a three-minute last layer left the bank stale by the whole
  3529. length of that layer (#2547). Progress keeps ticking through it.
  3530. Best-effort: any failure just leaves the previous banked frame.
  3531. """
  3532. logger = logging.getLogger(__name__)
  3533. client = printer_manager.get_client(printer_id)
  3534. state = client.state if client else None
  3535. if not state or state.state != "RUNNING":
  3536. return
  3537. # Only during actual extrusion — firmware ticks layer_num during the
  3538. # pre-print calibration sequence, whose sub-stages are non-zero.
  3539. if state.mc_print_sub_stage not in (None, 0):
  3540. return
  3541. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3542. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3543. # now that progress advances also drive banking, that exemption would fire a
  3544. # camera grab on every percent tick of the last layer. Bambu printers accept
  3545. # one RTSP client at a time, so each grab contends with the live view.
  3546. now = time.monotonic()
  3547. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3548. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3549. return
  3550. total = state.total_layers or 0
  3551. try:
  3552. async with async_session() as db:
  3553. from backend.app.models.printer import Printer
  3554. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3555. printer = result.scalar_one_or_none()
  3556. if not printer:
  3557. return
  3558. # Reuses the notification snapshot path, which honours the
  3559. # `capture_finish_photo` setting (returns None when disabled) so we
  3560. # don't bank frames the user never asked for. Without the chamber light
  3561. # (#1655): this runs every 25 seconds for the whole print.
  3562. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3563. if frame:
  3564. _inprint_frame_bank[printer_id] = frame
  3565. _inprint_frame_bank_ts[printer_id] = now
  3566. logger.debug(
  3567. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3568. printer_id,
  3569. layer_num,
  3570. total,
  3571. len(frame),
  3572. )
  3573. except Exception as e:
  3574. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3575. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3576. """Apply camera rotation to snapshot image if configured."""
  3577. from backend.app.services.camera import apply_camera_rotation
  3578. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3579. async def _send_print_start_notification(
  3580. printer_id: int,
  3581. data: dict,
  3582. archive_data: dict | None = None,
  3583. logger=None,
  3584. ):
  3585. """Helper to send print start notification with optional archive data."""
  3586. if logger is None:
  3587. logger = logging.getLogger(__name__)
  3588. try:
  3589. async with async_session() as db:
  3590. from backend.app.models.printer import Printer
  3591. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3592. printer = result.scalar_one_or_none()
  3593. printer_name = printer.name if printer else f"Printer {printer_id}"
  3594. # Capture camera snapshot for notification image attachment
  3595. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3596. if image_data:
  3597. if archive_data is None:
  3598. archive_data = {}
  3599. archive_data["image_data"] = image_data
  3600. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3601. # Send user-specific email notification for print start
  3602. if archive_data and archive_data.get("created_by_id"):
  3603. await notification_service.send_user_print_email(
  3604. event_type="user_print_start",
  3605. created_by_id=archive_data["created_by_id"],
  3606. printer_name=printer_name,
  3607. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3608. db=db,
  3609. )
  3610. except Exception as e:
  3611. logger.warning("Notification on_print_start failed: %s", e)
  3612. async def _dispatch_user_print_email(
  3613. status: str,
  3614. created_by_id: int | None,
  3615. printer_name: str,
  3616. filename: str,
  3617. db,
  3618. image_data: bytes | None = None,
  3619. finish_photo_url: str | None = None,
  3620. ) -> None:
  3621. """Send a user-specific print-completion email based on print status.
  3622. Maps the normalised print status to the correct event type and delegates
  3623. to :meth:`NotificationService.send_user_print_email`. A single helper
  3624. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3625. "stopped"`` dispatch block at every call site.
  3626. Does nothing if *created_by_id* is ``None``.
  3627. """
  3628. if created_by_id is None:
  3629. return
  3630. if status == "completed":
  3631. event_type = "user_print_complete"
  3632. elif status == "failed":
  3633. event_type = "user_print_failed"
  3634. elif status in ("stopped", "aborted", "cancelled"):
  3635. event_type = "user_print_stopped"
  3636. else:
  3637. return
  3638. await notification_service.send_user_print_email(
  3639. event_type=event_type,
  3640. created_by_id=created_by_id,
  3641. printer_name=printer_name,
  3642. filename=filename,
  3643. db=db,
  3644. image_data=image_data,
  3645. finish_photo_url=finish_photo_url,
  3646. )
  3647. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3648. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3649. try:
  3650. from backend.app.services.archive import extract_printable_objects_from_archive
  3651. client = printer_manager.get_client(printer_id)
  3652. if not client:
  3653. return
  3654. # Extract with positions for UI overlay, scoped to the plate that
  3655. # is printing — resolve_plate_id is the same resolver /cover uses,
  3656. # so the object list can't disagree with the thumbnail it is drawn
  3657. # over (#2522).
  3658. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3659. app_settings.base_dir / archive.file_path,
  3660. plate_number=resolve_plate_id(client.state),
  3661. )
  3662. if printable_objects:
  3663. client.state.printable_objects = printable_objects
  3664. client.state.printable_objects_bbox_all = bbox_all
  3665. client.state.skipped_objects = []
  3666. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3667. except Exception as e:
  3668. logger.debug("Failed to extract printable objects from archive: %s", e)
  3669. def _load_pauses_from_3mf(threemf_path, printer_id: int, *, warned_layers=(), passed_through_layer: int = 0) -> None:
  3670. """Read the running print's slicer pauses from its 3MF, in the background (#2984).
  3671. In a thread: a plate's G-code runs to tens of MB, and the print-start
  3672. handler must not wait for it. Kept only while the printer is still on
  3673. the print they were read for: a new print replaces the list.
  3674. ``warned_layers``: pauses this print was already warned about, kept on its
  3675. archive, so a restart does not send the heads-up again.
  3676. ``passed_through_layer``: for a print resumed after a restart, the layer it
  3677. is on. Its pauses up to there are behind it, though the printer's layer
  3678. reads 0 until it reports the next one.
  3679. """
  3680. client = printer_manager.get_client(printer_id)
  3681. if not client:
  3682. return
  3683. state = client.state
  3684. read_for = state.pause_points
  3685. try:
  3686. plate_id = resolve_plate_id(state)
  3687. except Exception:
  3688. # Never at the cost of the print-start handler this runs inside.
  3689. logging.getLogger(__name__).warning("[Printer %s] Could not tell the plate to read pauses for", printer_id)
  3690. return
  3691. async def _load() -> None:
  3692. from backend.app.utils.threemf_tools import extract_pause_points_from_3mf
  3693. points = await asyncio.to_thread(extract_pause_points_from_3mf, Path(threemf_path), plate_id)
  3694. if state.pause_points is not read_for:
  3695. return
  3696. state.pause_points = [p for p in points if p.layer > passed_through_layer]
  3697. state.pause_warned_layers = set(state.pause_warned_layers) | set(warned_layers)
  3698. if points:
  3699. logging.getLogger(__name__).info(
  3700. "Loaded %s slicer pause(s) for printer %s at layer(s) %s",
  3701. len(points),
  3702. printer_id,
  3703. [p.layer for p in points],
  3704. )
  3705. spawn_background_task(_load(), name=f"load-pauses-{printer_id}")
  3706. def _load_pauses_from_resumed_archive(archive, printer_id: int) -> None:
  3707. """Pauses for a print start taken as the resumption of a running print.
  3708. A restart while the print was paused makes its resume look like a new
  3709. print (#2984): the pauses warned about and passed are kept from before.
  3710. """
  3711. client = printer_manager.get_client(printer_id)
  3712. state = client.state if client else None
  3713. _load_pauses_from_3mf(
  3714. app_settings.base_dir / archive.file_path,
  3715. printer_id,
  3716. warned_layers=pause_eta.warned_layers_of(archive, state) if state is not None else (),
  3717. passed_through_layer=getattr(client, "layer_before_new_print", 0) if client else 0,
  3718. )
  3719. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3720. """Put the skip-objects list back after a restart mid-print.
  3721. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3722. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3723. which the #1304 guard suppresses on the first RUNNING push after startup.
  3724. Everything else this hook restores (the archive, the usage-tracking session,
  3725. the timelapse baseline) was already handled; the object list was not, so a
  3726. restart mid-print took skip-objects away for the rest of that print.
  3727. Nothing recovered it either: the printer card gates its Skip button on the
  3728. object count, and the one endpoint that can rebuild the list is reachable
  3729. only from the modal that button opens.
  3730. The archive is the running print's as ``running_print_archive`` finds it:
  3731. by subtask_id, or for a print that reports none by the archive bound to it
  3732. (#3327), never by name: a leftover ``status="printing"`` row from a
  3733. completion we never saw must not hand this print someone else's objects.
  3734. After a restart that binding exists only for Bambuddy's own prints, so a
  3735. print that reports no subtask_id loads nothing rather than a guess; the
  3736. reload path on ``GET /print/objects`` covers that case on demand.
  3737. """
  3738. client = printer_manager.get_client(printer_id)
  3739. if client is None or (client.state.printable_objects and client.state.pause_points):
  3740. return
  3741. archive = await running_print_archive(db, printer_id, state, printing_only=True, by_name=False)
  3742. if archive is not None and archive.file_path:
  3743. if not client.state.printable_objects:
  3744. _load_objects_from_archive(archive, printer_id, logger)
  3745. # The slicer's pauses are in-memory only as well (#2984).
  3746. if not client.state.pause_points:
  3747. _load_pauses_from_3mf(
  3748. app_settings.base_dir / archive.file_path,
  3749. printer_id,
  3750. warned_layers=pause_eta.warned_layers_of(archive, state),
  3751. )
  3752. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3753. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3754. # past it; the second covers a handshake that failed again on the way back and
  3755. # armed a fresh one. Module-level so tests can shrink them.
  3756. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3757. # Retry ladder for the other temporary give-up: the file service answered and
  3758. # the transfer still did not finish, which at print start is usually the printer
  3759. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3760. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3761. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3762. # two cover a printer that stays busy well into the print.
  3763. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3764. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3765. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3766. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3767. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3768. # by view, so two views race), the cool-off retry task, and print completion.
  3769. # Without this they each read file_path == "" and each run a full copy, so the row
  3770. # ends up pointing at one timestamped directory while the others sit orphaned.
  3771. #
  3772. # Keyed by printer rather than archive because a printer runs one print at a time,
  3773. # which makes the two equally strong here — and it bounds the dict by printer
  3774. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3775. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3776. # resuming, so "no waiters" is not a question this API can answer.
  3777. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3778. # How many of a printer's newest archives a touchscreen reprint is compared
  3779. # against (#3307). A repeat is usually of a recent job; the bound keeps a
  3780. # print start from reading a long history's extra_data.
  3781. _REPEAT_LOOKBACK = 200
  3782. async def _archived_3mf_for_repeat(
  3783. db, printer_id: int, subtask_name: str | None, gcode_file: str | None, total_layers: int | None
  3784. ):
  3785. """The newest archive of the job this printer is running again, with its 3MF.
  3786. A "Print again" on the printer's screen never names the file on the card:
  3787. it reports its own history copy under a generic name
  3788. (``file:///userdata/project_file.gcode.3mf``), the 3MF's internal title as
  3789. ``subtask_name`` and the plate as ``gcode_file`` -- and the title is often
  3790. not the card file's name, so every lookup built from it misses (#3307).
  3791. An earlier run that was archived recorded that same title and plate in its
  3792. ``_print_data``, and holds the 3MF.
  3793. Same printer, same title, same plate, a 3MF still on disk. A layer count
  3794. known on both sides must agree: the same title and plate re-sliced is
  3795. another job. None when nothing matches.
  3796. """
  3797. from backend.app.models.archive import PrintArchive
  3798. if not subtask_name or not gcode_file:
  3799. return None
  3800. rows = (
  3801. (
  3802. await db.execute(
  3803. select(PrintArchive)
  3804. .where(
  3805. PrintArchive.printer_id == printer_id,
  3806. PrintArchive.deleted_at.is_(None),
  3807. PrintArchive.file_path.isnot(None),
  3808. PrintArchive.file_path != "",
  3809. )
  3810. .order_by(PrintArchive.created_at.desc(), PrintArchive.id.desc())
  3811. .limit(_REPEAT_LOOKBACK)
  3812. )
  3813. )
  3814. .scalars()
  3815. .all()
  3816. )
  3817. for archive in rows:
  3818. extra = archive.extra_data if isinstance(archive.extra_data, dict) else {}
  3819. run = extra.get("_print_data")
  3820. if not isinstance(run, dict):
  3821. continue
  3822. if run.get("subtask_name") != subtask_name or run.get("filename") != gcode_file:
  3823. continue
  3824. if total_layers and archive.total_layers and archive.total_layers != total_layers:
  3825. continue
  3826. if not (app_settings.base_dir / archive.file_path).is_file():
  3827. continue
  3828. return archive
  3829. return None
  3830. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True) -> bool:
  3831. """Fill in a no-3MF archive from a 3MF that turned up later.
  3832. Returns True when the row was upgraded. Safe to call speculatively: it
  3833. verifies the archive still exists, is still a fallback, and that the file
  3834. is a readable 3MF before touching anything.
  3835. Serialised per printer — see ``_fallback_recovery_locks``.
  3836. """
  3837. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3838. async with lock:
  3839. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id, price=price)
  3840. async def _recover_fallback_archive_locked(
  3841. archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True
  3842. ) -> bool:
  3843. """The body of :func:`_recover_fallback_archive`, under its per-printer lock.
  3844. ``price`` is False when the print's end is being handled: the archive
  3845. still reads "printing" then, and its end prices it.
  3846. """
  3847. import zipfile
  3848. from backend.app.models.archive import PrintArchive
  3849. from backend.app.services.archive import ArchiveService
  3850. logger = logging.getLogger(__name__)
  3851. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3852. return False
  3853. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3854. # A truncated or half-written download is worse than no download: it
  3855. # would replace an honest empty archive with wrong metadata.
  3856. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3857. return False
  3858. async with async_session() as db:
  3859. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3860. if archive is None or archive.deleted_at is not None:
  3861. return False
  3862. if archive.file_path:
  3863. # Already recovered, or never was a fallback. Either way there is a
  3864. # real 3MF attached and overwriting it is not this function's job.
  3865. return False
  3866. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3867. service = ArchiveService(db)
  3868. recovered = await service.archive_print(
  3869. printer_id=printer_id,
  3870. source_file=source_3mf,
  3871. print_data={**print_data, "status": archive.status or "printing"},
  3872. subtask_id=archive.subtask_id,
  3873. update_archive_id=archive.id,
  3874. )
  3875. if recovered is None:
  3876. return False
  3877. logger.info(
  3878. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3879. archive_id,
  3880. source_3mf,
  3881. recovered.file_size,
  3882. )
  3883. # Spoolman's tracking stored no 3MF usage at print start and would
  3884. # charge the AMS remain% change; the built-in tracker reads the archive
  3885. # at completion and needs nothing. Also at the print's end (``price``
  3886. # False): that recovery runs inside the close-out, before the charge.
  3887. try:
  3888. from backend.app.services.spoolman_tracking import attach_recovered_3mf
  3889. from backend.app.services.usage_tracker import is_completing
  3890. await attach_recovered_3mf(
  3891. printer_id,
  3892. recovered.id,
  3893. recovered.file_path,
  3894. db,
  3895. printer_manager,
  3896. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3897. may_start=not price or (recovered.status == "printing" and not is_completing(printer_id)),
  3898. )
  3899. except Exception:
  3900. logger.warning(
  3901. "[RECOVER] Archive %s: could not add the 3MF to Spoolman's usage tracking", archive_id, exc_info=True
  3902. )
  3903. if price and recovered.status == "printing" and recovered.file_path:
  3904. # Print start had no 3MF to read the slicer's pauses from (#2984).
  3905. _load_pauses_from_3mf(app_settings.base_dir / recovered.file_path, printer_id)
  3906. if price and recovered.status == "printing":
  3907. # Print start priced it from the default rate, having no 3MF to
  3908. # estimate from; now it has one. An ended print is left alone: its
  3909. # end prices it. A print Bambuddy didn't dispatch has no start
  3910. # plate; the one the archive just read from the 3MF stands in.
  3911. _schedule_archive_cost_estimate(
  3912. printer_id,
  3913. recovered.id,
  3914. printer_manager,
  3915. ams_mapping=_get_start_ams_mapping(print_data, printer_id, recovered.id),
  3916. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3917. session_factory=async_session,
  3918. )
  3919. # `archive_updated`, not `archive_created` — the row was already on the
  3920. # Archives page as an empty card and is now filled in, not new.
  3921. await ws_manager.send_archive_updated(
  3922. {
  3923. "id": recovered.id,
  3924. "printer_id": recovered.printer_id,
  3925. "filename": recovered.filename,
  3926. "print_name": recovered.print_name,
  3927. "status": recovered.status,
  3928. }
  3929. )
  3930. return True
  3931. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path, *, price: bool = True) -> bool:
  3932. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3933. Called from the paths that pull a 3MF for a print that is already under way
  3934. — chiefly the cover endpoint, which downloads the very file the archive flow
  3935. could not get and, before #2957, used it for a thumbnail and nothing else.
  3936. The bytes are already local, so this costs a parse and a row update.
  3937. No-op when the running print has a real archive, which is the common case.
  3938. """
  3939. from backend.app.models.archive import PrintArchive
  3940. logger = logging.getLogger(__name__)
  3941. # `_active_prints` is keyed on the raw names seen at print start — the
  3942. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3943. # Callers here arrive with whichever variant their own path produced, so
  3944. # match on the same normalization the download cache uses rather than on an
  3945. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3946. # endpoint find an archive registered under "Desktop_Goose".
  3947. wanted = normalize_3mf_name(name)
  3948. archive_id = None
  3949. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3950. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3951. archive_id = value
  3952. break
  3953. if archive_id is None:
  3954. return False
  3955. async with async_session() as db:
  3956. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3957. # Cheap pre-check so the common case (a normal archive) does no work.
  3958. if archive is None or archive.file_path or archive.deleted_at is not None:
  3959. return False
  3960. try:
  3961. return await _recover_fallback_archive(archive_id, path, printer_id, price=price)
  3962. except Exception as e:
  3963. # Recovery is opportunistic. A failure here must never take down the
  3964. # caller, which is usually just trying to render a thumbnail.
  3965. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3966. return False
  3967. def _schedule_fallback_3mf_retry(
  3968. printer_id: int,
  3969. archive_id: int,
  3970. filenames: list[str],
  3971. delays: tuple[float, ...] | None = None,
  3972. reason: str = REASON_FTPS_COOLOFF,
  3973. ) -> None:
  3974. """Re-attempt the 3MF download after a temporary give-up.
  3975. ``reason`` says which give-up this is, and picks the default ladder: an
  3976. FTPS cool-off has to be waited out, while a transfer that timed out under
  3977. contention is worth asking about again straight away (#3063). It is only
  3978. read for the ladder and the log line -- the retry itself is identical, since
  3979. in both cases the file is on the printer and the last attempt at it failed
  3980. for a reason that does not last.
  3981. """
  3982. logger = logging.getLogger(__name__)
  3983. if delays is None:
  3984. delays = (
  3985. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3986. if reason == REASON_FTP_TRANSFER_FAILED
  3987. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3988. )
  3989. async def _retry() -> None:
  3990. from backend.app.models.archive import PrintArchive
  3991. from backend.app.models.printer import Printer
  3992. for delay in delays:
  3993. await asyncio.sleep(delay)
  3994. async with async_session() as db:
  3995. archive = (
  3996. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3997. ).scalar_one_or_none()
  3998. if archive is None or archive.deleted_at is not None or archive.file_path:
  3999. return
  4000. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  4001. if printer is None:
  4002. return
  4003. # Read the fields while the session is open rather than touching
  4004. # a detached instance minutes later, mid-download.
  4005. printer_ip = printer.ip_address
  4006. printer_code = printer.access_code
  4007. printer_model = printer.model
  4008. # Someone else may have fetched it in the meantime — the cover
  4009. # endpoint routinely does, and its copy is the same bytes.
  4010. for name in filenames:
  4011. cached = get_cached_3mf(printer_id, name)
  4012. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  4013. return
  4014. if ftps_handshake_blocked(printer_ip):
  4015. logger.info(
  4016. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  4017. printer_id,
  4018. archive_id,
  4019. )
  4020. continue
  4021. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  4022. for candidate in filenames:
  4023. # Bare name only. These come from the print-start flow, which
  4024. # already strips the path, but the local temp write must not
  4025. # depend on that holding for every future caller — a name that
  4026. # is absolute or contains ".." would otherwise escape the data
  4027. # volume via the `/` operator.
  4028. name = Path(candidate).name
  4029. if not name or name in (".", ".."):
  4030. continue
  4031. if not name.endswith(".3mf"):
  4032. name = f"{name}.3mf"
  4033. temp_path = app_settings.archive_dir / "temp" / name
  4034. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4035. try:
  4036. hit = await download_file_try_paths_async(
  4037. printer_ip,
  4038. printer_code,
  4039. ftp_probe_paths(name),
  4040. temp_path,
  4041. socket_timeout=ftp_timeout,
  4042. printer_model=printer_model,
  4043. max_total_timeout=RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  4044. )
  4045. except Exception as e:
  4046. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  4047. continue
  4048. if not hit:
  4049. continue
  4050. cache_3mf_download(printer_id, name, temp_path)
  4051. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  4052. return
  4053. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  4054. async def _guarded() -> None:
  4055. try:
  4056. await _retry()
  4057. except asyncio.CancelledError:
  4058. raise
  4059. except Exception as e:
  4060. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  4061. finally:
  4062. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  4063. _fallback_3mf_retry_tasks.pop(printer_id, None)
  4064. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  4065. if existing and not existing.done():
  4066. existing.cancel()
  4067. task = asyncio.create_task(_guarded())
  4068. _fallback_3mf_retry_tasks[printer_id] = task
  4069. logger.info(
  4070. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  4071. archive_id,
  4072. reason,
  4073. printer_id,
  4074. ", ".join(f"{d:g}s" for d in delays),
  4075. )
  4076. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  4077. """Whether an archive created here should ask for the print's outcome (#1898).
  4078. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  4079. branches below: a queued job already has its archive and takes the
  4080. expected-print branch, where the queue item's own ``confirm_outcome``
  4081. decides. The queue is still consulted, because a restart mid-print empties
  4082. ``_expected_prints`` — without the check the setting could override a queue
  4083. item that deliberately has the flag off. Any failure answers "don't ask":
  4084. an unwanted prompt is worse than a missing one, and this must never be the
  4085. reason a print goes unarchived.
  4086. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  4087. leaves one behind when a completion cannot be matched to it
  4088. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  4089. only takes it back once the printer has sat connected and terminal for
  4090. minutes. Until then every screen-started print on that printer would
  4091. silently lose its prompt, so the row is held against ``observed_name`` by
  4092. the same comparison a completion uses: a positive disagreement means the row
  4093. is about some other run and this print is external after all.
  4094. """
  4095. logger = logging.getLogger(__name__)
  4096. try:
  4097. # A savepoint rather than a rollback of the caller's transaction on
  4098. # failure: a failed statement leaves the transaction unusable, but a
  4099. # full rollback also expires every object the caller has loaded (the
  4100. # printer, the archive it just created), and on an async session the
  4101. # next attribute read then raises instead of reloading. Everything here
  4102. # is a read, so undoing the savepoint loses nothing.
  4103. async with db.begin_nested():
  4104. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  4105. except Exception as e:
  4106. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  4107. return False
  4108. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  4109. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  4110. from backend.app.api.routes.settings import get_setting, setting_is_true
  4111. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  4112. return False
  4113. from backend.app.models.print_queue import PrintQueueItem
  4114. dispatched_here = await db.scalar(
  4115. select(PrintQueueItem)
  4116. .where(
  4117. PrintQueueItem.printer_id == printer_id,
  4118. PrintQueueItem.status == "printing",
  4119. )
  4120. .limit(1)
  4121. )
  4122. if dispatched_here is None:
  4123. return True
  4124. expected = await _queue_item_dispatched_name(db, dispatched_here)
  4125. observed = (observed_name or "").strip()
  4126. if not expected or not observed or _subtask_names_match(expected, observed):
  4127. logger.info(
  4128. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  4129. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  4130. printer_id,
  4131. dispatched_here.id,
  4132. )
  4133. return False
  4134. logger.info(
  4135. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  4136. "%r; treating this as an externally started print.",
  4137. dispatched_here.id,
  4138. printer_id,
  4139. expected,
  4140. observed,
  4141. )
  4142. return True
  4143. async def _dispatch_outcome_confirmation_safely(
  4144. db,
  4145. printer_id: int,
  4146. printer_name: str,
  4147. data: dict,
  4148. archive_id: int,
  4149. archive_data: dict | None = None,
  4150. run_id: int | None = None,
  4151. ) -> None:
  4152. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  4153. The completion task sends the per-user print email on the same session
  4154. right after the prompt. A failed statement in the prompt leaves that
  4155. session needing a rollback, and without one the email step fails with
  4156. PendingRollbackError; the prompt is the optional part, so it must not be
  4157. the reason the email never goes out.
  4158. """
  4159. try:
  4160. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data, run_id=run_id)
  4161. except Exception as e:
  4162. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  4163. try:
  4164. await db.rollback()
  4165. except Exception:
  4166. pass
  4167. async def _outcome_answerers(db, owner_id: int | None) -> set[int] | None:
  4168. """Who may answer a print's outcome prompt in the app: its owner and anyone
  4169. who may change everyone's archives. None (everyone on the printer) with auth
  4170. off, or for a print nobody owns."""
  4171. from sqlalchemy.orm import selectinload
  4172. from backend.app.core.auth import is_auth_enabled
  4173. from backend.app.core.permissions import Permission
  4174. from backend.app.models.user import User
  4175. if owner_id is None or not await is_auth_enabled(db):
  4176. return None
  4177. users = (await db.execute(select(User).options(selectinload(User.groups)).where(User.is_active))).scalars().all()
  4178. return {owner_id} | {u.id for u in users if u.has_permission(Permission.ARCHIVES_UPDATE_ALL.value)}
  4179. async def dispatch_outcome_confirmation(
  4180. db,
  4181. printer_id: int,
  4182. printer_name: str,
  4183. data: dict,
  4184. archive_id: int,
  4185. archive_data: dict | None = None,
  4186. *,
  4187. run_id: int | None = None,
  4188. ) -> bool:
  4189. """Emit the post-print outcome prompt for a completed print (#1898).
  4190. Gated on the run that ended (``run_id``): ``confirm_requested`` is the
  4191. opt-in (from the queue item, or from ``confirm_outcome_external_prints``
  4192. for a print Bambuddy did not start, copied onto the run at its start) and
  4193. ``user_verdict`` being unset is what makes the question still open. Mints
  4194. the run's capability token the one-tap verdict links carry: plates of one
  4195. archive each have their own question. Without a run, the archive's, as
  4196. before runs.
  4197. Lives here rather than inline in ``on_print_complete``'s notification task
  4198. because that task swallows every exception: extracted, the gate and the two
  4199. emissions can be driven by a test, which is the only thing standing between
  4200. a regression here and a farm that quietly stops asking.
  4201. Returns whether a prompt was sent.
  4202. """
  4203. logger = logging.getLogger(__name__)
  4204. from backend.app.models.archive import PrintArchive
  4205. from backend.app.models.print_log import PrintLogEntry
  4206. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  4207. if confirm_archive is None:
  4208. return False
  4209. run = await db.get(PrintLogEntry, run_id) if run_id is not None else None
  4210. if run is not None and run.archive_id != archive_id:
  4211. run = None
  4212. # The run carries the opt-in from its start; one logged before it did
  4213. # (None) asks as its archive does.
  4214. asks = confirm_archive if run is None or run.confirm_requested is None else run
  4215. holder = run if run is not None else confirm_archive
  4216. if not (asks.confirm_requested and holder.user_verdict is None):
  4217. return False
  4218. import secrets as _secrets
  4219. # A spent token stays on the row so the one-tap route can recognise it, so
  4220. # "has a token" no longer means "answerable". A prompt going out now needs a
  4221. # live one: mint a new token whenever the stored one is already spent, or
  4222. # every button in the new message would land on the already-answered page.
  4223. if not holder.confirm_token or holder.confirm_token_used_at is not None:
  4224. holder.confirm_token = _secrets.token_urlsafe(32)
  4225. holder.confirm_token_used_at = None
  4226. await db.commit()
  4227. from backend.app.api.routes.settings import get_external_base_url, get_setting
  4228. base = await get_external_base_url(db)
  4229. if not await get_setting(db, "external_url"):
  4230. # Both the Telegram inline keyboard and the ntfy action buttons need an
  4231. # absolute URL, so an unconfigured install used to get a message body
  4232. # with two unusable relative paths and no buttons at all. The shared
  4233. # fallback at least produces tappable links; say which setting makes
  4234. # them resolve from a phone.
  4235. logger.warning(
  4236. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  4237. "Set Settings → External URL so they resolve away from this host.",
  4238. base,
  4239. )
  4240. token = holder.confirm_token
  4241. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  4242. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  4243. confirm_url = f"{base}/archives?confirm={archive_id}" + (f"&run={run.id}" if run is not None else "")
  4244. await ws_manager.send_print_confirm_request(
  4245. printer_id,
  4246. {
  4247. "archive_id": archive_id,
  4248. "run_id": run.id if run is not None else None,
  4249. "print_name": confirm_archive.print_name or confirm_archive.filename,
  4250. },
  4251. user_ids=await _outcome_answerers(db, confirm_archive.created_by_id),
  4252. )
  4253. await notification_service.on_print_confirm_request(
  4254. printer_id,
  4255. printer_name,
  4256. data,
  4257. db,
  4258. archive_data=archive_data,
  4259. good_url=good_url,
  4260. reject_url=reject_url,
  4261. confirm_url=confirm_url,
  4262. archive_id=archive_id,
  4263. run_id=run.id if run is not None else None,
  4264. )
  4265. return True
  4266. async def _printer_gone(db, printer_id: int) -> bool:
  4267. """Whether the printer was deleted. A column read: the session's loaded
  4268. Printer would otherwise answer for the database."""
  4269. from backend.app.models.printer import Printer
  4270. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  4271. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  4272. """Remove the archive just written if its printer was deleted meanwhile.
  4273. The delete route sweeps the printer's archives before it commits, so a row
  4274. committed after that sweep (the check before writing passed while the
  4275. delete was still uncommitted) is left for a printer that will never report
  4276. the print's end. A row the sweep reached is the route's: deleted with the
  4277. printer's archives, or detached (printer_id NULL) when the user kept them,
  4278. and then left as it is. Either way nothing is registered for it. Run after
  4279. the archive's commit, before anything is registered for it.
  4280. """
  4281. from backend.app.models.archive import PrintArchive
  4282. if not await _printer_gone(db, printer_id):
  4283. return False
  4284. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  4285. if owner == printer_id:
  4286. logging.getLogger(__name__).info(
  4287. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  4288. )
  4289. await ArchiveService(db).delete_archive(archive_id)
  4290. await forget_printer(printer_id)
  4291. return True
  4292. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  4293. """After an IntegrityError on a print start's archive write: whether it was
  4294. the printer being deleted, forgotten then (the caller returns).
  4295. PostgreSQL: the delete route locks the printer from its archive sweep to its
  4296. commit, so an archive written or adopted for it meanwhile (one that sets
  4297. printer_id) waits and the printer's foreign key then refuses it. That is
  4298. the printer being deleted, not an error; anything else is re-raised by the
  4299. caller.
  4300. """
  4301. await db.rollback()
  4302. if not await _printer_gone(db, printer_id):
  4303. return False
  4304. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  4305. await forget_printer(printer_id)
  4306. return True
  4307. async def _forget_if_printer_gone(printer_id: int) -> None:
  4308. """At the end of a print start: the slow steps after the last check (smart
  4309. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  4310. printer's delete and its forget_printer, and then wrote state back.
  4311. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  4312. SQLite; PostgreSQL refuses it.)
  4313. Its own session: those steps can leave the handler's needing a rollback (a
  4314. write to the archive the delete removed). Never raises: it runs inside the
  4315. fallback branch's try, whose except reports the archive as failed.
  4316. """
  4317. try:
  4318. async with async_session() as db:
  4319. gone = await _printer_gone(db, printer_id)
  4320. if gone:
  4321. await forget_printer(printer_id)
  4322. except Exception:
  4323. logging.getLogger(__name__).warning(
  4324. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  4325. )
  4326. async def _announce_plate_check_failed(printer_id: int, printer_name: str, reason: str) -> None:
  4327. """Tell the UI a plate check could not run. It does not block the print,
  4328. but an unchecked plate is not an empty one."""
  4329. try:
  4330. await ws_manager.broadcast(
  4331. {"type": "plate_check_failed", "printer_id": printer_id, "printer_name": printer_name, "reason": reason}
  4332. )
  4333. except Exception as e:
  4334. logging.getLogger(__name__).warning("[PLATE CHECK] Could not announce the failed check: %s", e)
  4335. def _expected_print_keys(printer_id: int, filename: str | None, subtask_name: str | None) -> list[tuple[int, str]]:
  4336. """The ``_expected_prints`` keys a print start may be registered under."""
  4337. keys: list[tuple[int, str]] = []
  4338. if subtask_name:
  4339. keys.append((printer_id, subtask_name))
  4340. keys.append((printer_id, f"{subtask_name}.3mf"))
  4341. keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  4342. if filename:
  4343. fname = filename.split("/")[-1] if "/" in filename else filename
  4344. keys.append((printer_id, fname))
  4345. # Strip extensions to match
  4346. base = fname.replace(".gcode", "").replace(".3mf", "")
  4347. keys.append((printer_id, base))
  4348. keys.append((printer_id, f"{base}.3mf"))
  4349. return keys
  4350. async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, subtask_name: str | None) -> bool:
  4351. """Whether this print start is one Bambuddy sent to the printer."""
  4352. if any(key in _expected_prints for key in _expected_print_keys(printer_id, filename, subtask_name)):
  4353. return True
  4354. from backend.app.models.archive import PrintArchive
  4355. from backend.app.models.print_queue import PrintQueueItem
  4356. # The queue row the scheduler sets to printing before it sends -- but only
  4357. # when it was sent as this print: a row left printing by a run whose end
  4358. # was missed names another file.
  4359. dispatched_names = (
  4360. await db.execute(
  4361. select(PrintArchive.filename)
  4362. .join(PrintQueueItem, PrintQueueItem.archive_id == PrintArchive.id)
  4363. .where(PrintQueueItem.printer_id == printer_id, PrintQueueItem.status == "printing")
  4364. )
  4365. ).scalars()
  4366. observed = [name for name in (subtask_name, (filename or "").rsplit("/", 1)[-1]) if name]
  4367. return any(
  4368. _subtask_names_match(_subtask_name_from_filename(dispatched), _subtask_name_from_filename(seen))
  4369. for dispatched in dispatched_names
  4370. if dispatched
  4371. for seen in observed
  4372. )
  4373. async def on_print_start(printer_id: int, data: dict):
  4374. """Handle print start - archive the 3MF file immediately."""
  4375. logger = logging.getLogger(__name__)
  4376. # The print's start, before the 3MF download that the archive waits for
  4377. # (#3327): a minute of it would otherwise be missing from the print time.
  4378. detected_at = datetime.now(timezone.utc)
  4379. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  4380. try:
  4381. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  4382. except Exception:
  4383. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  4384. # Clear any stale user-stopped flag from previous print cycles
  4385. _user_stopped_printers.discard(printer_id)
  4386. _kill_switch_stopped.discard(printer_id)
  4387. # A new print starts its milestones from zero (#3211). The status path only
  4388. # resets on progress below 5 while not printing, which a printer that goes
  4389. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  4390. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  4391. # or on resume from pause, so it cannot repeat a milestone mid-print.
  4392. _last_progress_milestone[printer_id] = 0
  4393. _kill_switch_notification_tasks.pop(printer_id, None)
  4394. # #1721: drop any leftover pre-captured finish frame from a prior print
  4395. # so a never-consumed cache entry can't bleed into the new print's photo.
  4396. _stage22_finish_frames.pop(printer_id, None)
  4397. # #1867: same for the in-print frame bank — a queued print must not reuse
  4398. # the previous job's banked frame.
  4399. _inprint_frame_bank.pop(printer_id, None)
  4400. _inprint_frame_bank_ts.pop(printer_id, None)
  4401. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  4402. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  4403. # print's flag instead of inheriting it.
  4404. print_dispatch_context.adopt(printer_id)
  4405. # Cancel any active bed cooldown waiter for this printer
  4406. if _bed_cool_waiters.pop(printer_id, None):
  4407. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  4408. # Clear cached cover images so the new print's thumbnail is fetched fresh
  4409. from backend.app.api.routes.printers import clear_cover_cache
  4410. clear_cover_cache(printer_id)
  4411. await ws_manager.send_print_start(printer_id, data)
  4412. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  4413. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  4414. # MQTT relay - publish print start
  4415. try:
  4416. printer_info = printer_manager.get_printer(printer_id)
  4417. if printer_info:
  4418. await mqtt_relay.on_print_start(
  4419. printer_id,
  4420. printer_info.name,
  4421. printer_info.serial_number,
  4422. data.get("filename", ""),
  4423. data.get("subtask_name", ""),
  4424. )
  4425. except Exception:
  4426. pass # Don't fail print start callback if MQTT fails
  4427. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  4428. # and mapping, and the seeded tray-change log.
  4429. #
  4430. # Unconditional, for both inventory backends. This only *captures* — the
  4431. # writing is still split, with the internal tracker skipped at completion
  4432. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  4433. # carries its plate-scoped 3MF figures and stored mapping, but not the
  4434. # tray-change log, and that log is the only record of which spool fed
  4435. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  4436. # it on one side only would leave Spoolman users with the mid-print
  4437. # restart bug this fixes for everyone else.
  4438. try:
  4439. async with async_session() as db:
  4440. from backend.app.api.routes.settings import get_setting
  4441. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  4442. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4443. await usage_on_print_start(
  4444. printer_id,
  4445. data,
  4446. printer_manager,
  4447. db=db,
  4448. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  4449. )
  4450. except Exception as e:
  4451. logger.warning("Usage tracker on_print_start failed: %s", e)
  4452. # Track if notification was sent (to avoid sending twice)
  4453. notification_sent = False
  4454. # Smart plug automation: turn on plug when print starts
  4455. try:
  4456. async with async_session() as db:
  4457. await smart_plug_manager.on_print_start(printer_id, db)
  4458. except Exception as e:
  4459. logger.warning("Smart plug on_print_start failed: %s", e)
  4460. async with async_session() as db:
  4461. from backend.app.models.printer import Printer
  4462. from backend.app.services.bambu_ftp import list_files_async
  4463. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4464. printer = result.scalar_one_or_none()
  4465. # Plate detection check - pause if objects detected on build plate
  4466. logger.info(
  4467. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  4468. )
  4469. if printer and printer.plate_detection_enabled:
  4470. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  4471. # Release the pooled DB connection before the plate-detection camera
  4472. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  4473. # printer SELECT has run so far — nothing to persist — so this commit
  4474. # is a data-noop that ends the read transaction and returns the
  4475. # connection to the pool during the I/O (issue #2572). expire_on_commit
  4476. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  4477. # archive lookups below re-acquire a fresh connection on next execute.
  4478. await db.commit()
  4479. try:
  4480. from backend.app.services.plate_detection import check_plate_empty
  4481. # Build ROI tuple from printer settings if available
  4482. roi = None
  4483. if all(
  4484. [
  4485. printer.plate_detection_roi_x is not None,
  4486. printer.plate_detection_roi_y is not None,
  4487. printer.plate_detection_roi_w is not None,
  4488. printer.plate_detection_roi_h is not None,
  4489. ]
  4490. ):
  4491. roi = (
  4492. printer.plate_detection_roi_x,
  4493. printer.plate_detection_roi_y,
  4494. printer.plate_detection_roi_w,
  4495. printer.plate_detection_roi_h,
  4496. )
  4497. # The light is held, not switched, so a live view opened
  4498. # meanwhile keeps it when the check lets go (SP-C11). Every
  4499. # printer, whatever the camera light mode: detection needs it.
  4500. plate_photo_data = None
  4501. objects_detected = False
  4502. check_failure: str | None = None
  4503. async with camera_light(printer, any_mode=True, settle=2.5):
  4504. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  4505. plate_result = await check_plate_empty(
  4506. printer_id=printer_id,
  4507. ip_address=printer.ip_address,
  4508. access_code=printer.access_code,
  4509. model=printer.model,
  4510. include_debug_image=False,
  4511. external_camera_url=printer.external_camera_url,
  4512. external_camera_type=printer.external_camera_type,
  4513. use_external=printer.external_camera_enabled,
  4514. roi=roi,
  4515. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  4516. )
  4517. # No reference to compare against is a check that did not
  4518. # run either: say so rather than call the plate empty.
  4519. check_failure = getattr(plate_result, "failure_reason", None) or (
  4520. "not_calibrated" if plate_result.needs_calibration else None
  4521. )
  4522. objects_detected = not check_failure and not plate_result.is_empty
  4523. if objects_detected:
  4524. # Objects detected - pause the print!
  4525. logger.warning(
  4526. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  4527. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  4528. )
  4529. pause_client = printer_manager.get_client(printer_id)
  4530. if pause_client:
  4531. pause_client.pause_print()
  4532. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  4533. # Snapshot while the light's still on — restoring it first
  4534. # would leave the notification with a dark photo.
  4535. try:
  4536. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  4537. except Exception as snap_err:
  4538. logger.warning(
  4539. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  4540. )
  4541. if objects_detected:
  4542. # Send notification about plate not empty
  4543. await ws_manager.broadcast(
  4544. {
  4545. "type": "plate_not_empty",
  4546. "printer_id": printer_id,
  4547. "printer_name": printer.name,
  4548. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  4549. }
  4550. )
  4551. # Also send push notification
  4552. try:
  4553. await notification_service.on_plate_not_empty(
  4554. printer_id=printer_id,
  4555. printer_name=printer.name,
  4556. db=db,
  4557. difference_percent=plate_result.difference_percent,
  4558. image_data=plate_photo_data,
  4559. )
  4560. except Exception as notif_err:
  4561. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4562. elif check_failure:
  4563. logger.warning(
  4564. "[PLATE CHECK] Plate check could not run for printer %s (%s): %s; proceeding with print",
  4565. printer_id,
  4566. check_failure,
  4567. plate_result.message,
  4568. )
  4569. await _announce_plate_check_failed(printer_id, printer.name, check_failure)
  4570. else:
  4571. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4572. except Exception as plate_err:
  4573. # Don't block print on plate detection errors
  4574. logger.warning(
  4575. "[PLATE CHECK] Plate check could not run for printer %s: %s; proceeding with print",
  4576. printer_id,
  4577. plate_err,
  4578. )
  4579. await _announce_plate_check_failed(printer_id, printer.name, "error")
  4580. if not printer:
  4581. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4582. if not notification_sent:
  4583. await _send_print_start_notification(printer_id, data, logger=logger)
  4584. return
  4585. # Skip the printer's own jobs — a calibration run is not a user's print.
  4586. # See is_internal_printer_job for what counts and why both fields are
  4587. # tested; the pressure-advance line reports as a subtask name with no
  4588. # /usr/ path, which the old prefix-only test here missed entirely.
  4589. #
  4590. # No notification either. The event describes the printer calibrating
  4591. # itself, so "Print started" is as wrong as the archive was, and the
  4592. # matching completion is suppressed in on_print_complete for the same
  4593. # reason. Checked before the auto-archive switches, whose "off" path
  4594. # still notifies.
  4595. # A /usr/ path is the printer's own file. A name alone is not proof: a
  4596. # print Bambuddy dispatched is never one, whatever it is called.
  4597. # Dispatched = an expected print, or, after a restart that lost those,
  4598. # a queue job printing on the printer.
  4599. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")) and (
  4600. (data.get("filename") or "").startswith("/usr/")
  4601. or not await _dispatched_by_bambuddy(db, printer_id, data.get("filename", ""), data.get("subtask_name", ""))
  4602. ):
  4603. logger.info(
  4604. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4605. data.get("filename", ""),
  4606. data.get("subtask_name", ""),
  4607. )
  4608. return
  4609. # The global switch is the master: off, no printer archives prints
  4610. # started outside Bambuddy; on, each printer's own switch decides.
  4611. from backend.app.api.routes.settings import get_setting
  4612. _global_auto_archive = await get_setting(db, "auto_archive")
  4613. archives_prints = printer.auto_archive and (
  4614. _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4615. )
  4616. if not archives_prints:
  4617. # auto-archive disabled — check if there's an expected print (dispatched
  4618. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4619. # If so, fall through to the expected-print handling below so the archive
  4620. # is tracked in _active_prints and usage tracking works at completion.
  4621. _fn = data.get("filename", "")
  4622. _sn = data.get("subtask_name", "")
  4623. _check_keys: list[tuple[int, str]] = []
  4624. if _sn:
  4625. _check_keys += [
  4626. (printer_id, _sn),
  4627. (printer_id, f"{_sn}.3mf"),
  4628. (printer_id, f"{_sn}.gcode.3mf"),
  4629. ]
  4630. if _fn:
  4631. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4632. _check_keys.append((printer_id, _base_fn))
  4633. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4634. _check_keys += [
  4635. (printer_id, _no_archive_base),
  4636. (printer_id, f"{_no_archive_base}.3mf"),
  4637. ]
  4638. _has_expected = any(k in _expected_prints for k in _check_keys)
  4639. if not _has_expected:
  4640. # No expected print — truly external print (started from slicer/touchscreen)
  4641. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4642. if not notification_sent:
  4643. _no_archive_creator: int | None = None
  4644. for _key in _check_keys:
  4645. _expected_prints.pop(_key, None)
  4646. _expected_print_registered_at.pop(_key, None)
  4647. popped_creator = _expected_print_creators.pop(_key, None)
  4648. if _no_archive_creator is None:
  4649. _no_archive_creator = popped_creator
  4650. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4651. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4652. return
  4653. else:
  4654. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4655. # Get the filename and subtask_name
  4656. filename = data.get("filename", "")
  4657. subtask_name = data.get("subtask_name", "")
  4658. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4659. # present, it lets us match an archive across a backend restart (#972):
  4660. # same id → same print → resume the existing row instead of cancelling
  4661. # it and recreating from scratch (which loses started_at). Treat "0"
  4662. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4663. raw_mqtt = data.get("raw_data") or {}
  4664. subtask_id = raw_mqtt.get("subtask_id")
  4665. if subtask_id is not None:
  4666. subtask_id = str(subtask_id).strip()
  4667. if subtask_id in ("", "0"):
  4668. subtask_id = None
  4669. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4670. if not filename and not subtask_name:
  4671. # Send notification without archive data (no filename)
  4672. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4673. if not notification_sent:
  4674. await _send_print_start_notification(printer_id, data, logger=logger)
  4675. return
  4676. # Check if this is an expected print from reprint/scheduled
  4677. expected_keys = _expected_print_keys(printer_id, filename, subtask_name)
  4678. expected_archive_id = None
  4679. # Who queued it, taken with the entries it was registered beside: left
  4680. # behind once those are gone (the archive deleted mid-dispatch, or the
  4681. # start notification already sent), the expiry never saw it, and an
  4682. # unrelated later print of that name was attributed to that user (EP-2).
  4683. fallback_creator = None
  4684. for key in expected_keys:
  4685. expected_archive_id = _expected_prints.pop(key, None)
  4686. _expected_print_registered_at.pop(key, None)
  4687. if expected_archive_id:
  4688. # Clean up other possible keys for this print
  4689. for other_key in expected_keys:
  4690. _expected_prints.pop(other_key, None)
  4691. _expected_print_registered_at.pop(other_key, None)
  4692. creator = _expected_print_creators.pop(other_key, None)
  4693. if fallback_creator is None:
  4694. fallback_creator = creator
  4695. break
  4696. if expected_archive_id:
  4697. # This is a reprint/scheduled print - use existing archive, don't create new one
  4698. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4699. # Bambuddy dispatched it: the kill switch's fast path keeps it as
  4700. # Bambuddy's once the expected entry is consumed here.
  4701. _owned_print_archive_ids.add(expected_archive_id)
  4702. from backend.app.models.archive import PrintArchive
  4703. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4704. archive = result.scalar_one_or_none()
  4705. # Deleted after this handler loaded it (the plate check waits
  4706. # seconds) but before the route forgot the expected print: the
  4707. # archive the route kept or deleted is left as the route left it.
  4708. if archive and await _printer_gone(db, printer_id):
  4709. logger.info(
  4710. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4711. )
  4712. await forget_printer(printer_id)
  4713. return
  4714. if archive:
  4715. # As it was before this adoption: put back if the printer turns
  4716. # out to have been deleted while it was adopted (below).
  4717. before_adoption = {
  4718. attr.columns[0].name: getattr(archive, attr.key)
  4719. for attr in sa_inspect(PrintArchive).column_attrs
  4720. if attr.key != "id"
  4721. }
  4722. # Update archive status to printing
  4723. archive.status = "printing"
  4724. archive.started_at = datetime.now(timezone.utc)
  4725. # The previous run's outcome is not this one's: a reprint that
  4726. # completes must not keep showing why the last one failed.
  4727. archive.failure_reason = None
  4728. archive.completed_at = None
  4729. # The previous run's answer is still on this row and the
  4730. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4731. # so without a reset the second run inherits the first run's
  4732. # verdict: no prompt at all, and a green "good" badge on a run
  4733. # nobody ever judged.
  4734. if archive.confirm_requested:
  4735. archive.user_verdict = None
  4736. archive.user_verdict_source = None
  4737. archive.user_verdict_at = None
  4738. archive.confirm_token = None
  4739. archive.confirm_token_used_at = None
  4740. # Reprint of an archive reuses the source row. Without resetting
  4741. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4742. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4743. # extracts the *original* print's last frame, which then ships in
  4744. # the completion notification (#1707). Clear the path so the
  4745. # scanner runs fresh; also unlink the old video file so reprints
  4746. # don't accumulate orphans in the archive directory. Photos list
  4747. # is left alone — accumulating one finish photo per run is fine.
  4748. # The print-start baseline (#2704) is stale for the same reason:
  4749. # it describes the printer before the previous run. The capture
  4750. # below overwrites it, but clear it here too so an early failure
  4751. # can't leave the scan diffing against the wrong snapshot.
  4752. #
  4753. # Unlinked only when it is the same plate printing again. Every
  4754. # plate of a Send All shares this archive, and the video on it
  4755. # can be the only copy of another plate's run -- the printer's
  4756. # was deleted once it attached (#3275). That one is left in the
  4757. # archive directory, which goes with the archive. A video whose
  4758. # plate is not on record (attached by hand, or before the
  4759. # column existed) is kept too where the 3MF has other plates,
  4760. # or cannot be read: nothing tells it apart from another plate's,
  4761. # and keeping costs one file where deleting can cost the only
  4762. # copy. On an archive with exactly one plate it is that plate's.
  4763. archive.timelapse_baseline = None
  4764. stale_timelapse_relpath = archive.timelapse_path
  4765. stale_timelapse_plate_id = archive.timelapse_plate_id
  4766. starting_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4767. if stale_timelapse_relpath:
  4768. archive.timelapse_path = None
  4769. archive.timelapse_plate_id = None
  4770. stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
  4771. if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
  4772. from backend.app.services.archive import plate_indexes_in_3mf
  4773. plates = await asyncio.to_thread(
  4774. plate_indexes_in_3mf,
  4775. app_settings.base_dir / archive.file_path, # SEC-PATH-OK: stored relative archive path
  4776. )
  4777. stale_is_this_plates = len(plates) == 1
  4778. if stale_timelapse_relpath and not stale_is_this_plates:
  4779. logger.info(
  4780. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4781. stale_timelapse_relpath,
  4782. stale_timelapse_plate_id,
  4783. expected_archive_id,
  4784. starting_plate_id,
  4785. )
  4786. # The video is deleted once the adoption stands (below).
  4787. delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
  4788. # Persist a restart-stable id so a later restart resumes this
  4789. # archive by subtask_id instead of name-matching + duplicating
  4790. # it (#1485). The printer often hasn't echoed subtask_id back
  4791. # this soon after dispatch, so fall back to the id Bambuddy
  4792. # minted when it sent the print command. Scoped to this
  4793. # expected-print branch on purpose: an expected match means
  4794. # Bambuddy dispatched this exact print in this process, so the
  4795. # client's last-dispatch id genuinely belongs to it — using it
  4796. # for an externally-started print could mis-tag the archive.
  4797. effective_subtask_id = subtask_id
  4798. if not effective_subtask_id:
  4799. _client = printer_manager.get_client(printer_id)
  4800. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4801. if _dispatched:
  4802. effective_subtask_id = str(_dispatched).strip() or None
  4803. # Update on first-set OR on reprint (the queue dispatcher mints
  4804. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4805. # the rewrite for reprints leaves the archive holding the FIRST
  4806. # run's id; if MQTT then reconnects mid-print, the reconciler
  4807. # (#1542) compares the stale stored id against the printer's
  4808. # live id, sees a mismatch, and synthesises a bogus PRINT
  4809. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4810. # in #1807. Inequality check preserves the noop-on-stable-push
  4811. # behaviour the earlier `not archive.subtask_id` guard provided.
  4812. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4813. archive.subtask_id = effective_subtask_id
  4814. # #1403 follow-up: VP-queue archives are created with
  4815. # printer_id=None at queue-add time (we don't know which
  4816. # printer will run the job yet). When the print actually
  4817. # starts on a specific printer the expected-archive lookup
  4818. # used to skip this assignment, leaving printer_id=None
  4819. # forever — which then disables the "Scan for timelapse"
  4820. # button in ArchivesPage (gated on !archive.printer_id).
  4821. if archive.printer_id != printer_id:
  4822. archive.printer_id = printer_id
  4823. adopting_id = archive.id # a rollback expires the object
  4824. try:
  4825. await db.commit()
  4826. except (IntegrityError, StaleDataError):
  4827. # The archive stays unchanged, or is gone: "delete archives"
  4828. # removed the row under the adoption, which then matched no
  4829. # row (StaleDataError) rather than being refused.
  4830. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4831. return
  4832. raise
  4833. # The printer can be deleted between the check above and this
  4834. # commit (the route's transaction lasts seconds), and the commit
  4835. # then adopted the archive anyway: status, verdict and timelapse
  4836. # changed, and the deleted printer's id written on a row the
  4837. # route had detached or never touched. Undo the adoption.
  4838. if await _printer_gone(db, printer_id):
  4839. logger.info(
  4840. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4841. printer_id,
  4842. archive.id,
  4843. )
  4844. # Everything as before this adoption. The printer it had
  4845. # then stays, unless it was the deleted one: the route
  4846. # detached that row (kept) or deleted it (no row matches).
  4847. previous_printer = before_adoption["printer_id"]
  4848. await db.execute(
  4849. update(PrintArchive)
  4850. .where(PrintArchive.id == archive.id)
  4851. .values(
  4852. {
  4853. **before_adoption,
  4854. "printer_id": None if previous_printer == printer_id else previous_printer,
  4855. }
  4856. )
  4857. )
  4858. await db.commit()
  4859. await forget_printer(printer_id)
  4860. return
  4861. await _drop_replaced_plate_videos(
  4862. db,
  4863. archive.id,
  4864. starting_plate_id,
  4865. stale_timelapse_relpath if delete_stale_video else None,
  4866. logger,
  4867. )
  4868. # Track as active print
  4869. _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
  4870. await _open_run_for(archive.id, printer_id, subtask_id)
  4871. # Start timelapse session if external camera is enabled (#1353).
  4872. # Queue / VP-dispatched prints land here in the expected-archive
  4873. # branch and used to skip start_session entirely — frames were
  4874. # never captured and the post-print stitch silently returned None.
  4875. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4876. # Inject ams_mapping into usage tracker session — the session was created
  4877. # before expected-print promotion, so it may have ams_mapping=None when
  4878. # the MQTT request topic subscription failed (common on P1S/A1).
  4879. _stored_map = _print_ams_mappings.get((printer_id, expected_archive_id))
  4880. _stored_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4881. if _stored_map or _stored_plate_id is not None:
  4882. try:
  4883. from backend.app.services.usage_tracker import _active_sessions
  4884. _ut_session = _active_sessions.get(printer_id)
  4885. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4886. _ut_session.ams_mapping = _stored_map
  4887. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4888. # plate_id injection covers direct-Print of plate N of a multi-plate
  4889. # 3MF — queue prints already capture it via the on_print_start queue
  4890. # lookup, but direct-Print never goes through the queue (#1697).
  4891. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4892. _ut_session.plate_id = _stored_plate_id
  4893. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4894. except Exception:
  4895. pass
  4896. # Set up energy tracking (#941: persist start on archive row)
  4897. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4898. await ws_manager.send_archive_updated(
  4899. {
  4900. "id": archive.id,
  4901. "status": "printing",
  4902. }
  4903. )
  4904. # Send notification with archive data (reprint/scheduled)
  4905. if not notification_sent:
  4906. # Use archive's created_by_id; fall back to the creator registered via
  4907. # register_expected_print (handles library-file-based queue items where
  4908. # the freshly-created archive has no created_by_id yet), taken above.
  4909. archive_data = {
  4910. "print_time_seconds": _run_print_time_seconds(archive, printer_id),
  4911. "created_by_id": archive.created_by_id or fallback_creator,
  4912. }
  4913. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4914. # Extract printable objects from the archived 3MF file
  4915. _load_objects_from_archive(archive, printer_id, logger)
  4916. if archive.file_path:
  4917. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  4918. # Store Spoolman tracking data for per-filament usage reporting
  4919. try:
  4920. await _store_spoolman_print_data(
  4921. printer_id,
  4922. archive.id,
  4923. archive.file_path,
  4924. db,
  4925. printer_manager,
  4926. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4927. plate_id=_get_start_plate_id(printer_id, archive.id),
  4928. )
  4929. except Exception as e:
  4930. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4931. # Price the print from its spools now rather than only at completion (#3261)
  4932. _schedule_archive_cost_estimate(
  4933. printer_id,
  4934. archive.id,
  4935. printer_manager,
  4936. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4937. plate_id=_get_start_plate_id(printer_id, archive.id),
  4938. session_factory=async_session,
  4939. )
  4940. # Capture timelapse file baseline for snapshot-diff on completion
  4941. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4942. # hit this branch — without the baseline the completion-time scan
  4943. # falls into its "take baseline now" fallback, which snapshots
  4944. # AFTER the new MP4 already exists and never matches a diff
  4945. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4946. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4947. await _forget_if_printer_gone(printer_id)
  4948. return # Skip creating a new archive
  4949. # The archive was deleted after the job was queued.
  4950. if not archives_prints:
  4951. # Only the expected print brought a printer that does not
  4952. # archive this far; with it gone, nothing is archived.
  4953. return
  4954. # Otherwise archive the print anew rather than drop it, so it still
  4955. # gets its notification, usage tracking and history.
  4956. logger.warning(
  4957. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4958. expected_archive_id,
  4959. printer_id,
  4960. )
  4961. # Check if there's already a "printing" archive for this printer/file
  4962. # This prevents duplicates when backend restarts during an active print
  4963. from backend.app.models.archive import PrintArchive
  4964. existing_archive: PrintArchive | None = None
  4965. resumed_by_run = False
  4966. # Best match: this job's run, open on the printer since the print
  4967. # started. The archive row is shared by every plate of it, and its
  4968. # printer, job id and status are the latest start's, which may be
  4969. # another printer's.
  4970. if subtask_id:
  4971. from backend.app.services.print_log import open_run_on_printer
  4972. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  4973. if run is not None and run.archive_id is not None:
  4974. existing_archive = await db.scalar(
  4975. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  4976. )
  4977. resumed_by_run = existing_archive is not None
  4978. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4979. # across a backend restart for the same print, so this is the most
  4980. # reliable way to reattach. Only a row still printing: a cancelled one
  4981. # has been through completion (usage, history, notifications) already,
  4982. # and reopening it would count the print twice.
  4983. if subtask_id and existing_archive is None:
  4984. by_id = await db.execute(
  4985. select(PrintArchive)
  4986. .where(PrintArchive.printer_id == printer_id)
  4987. .where(PrintArchive.subtask_id == subtask_id)
  4988. .where(PrintArchive.status == "printing")
  4989. .order_by(PrintArchive.created_at.desc())
  4990. .limit(1)
  4991. )
  4992. existing_archive = by_id.scalar_one_or_none()
  4993. # Fallback match: name-based lookup. Kept as-is for prints whose
  4994. # subtask_id is missing ("0" / local / non-cloud prints).
  4995. if existing_archive is None:
  4996. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4997. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4998. # A print started from the printer's screen names its file in full,
  4999. # so the forms above double its extension. The file itself is the
  5000. # one exact match, and nothing looser is added (#3009).
  5001. if _subtask_is_the_file(subtask_name, filename):
  5002. archive_filenames.append(subtask_name)
  5003. existing = await db.execute(
  5004. select(PrintArchive)
  5005. .where(PrintArchive.printer_id == printer_id)
  5006. .where(PrintArchive.status == "printing")
  5007. .where(
  5008. or_(
  5009. PrintArchive.print_name == check_name,
  5010. PrintArchive.filename.in_(archive_filenames),
  5011. )
  5012. )
  5013. .order_by(PrintArchive.created_at.desc())
  5014. .limit(1)
  5015. )
  5016. existing_archive = existing.scalar_one_or_none()
  5017. if existing_archive:
  5018. # subtask_id match → always resume, regardless of age. Same print,
  5019. # just a backend restart.
  5020. subtask_match = resumed_by_run or bool(subtask_id and existing_archive.subtask_id == subtask_id)
  5021. if subtask_match:
  5022. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  5023. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  5024. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  5025. _mark_owned_if_dispatched(existing_archive)
  5026. if await _run_needs_energy_start(existing_archive, printer_id, db):
  5027. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  5028. if not notification_sent:
  5029. archive_data = {
  5030. "print_time_seconds": _run_print_time_seconds(existing_archive, printer_id),
  5031. "created_by_id": existing_archive.created_by_id,
  5032. }
  5033. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5034. _load_objects_from_archive(existing_archive, printer_id, logger)
  5035. if existing_archive.file_path:
  5036. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  5037. return
  5038. # Name-match only (no subtask_id to anchor on): decide resume vs.
  5039. # stale from the printer's *current* progress, not wall-clock age.
  5040. # A genuinely long print used to trip a blind 4h cutoff and have its
  5041. # live archive cancelled + duplicated on every backend restart
  5042. # (#1485). If the printer reports real progress, this name-matched
  5043. # 'printing' archive IS that ongoing print — resume it whatever its
  5044. # age. Only treat it as a stale leftover when the printer clearly
  5045. # shows a different, freshly-started print: near-0% progress on an
  5046. # archive far too old to still be at 0%. Unknown progress (printer
  5047. # not connected) never cancels — resuming is the safe default.
  5048. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  5049. live_status = printer_manager.get_status(printer_id)
  5050. live_progress = getattr(live_status, "progress", None) if live_status else None
  5051. looks_stale = (
  5052. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  5053. )
  5054. # Two subtask ids are two prints, however young the archive: one
  5055. # whose completion was missed must not swallow the next print of
  5056. # the same file. Except Bambuddy's own reprint, which reuses the
  5057. # row and mints a fresh id (#1807): the id it last sent says so,
  5058. # and after a restart, which forgets it, this printer's queue job
  5059. # running the archive.
  5060. if (
  5061. not looks_stale
  5062. and subtask_id
  5063. and existing_archive.subtask_id
  5064. and existing_archive.subtask_id != subtask_id
  5065. ):
  5066. _client = printer_manager.get_client(printer_id)
  5067. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  5068. if _dispatched:
  5069. looks_stale = _dispatched != subtask_id
  5070. else:
  5071. from backend.app.models.print_queue import PrintQueueItem as _PQI
  5072. queue_run = await db.scalar(
  5073. select(_PQI.id)
  5074. .where(_PQI.archive_id == existing_archive.id)
  5075. .where(_PQI.printer_id == printer_id)
  5076. .where(_PQI.status == "printing")
  5077. .limit(1)
  5078. )
  5079. looks_stale = queue_run is None
  5080. if looks_stale:
  5081. logger.warning(
  5082. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  5083. " — marking cancelled and creating new archive",
  5084. existing_archive.id,
  5085. archive_age,
  5086. live_progress,
  5087. existing_archive.subtask_id,
  5088. subtask_id,
  5089. )
  5090. existing_archive.status = "cancelled"
  5091. # Canonical key, not a sentence (issue #2974). "No status update
  5092. # received" is what both stale paths actually observed; which of
  5093. # the two it was is already carried by ``status`` -- cancelled
  5094. # here, the reconciled outcome at the reconnect site -- so one
  5095. # key loses no information and gives the Statistics breakdown a
  5096. # single bucket instead of two untranslatable prose strings.
  5097. existing_archive.failure_reason = "noStatusUpdate"
  5098. # And its run, as before runs were opened at the start: a new
  5099. # print starts on the printer, so whatever is open there ended
  5100. # unseen. Left open, the next reconnect would close it again.
  5101. from backend.app.services.print_log import discard_open_runs
  5102. discarded = await discard_open_runs(db, printer_id)
  5103. await db.commit()
  5104. await _announce_discarded_runs(discarded, printer_id)
  5105. # Its print keys go with it; the new archive registers its own.
  5106. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id and k[0] == printer_id]:
  5107. del _active_prints[_key]
  5108. # Fall through to create new archive (don't return)
  5109. else:
  5110. logger.info(
  5111. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  5112. )
  5113. # Track this as the active print
  5114. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  5115. _mark_owned_if_dispatched(existing_archive)
  5116. # Attach subtask_id retroactively so future restarts can resume.
  5117. # Compare for inequality (not "is empty") to also pick up reprint
  5118. # dispatches that mint a fresh id — see #1807 for the bogus
  5119. # "Print Stopped" the strict-empty guard caused on reconnect.
  5120. if subtask_id and existing_archive.subtask_id != subtask_id:
  5121. existing_archive.subtask_id = subtask_id
  5122. await db.commit()
  5123. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  5124. # Also set up energy tracking if not already tracked (#941: persisted column)
  5125. if await _run_needs_energy_start(existing_archive, printer_id, db):
  5126. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  5127. # Send notification with archive data (existing archive)
  5128. if not notification_sent:
  5129. archive_data = {
  5130. "print_time_seconds": _run_print_time_seconds(existing_archive, printer_id),
  5131. "created_by_id": existing_archive.created_by_id,
  5132. }
  5133. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5134. # Extract printable objects from the archived 3MF file
  5135. _load_objects_from_archive(existing_archive, printer_id, logger)
  5136. if existing_archive.file_path:
  5137. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  5138. return
  5139. # Build list of possible 3MF filenames to try
  5140. possible_names = []
  5141. # Bambu printers typically store files as "Name.gcode.3mf"
  5142. # The subtask_name is usually the best source for the filename
  5143. if subtask_name:
  5144. if _subtask_is_the_file(subtask_name, filename):
  5145. # A print started from the printer's own screen reports the
  5146. # file's full name, extension included. That is the file, so
  5147. # no extension is appended to it (#3009).
  5148. possible_names.append(subtask_name)
  5149. else:
  5150. # Try common Bambu naming patterns
  5151. possible_names.append(f"{subtask_name}.gcode.3mf")
  5152. possible_names.append(f"{subtask_name}.3mf")
  5153. # Try original filename with .3mf extension
  5154. if filename:
  5155. # Extract just the filename part, not the full path
  5156. fname = filename.split("/")[-1] if "/" in filename else filename
  5157. if fname.endswith(".3mf"):
  5158. possible_names.append(fname)
  5159. elif fname.endswith(".gcode"):
  5160. base = fname.rsplit(".", 1)[0]
  5161. possible_names.append(f"{base}.gcode.3mf")
  5162. possible_names.append(f"{base}.3mf")
  5163. else:
  5164. possible_names.append(f"{fname}.gcode.3mf")
  5165. possible_names.append(f"{fname}.3mf")
  5166. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  5167. space_variants = []
  5168. for name in possible_names:
  5169. if " " in name:
  5170. space_variants.append(name.replace(" ", "_"))
  5171. possible_names.extend(space_variants)
  5172. # Remove duplicates while preserving order
  5173. seen = set()
  5174. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  5175. logger.info("Trying filenames: %s", possible_names)
  5176. # Release the pooled DB connection before the 3MF FTP download. Reaching
  5177. # here means none of the expected-/existing-archive write branches ran
  5178. # (they all return earlier) — only SELECTs have executed on this path, so
  5179. # this commit persists nothing; it ends the read transaction so the
  5180. # connection returns to the pool during the download. That download tries
  5181. # up to five remote paths per candidate filename with retry/backoff and
  5182. # can run for minutes under FTP contention; holding the session across it
  5183. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  5184. # work runs during the download — the new-archive writes below re-acquire
  5185. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  5186. await db.commit()
  5187. # Try to find and download the 3MF file
  5188. temp_path = None
  5189. downloaded_filename = None
  5190. # Cache check: cover endpoint may have already pulled this 3MF during
  5191. # the print (frontend opens the card and shows the thumbnail) — reuse
  5192. # that file instead of re-downloading 36MB over the same FTP link that
  5193. # just served it (#972). The cache keys on a normalized filename so
  5194. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  5195. for try_filename in possible_names:
  5196. if not try_filename.endswith(".3mf"):
  5197. continue
  5198. cached = get_cached_3mf(printer_id, try_filename)
  5199. if cached:
  5200. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  5201. temp_path = cached
  5202. downloaded_filename = try_filename
  5203. break
  5204. # Does this printer keep the sliced file somewhere FTPS can reach? On
  5205. # H2-series and P2S the answer is routinely no — the file stays on
  5206. # internal eMMC and port 990 only ever serves external storage — and
  5207. # then the whole sweep below (six filenames x five directories x four
  5208. # retries, then the directory walk) is ~110 connections that cannot
  5209. # succeed. Skip it and say why (#2780).
  5210. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  5211. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  5212. # running rather than because the file is somewhere unreachable. The
  5213. # distinction is the whole of #2957: one is permanent, the other clears
  5214. # in minutes with the file still sitting on the printer.
  5215. blocked_by_ftps_cooloff = False
  5216. # Set when a probe reached the printer and still came back without the
  5217. # file -- a timeout mid-transfer, a refused connection, anything that is
  5218. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  5219. # caught by name below, so a file that genuinely is not on the card
  5220. # leaves this False and schedules nothing. Anything else means the
  5221. # transfer, not the file, is what failed, and that does not last (#3063).
  5222. ftp_transfer_failed = False
  5223. # The narrower case of the above: the directory walk *listed* a file
  5224. # for this print and could not fetch it, so the file is on the card
  5225. # under a name that matches. The only failure that rules out an
  5226. # earlier run's 3MF standing in for it (#3307).
  5227. walk_transfer_failed = False
  5228. # Paths the sweep reached and could not transfer -- a timeout, not a
  5229. # 550. The directory walk lists the same folders and would download
  5230. # the same file again: on a slow A1 that was a second 300 s on the
  5231. # printer's one FTPS slot, at print start, for a file the recovery
  5232. # retry fetches with a deadline twice as long (#3308).
  5233. sweep_failed_paths: set[str] = set()
  5234. # The print's name, for a fallback archive whose `subtask_name` the
  5235. # plate guard below had to disown. Display only, and deliberately kept
  5236. # apart from `subtask_name`: that variable is what every file lookup
  5237. # here is built from, and once a name has been shown to fetch another
  5238. # plate's 3MF it must not key `_active_prints` either, or the cover
  5239. # endpoint hands the same contradicted file to
  5240. # `_recover_fallback_archive` and fills the row in with it (#3126).
  5241. display_name_after_plate_reject: str | None = None
  5242. # Get FTP retry settings
  5243. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  5244. # ...but "the printer put it on eMMC" is where it went, not whether we
  5245. # can read it. An H2D with a card in mirrors the job to /cache and
  5246. # serves it happily, and skipping on the URL alone cost that reporter
  5247. # every archive for two days (#2856). So ask the printer instead of
  5248. # guessing: the dispatch named the exact file, which is one connection
  5249. # walking five paths rather than the sweep's ~110. Only when the probe
  5250. # comes back empty does the verdict's reason stand.
  5251. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  5252. if ftps_handshake_blocked(printer.ip_address):
  5253. # Deliberately NOT recorded as a cool-off give-up. This branch
  5254. # only runs on an unreachable verdict, and that verdict is the
  5255. # honest, permanent reason the archive is empty — the probe was
  5256. # a long shot on top of it. Blaming the cool-off here would
  5257. # schedule a retry for a file sitting on internal eMMC, which is
  5258. # the sweep #2780 removed (#2957).
  5259. logger.debug(
  5260. "Not probing for %s on printer %s: its file service is not answering over TLS",
  5261. storage.probe_filename,
  5262. printer_id,
  5263. )
  5264. else:
  5265. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  5266. probe_path.parent.mkdir(parents=True, exist_ok=True)
  5267. try:
  5268. probe_hit = await download_file_try_paths_async(
  5269. printer.ip_address,
  5270. printer.access_code,
  5271. ftp_probe_paths(storage.probe_filename),
  5272. probe_path,
  5273. socket_timeout=ftp_timeout,
  5274. printer_model=printer.model,
  5275. )
  5276. except Exception as e:
  5277. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  5278. probe_hit = False
  5279. if probe_hit:
  5280. downloaded_filename = storage.probe_filename
  5281. temp_path = probe_path
  5282. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  5283. # Naming the path, not just the file: a printer that keeps
  5284. # uploads around for weeks can serve a same-named copy of an
  5285. # earlier slice, and without the directory in the log that
  5286. # mismatch is invisible rather than merely rare (#1820).
  5287. logger.info(
  5288. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  5289. downloaded_filename,
  5290. probe_hit,
  5291. printer_id,
  5292. storage.reason,
  5293. )
  5294. if not storage.reachable and not downloaded_filename:
  5295. # Same opening words whether or not a probe ran, because that is
  5296. # the phrase support asks people to grep for — only the tail says
  5297. # which of the two happened.
  5298. logger.info(
  5299. "Skipping the 3MF lookup for printer %s: %s — %s",
  5300. printer_id,
  5301. storage.reason,
  5302. "no copy of it on external storage either"
  5303. if storage.probe_filename
  5304. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  5305. )
  5306. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  5307. if not try_filename.endswith(".3mf"):
  5308. continue
  5309. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  5310. # printers, so try it first — deferring it to last cost #972's reporter
  5311. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  5312. # landing on the path that actually had the file.
  5313. remote_paths = [
  5314. f"/{try_filename}",
  5315. f"/cache/{try_filename}",
  5316. f"/model/{try_filename}",
  5317. f"/data/{try_filename}",
  5318. f"/data/Metadata/{try_filename}",
  5319. ]
  5320. temp_path = app_settings.archive_dir / "temp" / try_filename
  5321. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5322. for remote_path in remote_paths:
  5323. if ftps_handshake_blocked(printer.ip_address):
  5324. # The printer's FTPS service is not completing a TLS
  5325. # handshake, so it has no path we could reach — walking the
  5326. # remaining candidates only re-runs the same failure
  5327. # (#2780). Fall through to the no-3MF archive now.
  5328. #
  5329. # Remember *why*, though. This is the one give-up that is
  5330. # temporary: the cool-off clears in minutes and the file was
  5331. # on the printer the whole time. The fallback archive is
  5332. # stamped with it so a retry can be scheduled, and so the
  5333. # Archives banner stops blaming storage (#2957).
  5334. blocked_by_ftps_cooloff = True
  5335. logger.warning(
  5336. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  5337. printer_id,
  5338. )
  5339. break
  5340. logger.debug("Trying FTP download: %s", remote_path)
  5341. try:
  5342. if ftp_retry_enabled:
  5343. downloaded = await with_ftp_retry(
  5344. download_file_async,
  5345. printer.ip_address,
  5346. printer.access_code,
  5347. remote_path,
  5348. temp_path,
  5349. timeout=ftp_timeout,
  5350. socket_timeout=ftp_timeout,
  5351. printer_model=printer.model,
  5352. max_retries=ftp_retry_count,
  5353. retry_delay=ftp_retry_delay,
  5354. operation_name=f"Download 3MF from {remote_path}",
  5355. cooloff_ip=printer.ip_address,
  5356. non_retry_exceptions=(FileNotOnPrinterError,),
  5357. )
  5358. else:
  5359. downloaded = await download_file_async(
  5360. printer.ip_address,
  5361. printer.access_code,
  5362. remote_path,
  5363. temp_path,
  5364. timeout=ftp_timeout,
  5365. socket_timeout=ftp_timeout,
  5366. printer_model=printer.model,
  5367. )
  5368. if downloaded:
  5369. downloaded_filename = try_filename
  5370. logger.info("Downloaded: %s", remote_path)
  5371. # Populate shared cache so the cover endpoint (if it
  5372. # runs next) doesn't refetch the same 36MB over FTP.
  5373. cache_3mf_download(printer_id, try_filename, temp_path)
  5374. break
  5375. # with_ftp_retry returns None once it has spent its budget,
  5376. # and download_file_async returns False on a timeout, so an
  5377. # exhausted transfer arrives here rather than as an
  5378. # exception (#3063).
  5379. ftp_transfer_failed = True
  5380. sweep_failed_paths.add(remote_path)
  5381. except FileNotOnPrinterError:
  5382. # 550 — file isn't at this path. Advance to next candidate
  5383. # without burning the retry budget.
  5384. logger.debug("3MF not at %s (550), trying next path", remote_path)
  5385. except Exception as e:
  5386. ftp_transfer_failed = True
  5387. sweep_failed_paths.add(remote_path)
  5388. logger.debug("FTP download failed for %s: %s", remote_path, e)
  5389. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  5390. break
  5391. # If still not found, try listing directories to find matching file
  5392. # Different printer models use different directory structures. Skipped
  5393. # when the printer's FTPS handshake is failing — the directory walk is
  5394. # five more connections that cannot get further than the download did.
  5395. if (
  5396. not downloaded_filename
  5397. and storage.reachable
  5398. and (filename or subtask_name)
  5399. and not ftps_handshake_blocked(printer.ip_address)
  5400. ):
  5401. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  5402. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  5403. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  5404. # Every folder is listed before one file is picked, so a file named
  5405. # for the print in a later folder wins over one that merely
  5406. # contains the name in an earlier folder.
  5407. listed_paths: list[str] = []
  5408. for search_dir in search_dirs:
  5409. try:
  5410. dir_files = await list_files_async(
  5411. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  5412. )
  5413. except Exception as e:
  5414. logger.debug("Failed to list %s: %s", search_dir, e)
  5415. continue
  5416. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  5417. if threemf_files:
  5418. logger.info(
  5419. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  5420. )
  5421. listed_paths += [
  5422. posixpath.join(search_dir, f.get("name", "")) for f in dir_files if not f.get("is_directory")
  5423. ]
  5424. for remote_full_path in _3mf_files_for_print(listed_paths, search_term):
  5425. if remote_full_path in sweep_failed_paths:
  5426. # Listed for this print, and its transfer already failed:
  5427. # the same as a failed walk download, without spending a
  5428. # second deadline on it. Skipping it cannot hand the walk a
  5429. # look-alike: while a file of the print's own name is
  5430. # listed, files that merely contain the name are not.
  5431. logger.info(
  5432. "Not downloading %s again: its transfer already failed; the recovery retry will fetch it",
  5433. remote_full_path,
  5434. )
  5435. walk_transfer_failed = True
  5436. continue
  5437. fname = posixpath.basename(remote_full_path)
  5438. logger.info("Found matching file: %s", remote_full_path)
  5439. temp_path = app_settings.archive_dir / "temp" / fname
  5440. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5441. try:
  5442. if ftp_retry_enabled:
  5443. downloaded = await with_ftp_retry(
  5444. download_file_async,
  5445. printer.ip_address,
  5446. printer.access_code,
  5447. remote_full_path,
  5448. temp_path,
  5449. timeout=ftp_timeout,
  5450. socket_timeout=ftp_timeout,
  5451. printer_model=printer.model,
  5452. max_retries=ftp_retry_count,
  5453. retry_delay=ftp_retry_delay,
  5454. operation_name=f"Download 3MF from {remote_full_path}",
  5455. cooloff_ip=printer.ip_address,
  5456. )
  5457. else:
  5458. downloaded = await download_file_async(
  5459. printer.ip_address,
  5460. printer.access_code,
  5461. remote_full_path,
  5462. temp_path,
  5463. timeout=ftp_timeout,
  5464. socket_timeout=ftp_timeout,
  5465. printer_model=printer.model,
  5466. )
  5467. except Exception as e:
  5468. logger.debug("Failed to download %s: %s", remote_full_path, e)
  5469. continue
  5470. if downloaded:
  5471. downloaded_filename = fname
  5472. logger.info("Found and downloaded: %s", remote_full_path)
  5473. cache_3mf_download(printer_id, fname, temp_path)
  5474. break
  5475. # The listing named the file, so it is on the card;
  5476. # only the transfer failed (#3063).
  5477. ftp_transfer_failed = True
  5478. walk_transfer_failed = True
  5479. # A "Print again" on the printer's screen names no file Bambuddy can
  5480. # find: only its history copy under a generic name, and the 3MF's
  5481. # internal title (#3307). When an earlier run of the same job was
  5482. # archived, its 3MF is the one being printed again. Not when the
  5483. # directory walk listed a file for this print and only its transfer
  5484. # failed: that file is on the card, and the retry fetches it. A
  5485. # cool-off or a failed sweep path is no such evidence -- the retry
  5486. # tries the same names, which this print's file never had.
  5487. reused_3mf_from: int | None = None
  5488. if not downloaded_filename and not walk_transfer_failed:
  5489. reported_layers = raw_mqtt.get("total_layer_num")
  5490. earlier = await _archived_3mf_for_repeat(
  5491. db,
  5492. printer_id,
  5493. subtask_name,
  5494. filename,
  5495. reported_layers if isinstance(reported_layers, int) and reported_layers > 0 else None,
  5496. )
  5497. if earlier is not None:
  5498. reuse_name = Path(earlier.filename or "").name or f"archive_{earlier.id}.3mf"
  5499. # Per printer: two printers reprinting the same job at once
  5500. # must not write one temp file (archive_print names the
  5501. # archive after original_filename, not this path).
  5502. reuse_path = app_settings.archive_dir / "temp" / f"reprint_{printer_id}_{reuse_name}"
  5503. try:
  5504. reuse_path.parent.mkdir(parents=True, exist_ok=True)
  5505. await asyncio.to_thread(shutil.copyfile, app_settings.base_dir / earlier.file_path, reuse_path)
  5506. except OSError as e:
  5507. # A copy that fails leaves the print the fallback archive
  5508. # it would have had, not no archive at all.
  5509. logger.warning("Could not copy the 3MF of archive %s for printer %s: %s", earlier.id, printer_id, e)
  5510. else:
  5511. temp_path = reuse_path
  5512. downloaded_filename = reuse_name
  5513. reused_3mf_from = earlier.id
  5514. cache_3mf_download(printer_id, reuse_name, temp_path)
  5515. logger.info(
  5516. "No 3MF on printer %s for %s (%s); using the 3MF of archive %s, an earlier run of the same job",
  5517. printer_id,
  5518. subtask_name,
  5519. filename,
  5520. earlier.id,
  5521. )
  5522. # Validate the downloaded 3MF actually matches the plate that's running
  5523. # (#1204): subtask_name lags across consecutive plates of the same model,
  5524. # so the first FTP candidate (built from subtask_name) can land on the
  5525. # previous plate's still-resident upload. Cross-check the slice_info
  5526. # plate index against the plate parsed from gcode_file (always fresh —
  5527. # it's the field whose change triggered this callback).
  5528. if downloaded_filename and temp_path:
  5529. expected_plate = parse_plate_id(filename)
  5530. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  5531. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  5532. logger.warning(
  5533. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  5534. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  5535. downloaded_filename,
  5536. actual_plate,
  5537. expected_plate,
  5538. subtask_name,
  5539. )
  5540. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  5541. retry_succeeded = False
  5542. if corrected_subtask and corrected_subtask != subtask_name:
  5543. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  5544. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  5545. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  5546. for remote_path in (
  5547. f"/{try_filename}",
  5548. f"/cache/{try_filename}",
  5549. f"/model/{try_filename}",
  5550. f"/data/{try_filename}",
  5551. f"/data/Metadata/{try_filename}",
  5552. ):
  5553. try:
  5554. if ftp_retry_enabled:
  5555. downloaded = await with_ftp_retry(
  5556. download_file_async,
  5557. printer.ip_address,
  5558. printer.access_code,
  5559. remote_path,
  5560. retry_temp_path,
  5561. timeout=ftp_timeout,
  5562. socket_timeout=ftp_timeout,
  5563. printer_model=printer.model,
  5564. max_retries=ftp_retry_count,
  5565. retry_delay=ftp_retry_delay,
  5566. operation_name=f"Re-download 3MF from {remote_path}",
  5567. cooloff_ip=printer.ip_address,
  5568. non_retry_exceptions=(FileNotOnPrinterError,),
  5569. )
  5570. else:
  5571. downloaded = await download_file_async(
  5572. printer.ip_address,
  5573. printer.access_code,
  5574. remote_path,
  5575. retry_temp_path,
  5576. timeout=ftp_timeout,
  5577. socket_timeout=ftp_timeout,
  5578. printer_model=printer.model,
  5579. )
  5580. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  5581. logger.info(
  5582. "[CALLBACK] Re-download succeeded with corrected name %s "
  5583. "(plate %s) — replacing wrong file",
  5584. try_filename,
  5585. expected_plate,
  5586. )
  5587. try:
  5588. temp_path.unlink(missing_ok=True)
  5589. except OSError:
  5590. pass
  5591. temp_path = retry_temp_path
  5592. downloaded_filename = try_filename
  5593. subtask_name = corrected_subtask
  5594. cache_3mf_download(printer_id, try_filename, temp_path)
  5595. retry_succeeded = True
  5596. break
  5597. elif downloaded:
  5598. # Wrong plate again — discard and keep trying
  5599. try:
  5600. retry_temp_path.unlink(missing_ok=True)
  5601. except OSError:
  5602. pass
  5603. except FileNotOnPrinterError:
  5604. continue
  5605. except Exception as e:
  5606. logger.debug("Re-download failed for %s: %s", remote_path, e)
  5607. if retry_succeeded:
  5608. break
  5609. # If the retry didn't find a matching file, drop the wrong 3MF
  5610. # so the no-3MF fallback below creates an archive whose name
  5611. # at least reflects the right plate.
  5612. if not retry_succeeded:
  5613. logger.warning(
  5614. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  5615. expected_plate,
  5616. )
  5617. try:
  5618. temp_path.unlink(missing_ok=True)
  5619. except OSError:
  5620. pass
  5621. temp_path = None
  5622. downloaded_filename = None
  5623. # Whatever the sweep's transport did earlier, it is not why
  5624. # this archive ends up empty: a 3MF downloaded fine, it was
  5625. # just the wrong plate. Retrying would re-fetch that same
  5626. # contradicted file under the same stale names and hand it
  5627. # to _recover_fallback_archive, which checks that a
  5628. # candidate is a readable 3MF but not which plate it is --
  5629. # so the row would be filled in with another plate's
  5630. # filament and cost, the exact swap #2957 removed (#3063).
  5631. ftp_transfer_failed = False
  5632. # Disown the name for *lookups*: it has just been shown to
  5633. # fetch another plate's 3MF, and it keys `_active_prints`
  5634. # below, where the cover endpoint's own download of that
  5635. # same name would find this archive and fill it in with the
  5636. # file we are discarding here.
  5637. #
  5638. # Keep it for the *title*, which is a separate question.
  5639. # ``swap_plate_suffix`` returns None both for a name that
  5640. # carries no "- Plate N" / "_plate_N" suffix and for no
  5641. # name at all, and those are not the same situation: a name
  5642. # without a suffix holds no stale plate number to be wrong
  5643. # about. Blanking both uses at once dropped the project
  5644. # name too, and the row fell through to the gcode_file path
  5645. # titled "plate_1" though the real name was in hand.
  5646. # #1204's own premise is consecutive plates *of the same
  5647. # model*, so the project part is right either way (#3126).
  5648. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  5649. subtask_name = corrected_subtask or ""
  5650. # Deleted while the 3MF was being fetched (that can take minutes): no
  5651. # archive, timelapse or tracking for a printer that will never report
  5652. # the print's end. forget_printer again: the download registered its
  5653. # 3MF cache entry after the delete cleared the id. (A delete committing
  5654. # while the archive is written is caught after its commit.)
  5655. if await _printer_gone(db, printer_id):
  5656. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  5657. await forget_printer(printer_id)
  5658. return
  5659. if not downloaded_filename or not temp_path:
  5660. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  5661. # Create a fallback archive without 3MF data so the print is still tracked
  5662. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  5663. try:
  5664. from backend.app.models.archive import PrintArchive
  5665. # Why the card is empty. The two temporary causes outrank the
  5666. # storage verdict because they say the sweep never got a fair
  5667. # answer: a cool-off skipped it at the transport, and a failed
  5668. # transfer reached the printer but never finished. Either way
  5669. # the file is still on the card, so reporting where the printer
  5670. # files its jobs would describe a setting that is not the
  5671. # problem (#2957, #3063).
  5672. if blocked_by_ftps_cooloff:
  5673. no_3mf_reason = REASON_FTPS_COOLOFF
  5674. elif storage.reachable and ftp_transfer_failed:
  5675. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5676. else:
  5677. no_3mf_reason = storage.reason
  5678. # Derive print name from subtask_name or filename. The
  5679. # plate guard's disowned name comes second: it is a real name
  5680. # for a real print, and only the gcode_file path is left
  5681. # otherwise -- which titles the row "plate_1" (#3126).
  5682. print_name = subtask_name or display_name_after_plate_reject or filename
  5683. if print_name:
  5684. # Clean up the name (remove extensions, path parts)
  5685. print_name = print_name.split("/")[-1]
  5686. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5687. else:
  5688. print_name = "Unknown Print"
  5689. # Recover estimated print time from MQTT (best-effort for notifications)
  5690. fallback_print_time = None
  5691. mqtt_remaining = data.get("remaining_time")
  5692. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5693. fallback_print_time = int(mqtt_remaining)
  5694. if fallback_print_time is None:
  5695. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5696. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5697. fallback_print_time = int(mc_remaining * 60)
  5698. # Best-effort filament metadata from MQTT — see
  5699. # _extract_filament_data_from_mqtt. Without this the fallback
  5700. # archive's filament fields stayed NULL even though the AMS
  5701. # state at print start was sitting right there in `data`.
  5702. # The slicer's ams_mapping (when present) narrows the result
  5703. # to slots actually used by the print (#1533).
  5704. mqtt_filament_meta = _extract_filament_data_from_mqtt(
  5705. data, _get_start_ams_mapping(data, printer_id, None)
  5706. )
  5707. # Create minimal archive entry
  5708. fallback_archive = PrintArchive(
  5709. printer_id=printer_id,
  5710. filename=filename or f"{print_name}.3mf",
  5711. file_path="", # Empty - no 3MF file available
  5712. file_size=0,
  5713. print_name=print_name,
  5714. print_time_seconds=fallback_print_time,
  5715. status="printing",
  5716. started_at=detected_at,
  5717. subtask_id=subtask_id,
  5718. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5719. filament_type=mqtt_filament_meta.get("filament_type"),
  5720. filament_color=mqtt_filament_meta.get("filament_color"),
  5721. extra_data={
  5722. "no_3mf_available": True,
  5723. # Why the card is empty, when we know -- see above. The
  5724. # banner reads this to stop telling H2/P2 owners to
  5725. # switch on a setting that is already on and would not
  5726. # have helped (#2780).
  5727. "no_3mf_reason": no_3mf_reason,
  5728. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5729. "_print_data": data,
  5730. },
  5731. )
  5732. db.add(fallback_archive)
  5733. try:
  5734. await db.commit()
  5735. except IntegrityError:
  5736. # Not "Failed to create fallback archive" below, and no
  5737. # start notification for a printer that is gone.
  5738. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5739. return
  5740. raise
  5741. await db.refresh(fallback_archive)
  5742. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5743. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5744. return
  5745. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5746. # Track as active print
  5747. _bind_active_print(printer_id, fallback_archive.id, fallback_archive.filename, filename, subtask_name)
  5748. await _open_run_for(fallback_archive.id, printer_id, subtask_id)
  5749. # Record starting energy if smart plug available (#941: persisted column)
  5750. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5751. # Send WebSocket notification
  5752. await ws_manager.send_archive_created(
  5753. {
  5754. "id": fallback_archive.id,
  5755. "printer_id": fallback_archive.printer_id,
  5756. "filename": fallback_archive.filename,
  5757. "print_name": fallback_archive.print_name,
  5758. "status": fallback_archive.status,
  5759. }
  5760. )
  5761. # MQTT relay - publish archive created
  5762. try:
  5763. await mqtt_relay.on_archive_created(
  5764. archive_id=fallback_archive.id,
  5765. print_name=fallback_archive.print_name,
  5766. printer_name=printer.name,
  5767. status=fallback_archive.status,
  5768. )
  5769. except Exception:
  5770. pass # Don't fail if MQTT fails
  5771. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5772. try:
  5773. await _store_spoolman_print_data(
  5774. printer_id,
  5775. fallback_archive.id,
  5776. fallback_archive.file_path,
  5777. db,
  5778. printer_manager,
  5779. ams_mapping=_get_start_ams_mapping(data, printer_id, fallback_archive.id),
  5780. plate_id=_get_start_plate_id(printer_id, fallback_archive.id),
  5781. )
  5782. except Exception as e:
  5783. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5784. # Both temporary give-ups are worth coming back for, and for
  5785. # the same reason: the file is on the printer and the last look
  5786. # failed at the transport rather than finding nothing. One waits
  5787. # out the handshake block (#2957), the other waits for the
  5788. # printer to stop being busy (#3063). Deliberately not scheduled
  5789. # for a storage verdict: a file on internal eMMC will not appear
  5790. # at any FTPS path however long we wait, and retrying it is
  5791. # exactly the sweep #2780 removed.
  5792. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5793. # `possible_names`, not the raw MQTT strings: it is the exact
  5794. # list this flow just tried, already stripped of any path
  5795. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5796. # some firmware) and deduped.
  5797. _schedule_fallback_3mf_retry(
  5798. printer_id=printer_id,
  5799. archive_id=fallback_archive.id,
  5800. filenames=list(possible_names),
  5801. reason=no_3mf_reason,
  5802. )
  5803. # Send notification without archive data (file not found)
  5804. if not notification_sent:
  5805. await _send_print_start_notification(printer_id, data, logger=logger)
  5806. # The same baseline the other two on_print_start branches take
  5807. # (#2704), and last for the same reason they are: it lists the
  5808. # printer's timelapse directory, so a slow card must not delay
  5809. # the _active_prints registration, the energy reading, the
  5810. # archive-created event or the start notification above it.
  5811. #
  5812. # This branch never took one, so every no-3MF archive reached
  5813. # completion with no baseline in memory and none on the row, and
  5814. # the completion scan fell into its "snapshot now" fallback --
  5815. # which runs after the printer has written the video, so the new
  5816. # file landed inside the baseline and no diff ever matched
  5817. # (#2957 follow-up).
  5818. #
  5819. # Skipped when the FTPS cool-off is what produced this fallback:
  5820. # the listing needs the same connection that just failed, so it
  5821. # could only record that the card was unreadable. The scan
  5822. # handles that case by refusing to choose between candidates.
  5823. if not blocked_by_ftps_cooloff:
  5824. await _capture_timelapse_baseline_at_start(
  5825. printer, printer_id, logger, archive_id=fallback_archive.id
  5826. )
  5827. await _forget_if_printer_gone(printer_id)
  5828. return
  5829. except Exception as e:
  5830. logger.error("Failed to create fallback archive: %s", e)
  5831. # Send notification without archive data (file not found)
  5832. if not notification_sent:
  5833. await _send_print_start_notification(printer_id, data, logger=logger)
  5834. return
  5835. try:
  5836. # Archive the file with status "printing"
  5837. service = ArchiveService(db)
  5838. try:
  5839. archive = await service.archive_print(
  5840. printer_id=printer_id,
  5841. source_file=temp_path,
  5842. print_data={
  5843. **data,
  5844. "status": "printing",
  5845. # Where the 3MF came from when the printer had none to
  5846. # give (#3307), for whoever reads this archive later.
  5847. **({"_3mf_from_archive": reused_3mf_from} if reused_3mf_from is not None else {}),
  5848. },
  5849. subtask_id=subtask_id,
  5850. started_at=detected_at,
  5851. # The reused copy's temp name carries the printer id; a
  5852. # download's is the file's own name, as before.
  5853. original_filename=downloaded_filename if reused_3mf_from is not None else None,
  5854. )
  5855. except IntegrityError:
  5856. # archive_print removed the folder it had copied the 3MF into.
  5857. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5858. return
  5859. raise
  5860. if archive:
  5861. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5862. # Set on the row rather than passed to archive_print, which also
  5863. # serves the queue dispatcher — there the queue item decides.
  5864. # Guarded because this branch has no ``except``: an unhandled
  5865. # write error would take the _active_prints registration, the
  5866. # start notification, the energy reading and the timelapse
  5867. # baseline below it with it, and a missing prompt is by far the
  5868. # cheaper failure.
  5869. archive_id = archive.id
  5870. try:
  5871. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5872. archive.confirm_requested = True
  5873. await db.commit()
  5874. except Exception as e:
  5875. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5876. # The rollback expires every loaded object, and on an async
  5877. # session reading one afterwards raises instead of
  5878. # reloading, so the two this branch goes on to use are
  5879. # fetched again. The archive itself was committed by
  5880. # archive_print; only the flag is lost.
  5881. try:
  5882. await db.rollback()
  5883. archive = await db.get(PrintArchive, archive_id)
  5884. printer = await db.get(Printer, printer_id)
  5885. except Exception as reload_error:
  5886. logger.warning(
  5887. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5888. )
  5889. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5890. return
  5891. # Track this active print (use both original filename and downloaded filename)
  5892. _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
  5893. await _open_run_for(archive_id, printer_id, subtask_id)
  5894. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5895. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5896. # Record starting energy from smart plug if available (#941: persisted column)
  5897. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5898. await ws_manager.send_archive_created(
  5899. {
  5900. "id": archive.id,
  5901. "printer_id": archive.printer_id,
  5902. "filename": archive.filename,
  5903. "print_name": archive.print_name,
  5904. "status": archive.status,
  5905. }
  5906. )
  5907. # MQTT relay - publish archive created
  5908. try:
  5909. await mqtt_relay.on_archive_created(
  5910. archive_id=archive.id,
  5911. print_name=archive.print_name,
  5912. printer_name=printer.name,
  5913. status=archive.status,
  5914. )
  5915. except Exception:
  5916. pass # Don't fail if MQTT fails
  5917. # Send notification with archive data (new archive created)
  5918. if not notification_sent:
  5919. archive_data = {
  5920. "print_time_seconds": _run_print_time_seconds(archive, printer_id),
  5921. "created_by_id": archive.created_by_id,
  5922. }
  5923. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5924. # Extract printable objects for skip object functionality
  5925. try:
  5926. from backend.app.services.archive import extract_printable_objects_from_3mf
  5927. client = printer_manager.get_client(printer_id)
  5928. if client:
  5929. with open(temp_path, "rb") as f:
  5930. threemf_data = f.read()
  5931. # Extract with positions for UI overlay, scoped to the
  5932. # plate that is printing — an all-plates 3MF carries
  5933. # every plate's objects (#2522).
  5934. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5935. threemf_data,
  5936. plate_number=resolve_plate_id(client.state),
  5937. include_positions=True,
  5938. )
  5939. if printable_objects:
  5940. # Store objects in printer state
  5941. client.state.printable_objects = printable_objects
  5942. client.state.printable_objects_bbox_all = bbox_all
  5943. client.state.skipped_objects = [] # Reset skipped objects for new print
  5944. logger.info(
  5945. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5946. )
  5947. except Exception as e:
  5948. logger.debug("Failed to extract printable objects: %s", e)
  5949. # From the archived copy: the downloaded one may be removed
  5950. # below while the pauses are still being read.
  5951. if archive is not None and archive.file_path:
  5952. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  5953. # Store Spoolman tracking data for per-filament usage reporting
  5954. try:
  5955. await _store_spoolman_print_data(
  5956. printer_id,
  5957. archive.id,
  5958. archive.file_path,
  5959. db,
  5960. printer_manager,
  5961. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5962. plate_id=_get_start_plate_id(printer_id, archive_id),
  5963. )
  5964. except Exception as e:
  5965. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5966. # Price the print from its spools now rather than only at completion (#3261)
  5967. _schedule_archive_cost_estimate(
  5968. printer_id,
  5969. archive.id,
  5970. printer_manager,
  5971. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5972. plate_id=_get_start_plate_id(printer_id, archive_id),
  5973. session_factory=async_session,
  5974. )
  5975. # Capture timelapse file baseline for snapshot-diff on completion
  5976. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5977. await _forget_if_printer_gone(printer_id)
  5978. finally:
  5979. # Keep temp_path around until print completes so the cover endpoint
  5980. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5981. # the file. If the cache entry was evicted early (file vanished),
  5982. # clean up any stragglers here to avoid leaking disk on retries.
  5983. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5984. if temp_path and temp_path.exists() and cached_now != temp_path:
  5985. temp_path.unlink()
  5986. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5987. _TIMELAPSE_DIRECTORIES = ("/timelapse", "/timelapse/video", "/record", "/recording")
  5988. # A baseline that could not be read at print start is read again on this
  5989. # schedule while the print runs (#3412). The printer writes the video only once
  5990. # the print has ended, so a reading taken mid-print is as good as one taken at
  5991. # the start. The interval is shorter than the FTPS handshake cool-off (300 s),
  5992. # which is what usually makes the card unreadable, so the first reading after
  5993. # it ends is not long behind; while the cool-off runs a round costs nothing, as
  5994. # no connection is opened. The cap bounds a print that never reports an end.
  5995. _TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS = 120.0
  5996. _TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS = 720
  5997. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5998. # tests can shrink them without waiting out real delays.
  5999. #
  6000. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  6001. # looking. Across 247 support bundles the attempt that found the video was #1
  6002. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  6003. # decaying one, which is the signature of a budget that expires while files are
  6004. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  6005. # prints make big videos and the printer writes them after the print ends, so
  6006. # the poll now runs for minutes and costs one FTP LIST per round.
  6007. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  6008. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  6009. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  6010. def _timelapse_scan_max_attempts() -> int:
  6011. """Round cap for the poll, derived from the wall-clock budget.
  6012. The deadline alone is not a sufficient bound: it assumes each round really
  6013. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  6014. and an FTP list that fails immediately would otherwise spin against the
  6015. printer at full speed for the whole window. Whichever bound is reached
  6016. first ends the poll.
  6017. """
  6018. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  6019. # A zero interval makes the wall-clock budget meaningless; fall back to
  6020. # the round count the production interval would have given.
  6021. return 32
  6022. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  6023. async def _read_timelapse_baseline(printer) -> tuple[set[str], bool]:
  6024. """The video names on *printer*'s card, and whether the card was read.
  6025. ``_list_timelapse_videos`` answers ``[]`` when its connect fails rather
  6026. than raising, so a card behind the FTPS handshake cool-off, or one whose
  6027. listing timed out, is indistinguishable from one holding no videos.
  6028. Everywhere that only wants to know "is there a video yet" the difference
  6029. does not matter -- both mean "not yet, retry".
  6030. It matters where an empty listing is recorded as a *baseline*. Recording
  6031. "the card held nothing" for a card that was never read means every video on
  6032. it counts as new, and the completion scan then attaches a stale video to
  6033. this print and deletes it from the printer (#2957 follow-up, #3412). So an
  6034. empty listing is asked again here in a way that tells the two apart: the
  6035. card counts as read only when every directory walked answered, with a
  6036. listing or with "no such directory". One that failed may be the one
  6037. holding the videos.
  6038. """
  6039. from backend.app.services.bambu_ftp import ftps_handshake_blocked, list_files_result_async
  6040. files, _ = await _list_timelapse_videos(printer)
  6041. if files:
  6042. return {f.get("name", "") for f in files}, True
  6043. ip_address = getattr(printer, "ip_address", None)
  6044. printer_id = getattr(printer, "id", None)
  6045. if not ip_address:
  6046. return set(), True
  6047. # No card in the slot: nothing to read, and nothing a video could land on.
  6048. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  6049. return set(), True
  6050. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  6051. if ftps_handshake_blocked(ip_address):
  6052. # Below any path: every remaining one would fail the same way.
  6053. return set(), False
  6054. listing = await list_files_result_async(
  6055. ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  6056. )
  6057. if not (listing.available or listing.missing):
  6058. return set(), False
  6059. videos = [
  6060. f
  6061. for f in listing.files
  6062. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  6063. ]
  6064. if videos:
  6065. return {f.get("name", "") for f in videos}, True
  6066. return set(), True
  6067. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  6068. """List video files from printer's timelapse directory.
  6069. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  6070. Returns (video_files, found_path) where video_files is a list of file dicts
  6071. and found_path is the directory where they were found, or ([], None).
  6072. An empty return does not distinguish "no videos" from "could not read the
  6073. card" — see :func:`_read_timelapse_baseline`, which the two baseline
  6074. callers use instead.
  6075. """
  6076. from backend.app.services.bambu_ftp import list_files_async
  6077. logger = logging.getLogger(__name__)
  6078. # No card in the slot means no /timelapse to walk — four connections that
  6079. # can only fail, on a path whose failures are swallowed and so would go on
  6080. # costing time silently forever (#2780).
  6081. #
  6082. # ``getattr`` rather than ``printer.id``: every dereference below happens
  6083. # inside the loop's own try/except, so a caller that passed something
  6084. # unexpected used to get an empty listing rather than an exception. Keep
  6085. # that, instead of making this gate the first thing that can raise here.
  6086. printer_id = getattr(printer, "id", None)
  6087. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  6088. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  6089. return [], None
  6090. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  6091. try:
  6092. found_files = await list_files_async(
  6093. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  6094. )
  6095. if found_files:
  6096. video_files = [
  6097. f
  6098. for f in found_files
  6099. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  6100. ]
  6101. if video_files:
  6102. return video_files, timelapse_path
  6103. except Exception as e:
  6104. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  6105. continue
  6106. return [], None
  6107. async def _capture_timelapse_baseline_at_start(
  6108. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  6109. ) -> None:
  6110. """Snapshot the printer's timelapse directory at print start so the
  6111. completion-time scan can pick the new file by set-difference.
  6112. Must be called from every on_print_start path that proceeds to a real
  6113. print — both the new-archive branch and the expected-archive branch (which
  6114. queue / VP-dispatched prints take). Without a baseline,
  6115. _scan_for_timelapse_with_retries falls into its "take baseline now"
  6116. fallback that runs AFTER the new MP4 has already landed on the SD card,
  6117. so the new file ends up in the "baseline" set and no diff ever matches.
  6118. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  6119. unreliable — the snapshot-diff approach sidesteps that entirely.
  6120. When ``archive_id`` is known the baseline is also written to the archive
  6121. row, so it survives a restart and the manual "Scan for Timelapse" button
  6122. can run the same diff instead of falling back to clock-based matching
  6123. (#2704). Only baselines taken at print start are persisted — one taken at
  6124. completion already contains the new video and would poison a later scan.
  6125. """
  6126. names: set[str] | None = None
  6127. unread = False
  6128. _timelapse_baselines_unread.discard(printer_id)
  6129. try:
  6130. names, read = await _read_timelapse_baseline(printer)
  6131. unread = not read
  6132. _timelapse_baselines[printer_id] = names
  6133. if unread:
  6134. # Recorded anyway, deliberately, and marked. An empty baseline taken
  6135. # off a card we could not read is not evidence, but it is still the
  6136. # right *default*: Bambuddy deletes each video from the printer once
  6137. # it is attached, so the usual card holds exactly one video at
  6138. # completion and an empty baseline resolves it. Persisting NULL
  6139. # instead would send completion to take its own snapshot, by which
  6140. # point this print's video is on the card and would be swallowed by
  6141. # it. The mark keeps the scan from choosing between several videos
  6142. # (#3412), and the card is read again while the print runs.
  6143. _timelapse_baselines_unread.add(printer_id)
  6144. logger.warning(
  6145. "[TIMELAPSE] Baseline for printer %s taken while its card could not be read — "
  6146. "treating it as empty for now and reading it again during the print",
  6147. printer_id,
  6148. )
  6149. logger.info(
  6150. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  6151. len(names),
  6152. printer_id,
  6153. )
  6154. except Exception as e:
  6155. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  6156. run_started_at: datetime | None = None
  6157. run_id: int | None = None
  6158. if archive_id is not None:
  6159. try:
  6160. async with async_session() as db:
  6161. from backend.app.models.archive import PrintArchive
  6162. from backend.app.services.print_log import open_run_on_printer
  6163. archive = await db.get(PrintArchive, archive_id)
  6164. if archive is not None:
  6165. # Written even when the listing failed, and then as NULL. A
  6166. # reprint reuses the archive row, so leaving the previous
  6167. # run's baseline in place would have the scan diff this print
  6168. # against the state of the printer before the *last* one —
  6169. # and a stale baseline reads as authoritative, where NULL
  6170. # correctly falls back to a fresh snapshot.
  6171. baseline = sorted(names) if names is not None else None
  6172. archive.timelapse_baseline = baseline
  6173. archive.timelapse_baseline_unread = unread
  6174. run_started_at = archive.started_at
  6175. # And on the run this print opened, whose scan reads it:
  6176. # the archive's is its latest start's, which another plate
  6177. # of it on another printer can take over.
  6178. run = await open_run_on_printer(db, printer_id)
  6179. if run is not None and run.archive_id == archive_id:
  6180. run.timelapse_baseline = baseline
  6181. run.timelapse_baseline_unread = unread
  6182. run_id = run.id
  6183. await db.commit()
  6184. except Exception as e:
  6185. # In-memory baseline still covers the normal completion path.
  6186. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  6187. if unread and names is not None:
  6188. spawn_background_task(
  6189. _reread_unread_timelapse_baseline(printer_id, names, archive_id, run_started_at, run_id),
  6190. name=f"reread-timelapse-baseline-{printer_id}",
  6191. )
  6192. # Before the print has ended there is no video yet: a long PREPARE (heating,
  6193. # levelling) counts as much as the print itself.
  6194. _BASELINE_REREAD_STATES = _ACTIVE_PRINT_STATES | {"PREPARE", "SLICING"}
  6195. def _schedule_timelapse_scan(
  6196. archive_id: int, printer_id: int, *, plate_id: int | None, run_id: int | None = None
  6197. ) -> None:
  6198. """Start the completion scan with the print-start baseline: the names, and
  6199. whether they were taken off a card that could not be read. Taking them
  6200. ends any re-read still running for it. ``run_id`` is the print that
  6201. ended, whose video it looks for."""
  6202. unread = printer_id in _timelapse_baselines_unread
  6203. _timelapse_baselines_unread.discard(printer_id)
  6204. baseline = _timelapse_baselines.pop(printer_id, None)
  6205. from backend.app.services import archive_work
  6206. # Held while it looks: it finds its print by the archive's id, which a
  6207. # merge would move away (archive redesign P2).
  6208. spawn_background_task(
  6209. archive_work.held_while(
  6210. archive_id,
  6211. _scan_for_timelapse_with_retries(
  6212. archive_id, baseline, plate_id=plate_id, baseline_unread=unread, run_id=run_id
  6213. ),
  6214. ),
  6215. name=f"scan-timelapse-{archive_id}",
  6216. )
  6217. def _unread_baseline_round(printer_id: int, names: set[str]) -> bool | None:
  6218. """Whether to read an unread baseline again now: True to read, None to
  6219. skip this round, False once it is over -- the print it was taken for is
  6220. no longer the one on the printer, has stopped printing, or the baseline
  6221. has been read.
  6222. ``names`` is the very set object recorded at print start: completion pops
  6223. it and the next print records a new one, so identity marks the run. A
  6224. printer that is momentarily disconnected says nothing about its print, so
  6225. that only skips the round.
  6226. """
  6227. if _timelapse_baselines.get(printer_id) is not names or printer_id not in _timelapse_baselines_unread:
  6228. return False
  6229. state = printer_manager.get_status(printer_id)
  6230. if state is None or not state.connected:
  6231. return None
  6232. return state.state in _BASELINE_REREAD_STATES
  6233. async def _reread_unread_timelapse_baseline(
  6234. printer_id: int,
  6235. names: set[str],
  6236. archive_id: int | None,
  6237. run_started_at: datetime | None,
  6238. run_id: int | None = None,
  6239. ) -> None:
  6240. """Read again a print-start baseline the card could not give (#3412).
  6241. The printer writes the video only once the print has ended, so the card
  6242. read at any point during the print holds exactly what it held at the
  6243. start. Each round stops once the print is no longer the one the baseline
  6244. was taken for or has stopped printing, and checks that again after the
  6245. listing returns, before anything is recorded.
  6246. """
  6247. from backend.app.models.archive import PrintArchive
  6248. from backend.app.models.printer import Printer
  6249. from backend.app.services.print_log import run_of
  6250. logger = logging.getLogger(__name__)
  6251. for _ in range(_TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS):
  6252. await asyncio.sleep(_TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS)
  6253. now = _unread_baseline_round(printer_id, names)
  6254. if now is False:
  6255. return
  6256. if now is None:
  6257. continue
  6258. try:
  6259. async with async_session() as db:
  6260. printer = await db.get(Printer, printer_id)
  6261. if printer is None:
  6262. return
  6263. fresh, read = await _read_timelapse_baseline(printer)
  6264. except Exception as e:
  6265. logger.debug("[TIMELAPSE] Re-reading the baseline for printer %s failed: %s", printer_id, e)
  6266. continue
  6267. if not read:
  6268. continue
  6269. now = _unread_baseline_round(printer_id, names)
  6270. if now is False:
  6271. return
  6272. if now is None:
  6273. # The printer dropped off while the listing was out, so nothing
  6274. # says it did not end meanwhile: keep the reading for a round that
  6275. # can vouch for it.
  6276. continue
  6277. names.update(fresh)
  6278. _timelapse_baselines_unread.discard(printer_id)
  6279. logger.info(
  6280. "[TIMELAPSE] Baseline for printer %s read during the print: %s video files",
  6281. printer_id,
  6282. len(fresh),
  6283. )
  6284. if archive_id is None:
  6285. return
  6286. try:
  6287. async with async_session() as db:
  6288. archive = await db.get(PrintArchive, archive_id)
  6289. # Only the run it was taken for: by now the row can belong to a
  6290. # reprint, whose baseline is its own.
  6291. if archive is not None and archive.started_at == run_started_at and archive.timelapse_baseline_unread:
  6292. archive.timelapse_baseline = sorted(names)
  6293. archive.timelapse_baseline_unread = False
  6294. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6295. if run is not None and run.timelapse_baseline_unread:
  6296. run.timelapse_baseline = sorted(names)
  6297. run.timelapse_baseline_unread = False
  6298. await db.commit()
  6299. except Exception as e:
  6300. # The in-memory baseline is read now, which covers completion
  6301. # unless Bambuddy restarts first.
  6302. logger.warning("[TIMELAPSE] Failed to persist the re-read baseline for archive %s: %s", archive_id, e)
  6303. return
  6304. async def _timelapse_still_wanted(db, archive, run_id: int | None, run_started_at: datetime | None) -> bool:
  6305. """Whether the print a timelapse is for still has none: its run, by id,
  6306. exists without a video and no later print took over (``superseded``).
  6307. Without a run, the archive is still on that print's start (a newer run's
  6308. video is its own) and has none."""
  6309. from backend.app.services.print_log import run_of, superseded
  6310. if run_id is not None:
  6311. run = await run_of(db, archive.id, run_id)
  6312. return run is not None and run.timelapse_path is None and not await superseded(db, run)
  6313. return archive.timelapse_path is None and archive.started_at == run_started_at
  6314. async def _scan_for_timelapse_with_retries(
  6315. archive_id: int,
  6316. baseline_names: set[str] | None = None,
  6317. *,
  6318. plate_id: int | None = None,
  6319. baseline_unread: bool = False,
  6320. run_id: int | None = None,
  6321. ):
  6322. """Poll the printer for this print's timelapse and attach it.
  6323. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  6324. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  6325. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  6326. (#2704). Comparing the current listing against the set of filenames that
  6327. existed when the print started needs no clock at all, because the printer
  6328. writes the video only once the print has ended.
  6329. Baseline precedence: the caller's in-memory set, then the one persisted on
  6330. the archive at print start, then a snapshot taken now. The last of those is
  6331. a poor substitute — by completion the new video may already be on the card,
  6332. in which case it lands in the "baseline" and no diff can ever match — but it
  6333. is all that is available for a print that began before Bambuddy started.
  6334. On success the video is deleted from the printer, which keeps ``/timelapse``
  6335. down to the unclaimed files and makes the next diff unambiguous.
  6336. ``baseline_unread`` marks the caller's baseline as taken off a card that
  6337. could not be read; a stored one carries the same mark on the archive.
  6338. ``run_id`` is the print that ended (archive redesign): the video is that
  6339. run's, the stored baseline is the run's own, and the poll ends once the
  6340. run has a video or is gone. Without it (no run was written), the run is
  6341. whichever the archive is on when the scan starts.
  6342. """
  6343. from backend.app.services.print_log import run_of
  6344. logger = logging.getLogger(__name__)
  6345. # Cleared when the baseline was taken off a card we could not read, so the
  6346. # attach step refuses to choose between several candidates (#2957, #3412).
  6347. baseline_trusted = True
  6348. # --- Phase 1: establish the baseline -------------------------------------
  6349. try:
  6350. async with async_session() as db:
  6351. from backend.app.models.printer import Printer
  6352. service = ArchiveService(db)
  6353. archive = await service.get_archive(archive_id)
  6354. if not archive:
  6355. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  6356. return
  6357. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6358. if run_id is not None and run is None:
  6359. logger.info("[TIMELAPSE] Run %s of archive %s is gone, aborting", run_id, archive_id)
  6360. return
  6361. if run.timelapse_path if run is not None else archive.timelapse_path:
  6362. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  6363. return
  6364. # The printer the print ran on: plates of one archive can print on
  6365. # two printers, and the archive's is the one that started last.
  6366. scan_printer_id = run.printer_id if run is not None and run.printer_id else archive.printer_id
  6367. if not scan_printer_id:
  6368. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  6369. return
  6370. # The run this scan is for. The archive row passes to a newer run
  6371. # when it prints again (the next plate, a reprint), and that run's
  6372. # video is its own.
  6373. run_started_at = run.started_at if run is not None else archive.started_at
  6374. # The baseline stored for it: the run's own, else the archive's
  6375. # while that is still this run's start's.
  6376. stored_baseline, stored_unread = None, False
  6377. if run is not None and run.timelapse_baseline is not None:
  6378. stored_baseline, stored_unread = run.timelapse_baseline, bool(run.timelapse_baseline_unread)
  6379. elif archive.started_at == run_started_at:
  6380. stored_baseline, stored_unread = archive.timelapse_baseline, archive.timelapse_baseline_unread
  6381. if baseline_names is not None and baseline_unread and stored_baseline is not None and not stored_unread:
  6382. # The card was read at print start, and the in-memory copy is
  6383. # one Bambuddy took after a restart off a card it could not
  6384. # read: the stored one is this run's and is evidence.
  6385. baseline_names = set(stored_baseline)
  6386. logger.info(
  6387. "[TIMELAPSE] Using stored baseline over an unread one: %s existing video files for archive %s",
  6388. len(baseline_names),
  6389. archive_id,
  6390. )
  6391. elif baseline_names is not None:
  6392. baseline_trusted = not baseline_unread
  6393. logger.info(
  6394. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  6395. len(baseline_names),
  6396. archive_id,
  6397. )
  6398. elif stored_baseline is not None:
  6399. # Persisted at print start — survives a restart mid-print.
  6400. baseline_names = set(stored_baseline)
  6401. baseline_trusted = not stored_unread
  6402. logger.info(
  6403. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  6404. len(baseline_names),
  6405. archive_id,
  6406. )
  6407. else:
  6408. result = await db.execute(select(Printer).where(Printer.id == scan_printer_id))
  6409. printer = result.scalar_one_or_none()
  6410. if not printer:
  6411. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  6412. return
  6413. baseline_names, baseline_trusted = await _read_timelapse_baseline(printer)
  6414. if not baseline_trusted:
  6415. # The card is unreadable at the one moment a baseline has to
  6416. # be taken, so the empty listing means "we never looked",
  6417. # not "these are all new". Carry on with it anyway — the
  6418. # usual card holds exactly one video, which resolves
  6419. # correctly — but stop the poll from *choosing* between
  6420. # several, which is how a stale video got attached to this
  6421. # print and then deleted off the printer (#2957 follow-up).
  6422. logger.warning(
  6423. "[TIMELAPSE] Baseline for archive %s taken while printer %s's card could not be "
  6424. "read. A single new video still resolves; several will not be guessed between — "
  6425. "use Scan for Timelapse to pick one by hand",
  6426. archive_id,
  6427. scan_printer_id,
  6428. )
  6429. logger.info(
  6430. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  6431. len(baseline_names),
  6432. archive_id,
  6433. )
  6434. except Exception as e:
  6435. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  6436. return
  6437. # --- Phase 2: poll for a file that was not there when the print began -----
  6438. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  6439. max_attempts = _timelapse_scan_max_attempts()
  6440. seen_names: set[str] = set()
  6441. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  6442. attempt = 0
  6443. while True:
  6444. await asyncio.sleep(delay)
  6445. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  6446. attempt += 1
  6447. try:
  6448. from backend.app.models.printer import Printer
  6449. # Read phase: fetch archive + printer in a short session and release
  6450. # the pooled connection BEFORE the FTP list/download below. Holding it
  6451. # across the FTP round-trips left one connection idle-in-transaction per
  6452. # in-flight scan (issue #2572).
  6453. async with async_session() as db:
  6454. from backend.app.services.print_log import claimed_timelapse_stems
  6455. service = ArchiveService(db)
  6456. archive = await service.get_archive(archive_id)
  6457. if not archive:
  6458. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  6459. return
  6460. if not await _timelapse_still_wanted(db, archive, run_id, run_started_at):
  6461. logger.info(
  6462. "[TIMELAPSE] Archive %s has its video or is printing again, stopping the run's poll",
  6463. archive_id,
  6464. )
  6465. return
  6466. result = await db.execute(select(Printer).where(Printer.id == scan_printer_id))
  6467. printer = result.scalar_one_or_none()
  6468. if not printer:
  6469. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  6470. return
  6471. claimed = await claimed_timelapse_stems(db, scan_printer_id, archive_id=archive_id, run_id=run_id)
  6472. # I/O phase (no DB connection held): FTP list + download.
  6473. video_files, found_path = await _list_timelapse_videos(printer)
  6474. # The poll can run for dozens of rounds, so only narrate a round
  6475. # that saw something change. Repeating the whole listing every 30 s
  6476. # would bury the one interesting line in the support bundle.
  6477. names_now = {f.get("name", "") for f in video_files}
  6478. changed = attempt == 1 or names_now != seen_names
  6479. seen_names = names_now
  6480. speak = logger.info if changed else logger.debug
  6481. if video_files:
  6482. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  6483. if changed:
  6484. for f in video_files[:5]:
  6485. logger.info("[TIMELAPSE] - %s", f.get("name"))
  6486. attached = await _attach_first_unclaimed_timelapse(
  6487. archive_id,
  6488. printer,
  6489. video_files,
  6490. baseline_names,
  6491. claimed,
  6492. attempt,
  6493. logger,
  6494. quiet=not changed,
  6495. require_unambiguous=not baseline_trusted,
  6496. plate_id=plate_id,
  6497. run_started_at=run_started_at,
  6498. run_id=run_id,
  6499. )
  6500. if attached:
  6501. return
  6502. else:
  6503. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  6504. except Exception as e:
  6505. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  6506. if attempt >= max_attempts or time.monotonic() >= deadline:
  6507. break
  6508. # No name-match fallback: it compared the print name against the filename,
  6509. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  6510. # bundles it fired 159 times and matched zero times, so all it added was a
  6511. # misleading log line before giving up.
  6512. logger.warning(
  6513. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  6514. archive_id,
  6515. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  6516. )
  6517. async def _attach_layer_timelapse(
  6518. archive_id: int,
  6519. timelapse_path: Path,
  6520. plate_id: int | None,
  6521. run_started_at: datetime | None,
  6522. run_id: int | None = None,
  6523. ) -> None:
  6524. """Attach the external camera's stitched timelapse to the archive.
  6525. The camera's video is the one the user set up in Bambuddy, so it wins
  6526. over the printer's own when both are on: it replaces the printer's video
  6527. (usually there first; stitching takes minutes) and that file is deleted,
  6528. leaving nothing in the archive folder unreferenced. ``run_started_at`` is
  6529. the run the frames were taken for: when the archive is printing again by
  6530. the time the stitch is done, the video is not the new run's and is
  6531. dropped. The stitched file is a temporary either way.
  6532. ``run_id`` is the print that ended (archive redesign): the video is that
  6533. run's and replaces that run's printer video; the poll by start above is
  6534. for a print without a run.
  6535. """
  6536. from backend.app.services.print_log import run_of, superseded
  6537. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  6538. logger = logging.getLogger(__name__)
  6539. try:
  6540. async with async_session() as db:
  6541. service = ArchiveService(db)
  6542. archive = await service.get_archive(archive_id)
  6543. if archive is None:
  6544. return
  6545. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6546. if run_id is not None and run is None:
  6547. logger.info("[LAYER-TL] Run %s of archive %s is gone; dropping its layer timelapse", run_id, archive_id)
  6548. return
  6549. if run is not None and await superseded(db, run):
  6550. logger.info(
  6551. "[LAYER-TL] A later print took over run %s of archive %s; dropping its layer timelapse",
  6552. run_id,
  6553. archive_id,
  6554. )
  6555. return
  6556. if run is None and archive.started_at != run_started_at:
  6557. logger.info(
  6558. "[LAYER-TL] Archive %s is printing again; dropping the previous run's layer timelapse", archive_id
  6559. )
  6560. return
  6561. holder = run if run is not None else archive
  6562. replaced = holder.timelapse_path
  6563. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  6564. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  6565. if not await service.attach_timelapse(
  6566. archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=plate_id, run_id=run_id
  6567. ):
  6568. return
  6569. attached = holder.timelapse_path
  6570. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  6571. if replaced and replaced != attached:
  6572. try:
  6573. old = safe_join_under(app_settings.base_dir, replaced, http=False)
  6574. except PathTraversalError:
  6575. return
  6576. await asyncio.to_thread(old.unlink, missing_ok=True)
  6577. logger.info("[LAYER-TL] Replaced the printer's timelapse %s on archive %s", replaced, archive_id)
  6578. finally:
  6579. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6580. # ``run_started_at`` not given: attach whichever run the archive is on.
  6581. _ANY_RUN = object()
  6582. async def _attach_first_unclaimed_timelapse(
  6583. archive_id: int,
  6584. printer,
  6585. video_files: list[dict],
  6586. baseline_names: set[str],
  6587. claimed: set[str],
  6588. attempt: int,
  6589. logger: logging.Logger,
  6590. *,
  6591. quiet: bool = False,
  6592. require_unambiguous: bool = False,
  6593. plate_id: int | None = None,
  6594. run_started_at: datetime | None | object = _ANY_RUN,
  6595. run_id: int | None = None,
  6596. ) -> bool:
  6597. """Download and attach the one video that belongs to this print.
  6598. A candidate is any file absent from the print-start baseline. More than one
  6599. can qualify when a previous print's video landed late, after this print's
  6600. baseline was taken — those are filtered out by name, because they are
  6601. already attached to another archive. Sorting the candidates instead would
  6602. mean sorting on mtime or on the filename timestamp, both of which come from
  6603. the printer's unsynced clock.
  6604. Returns True once a video is attached. The printer's copy is deleted only
  6605. after the attach succeeds on bytes whose length matched the listing.
  6606. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  6607. already seen this exact listing — the poll runs for many rounds and only the
  6608. rounds where something changed are worth an INFO line.
  6609. """
  6610. from backend.app.services.bambu_ftp import (
  6611. DownloadDeadlineExceeded,
  6612. delete_archived_timelapse,
  6613. download_file_bytes_async,
  6614. remote_file_settled,
  6615. )
  6616. speak = logger.debug if quiet else logger.info
  6617. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  6618. if not new_files:
  6619. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  6620. return False
  6621. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  6622. if not candidates:
  6623. speak(
  6624. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  6625. attempt,
  6626. len(new_files),
  6627. )
  6628. return False
  6629. if len(candidates) > 1:
  6630. if require_unambiguous:
  6631. # The baseline is not evidence -- it was taken off a card that could
  6632. # not be read -- so "new since the baseline" does not narrow these
  6633. # down at all. Taking the first would attach an arbitrary video to
  6634. # this print and then delete it from the printer.
  6635. logger.warning(
  6636. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  6637. "leaving all of them on the printer for manual selection",
  6638. attempt,
  6639. len(candidates),
  6640. ", ".join(str(f.get("name")) for f in candidates),
  6641. )
  6642. return False
  6643. logger.warning(
  6644. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  6645. "the rest stay on the printer for manual selection",
  6646. attempt,
  6647. len(candidates),
  6648. ", ".join(str(f.get("name")) for f in candidates),
  6649. )
  6650. target = candidates[0]
  6651. file_name = str(target.get("name") or "") # every listed entry has one
  6652. remote_path = target.get("path") or f"/timelapse/{file_name}"
  6653. logger.info(
  6654. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  6655. attempt,
  6656. file_name,
  6657. archive_id,
  6658. )
  6659. # The listing always carries a size (`list_files` skips entries it can't
  6660. # parse), but read it explicitly: the delete below is destructive and must
  6661. # depend on a size we actually had, not on one we hoped was there.
  6662. expected_size = target.get("size")
  6663. try:
  6664. timelapse_data = await download_file_bytes_async(
  6665. printer.ip_address,
  6666. printer.access_code,
  6667. remote_path,
  6668. printer_model=printer.model,
  6669. expected_size=expected_size,
  6670. )
  6671. except DownloadDeadlineExceeded:
  6672. # Too slow for its size this round; the printer keeps its copy.
  6673. timelapse_data = None
  6674. if not timelapse_data:
  6675. # Short or failed transfer. The printer keeps its copy, so the next
  6676. # round can try again — which is exactly why the delete below is
  6677. # gated on a verified download.
  6678. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  6679. return False
  6680. # The length check above proves we got what the listing said, not that the
  6681. # printer had finished writing. A video still being written can be listed
  6682. # short, served short, and pass — so confirm it has stopped growing before
  6683. # committing to it and deleting the original (#2704).
  6684. if not await remote_file_settled(
  6685. printer.ip_address,
  6686. printer.access_code,
  6687. remote_path,
  6688. len(timelapse_data),
  6689. printer_model=printer.model,
  6690. ):
  6691. return False
  6692. # Write phase: attach in a fresh short-lived session. The download took a
  6693. # while: by now the archive may have its video, or be printing again for a
  6694. # newer run, whose video this is not. Then nothing is attached or deleted,
  6695. # and the poll ends (True).
  6696. async with async_session() as db:
  6697. service = ArchiveService(db)
  6698. if run_id is not None or run_started_at is not _ANY_RUN:
  6699. current = await service.get_archive(archive_id)
  6700. started = None if run_started_at is _ANY_RUN else cast("datetime | None", run_started_at)
  6701. if current is None or not await _timelapse_still_wanted(db, current, run_id, started):
  6702. logger.info(
  6703. "[TIMELAPSE] Archive %s moved on during the download (video attached or printing again); "
  6704. "%s stays on the printer",
  6705. archive_id,
  6706. file_name,
  6707. )
  6708. return True
  6709. success = await service.attach_timelapse(
  6710. archive_id, timelapse_data, file_name, plate_id=plate_id, run_id=run_id
  6711. )
  6712. if not success:
  6713. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  6714. return False
  6715. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  6716. await delete_archived_timelapse(
  6717. printer.ip_address,
  6718. printer.access_code,
  6719. remote_path,
  6720. verified=expected_size is not None,
  6721. printer_model=printer.model,
  6722. printer_name=printer.name,
  6723. )
  6724. return True
  6725. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  6726. # module-level so tests can monkeypatch them down to ~0 without timing out.
  6727. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  6728. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  6729. # How long the *background* upgrade keeps waiting after the notification has
  6730. # already gone out (#2704 follow-up). The short bound above exists so a slow
  6731. # printer can't hold up the print-complete notification; this one exists so the
  6732. # archive still ends up with the better frame afterwards.
  6733. #
  6734. # Measured across 261 attaches in the support bundles, the video lands a median
  6735. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  6736. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  6737. # was 546s. Every other model was inside 26s. The long budget is therefore
  6738. # almost entirely for P1-series users; on everything else the short wait already
  6739. # wins and this task never runs.
  6740. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  6741. async def _capture_finish_photo_from_timelapse(
  6742. archive_id: int,
  6743. archive_dir: Path,
  6744. timeout: float | None = None,
  6745. rotation: int = 0,
  6746. run_id: int | None = None,
  6747. ) -> tuple[str | None, bool]:
  6748. """Wait for the per-print timelapse to land on the archive and extract its
  6749. last frame as the finish photo (#1397).
  6750. Bambu firmware stops timelapse recording after the toolhead parks but
  6751. before the bed-drop end-gcode runs, so the last frame frames the finished
  6752. print correctly. A live camera grab at gcode_state=FINISH captures the
  6753. bed already lowered.
  6754. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  6755. ``archive.timelapse_path`` when the file lands. This function polls for
  6756. that field.
  6757. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  6758. the wait ran out with no video on the archive yet — i.e. the video may
  6759. still be coming and a later attempt could succeed. It is False when the
  6760. video landed (whether or not extraction worked), because in that case
  6761. waiting longer changes nothing. The caller uses that to decide between
  6762. falling back permanently and scheduling a background upgrade.
  6763. ``rotation`` is the printer's camera_rotation, applied to the extracted
  6764. still (#2708) so this source agrees with every other finish-photo source.
  6765. The archived video itself is the printer's own file and is left alone —
  6766. rotating it would mean re-encoding it.
  6767. ``run_id`` is the print that ended: its own video is the one waited for,
  6768. not the archive's, which can be another plate's.
  6769. """
  6770. import uuid
  6771. from backend.app.models.archive import PrintArchive
  6772. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  6773. from backend.app.services.print_log import run_of
  6774. logger = logging.getLogger(__name__)
  6775. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  6776. deadline = asyncio.get_event_loop().time() + budget
  6777. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  6778. while True:
  6779. async with async_session() as db:
  6780. if run_id is not None:
  6781. run = await run_of(db, archive_id, run_id)
  6782. timelapse_relpath = run.timelapse_path if run else None
  6783. else:
  6784. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6785. archive = result.scalar_one_or_none()
  6786. timelapse_relpath = archive.timelapse_path if archive else None
  6787. if timelapse_relpath:
  6788. video_path = app_settings.base_dir / timelapse_relpath
  6789. if video_path.exists() and video_path.stat().st_size > 0:
  6790. photos_dir = archive_dir / "photos"
  6791. photos_dir.mkdir(parents=True, exist_ok=True)
  6792. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6793. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6794. output_path = photos_dir / filename
  6795. if await extract_video_last_frame(video_path, output_path):
  6796. await apply_camera_rotation_to_file(output_path, rotation, logger)
  6797. logger.info(
  6798. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  6799. video_path.name,
  6800. archive_id,
  6801. )
  6802. return filename, False
  6803. logger.warning(
  6804. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  6805. video_path.name,
  6806. archive_id,
  6807. )
  6808. return None, False
  6809. if asyncio.get_event_loop().time() >= deadline:
  6810. logger.info(
  6811. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  6812. archive_id,
  6813. budget,
  6814. )
  6815. return None, True
  6816. await asyncio.sleep(poll_interval)
  6817. async def _upgrade_finish_photo_from_timelapse(
  6818. archive_id: int, archive_dir: Path, rotation: int = 0, run_id: int | None = None
  6819. ) -> None:
  6820. """Add the timelapse's last frame to an archive after the fact (#2704).
  6821. The print-complete notification waits only ~60s for the video, because
  6822. holding a notification for minutes is worse than sending it with a live
  6823. camera grab. On a P1-series printer the video often lands well after that,
  6824. so the archive used to be stuck with the live grab — which is taken at
  6825. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  6826. the worse photo of the two.
  6827. This keeps waiting in the background and, when the video arrives, extracts
  6828. the frame and puts it *first* in the archive's photo list, so opening the
  6829. gallery shows it. The live grab is deliberately kept: the notification that
  6830. already went out links to that exact file, and deleting it would leave a
  6831. broken image in Discord or Telegram. ``run_id`` is the print it is for,
  6832. whose list leads with it too.
  6833. """
  6834. from backend.app.services.print_log import add_run_photo, run_of
  6835. logger = logging.getLogger(__name__)
  6836. filename, _ = await _capture_finish_photo_from_timelapse(
  6837. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation, run_id=run_id
  6838. )
  6839. if not filename:
  6840. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  6841. return
  6842. try:
  6843. async with async_session() as db:
  6844. from backend.app.models.archive import PrintArchive
  6845. archive = await db.get(PrintArchive, archive_id)
  6846. if archive is None:
  6847. return
  6848. photos = list(archive.photos or [])
  6849. if filename in photos:
  6850. return
  6851. # Front of the list: PhotoGalleryModal opens at index 0.
  6852. archive.photos = [filename, *photos]
  6853. add_run_photo(await run_of(db, archive_id, run_id) if run_id is not None else None, filename, first=True)
  6854. await db.commit()
  6855. except Exception as e:
  6856. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  6857. return
  6858. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  6859. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  6860. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  6861. """Put the filament-attribution context back after a restart mid-print.
  6862. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  6863. both die with the process. The print keeps running, so at completion the
  6864. tracker would fall back to whatever the printer reports *now* — and AMS
  6865. filament backup makes "now" the substitute tray, charging the whole print
  6866. to the spool that only finished it.
  6867. The persisted row is only trusted when its print name still matches what
  6868. the printer says it is running: a row left behind by a completion we never
  6869. saw must not attach itself to the next print.
  6870. """
  6871. try:
  6872. from backend.app.api.routes.settings import get_setting
  6873. from backend.app.services.usage_tracker import (
  6874. clear_persisted_session,
  6875. get_persisted_ams_mapping,
  6876. get_persisted_print_name,
  6877. get_persisted_spool_change_log,
  6878. restore_session,
  6879. )
  6880. persisted_name = await get_persisted_print_name(db, printer_id)
  6881. current_name = (state.subtask_name or "").strip()
  6882. if persisted_name and current_name and persisted_name.strip() != current_name:
  6883. logger.info(
  6884. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  6885. printer_id,
  6886. persisted_name,
  6887. current_name,
  6888. )
  6889. await clear_persisted_session(db, printer_id)
  6890. # Fall through to seeding: the print on the printer is real, it just
  6891. # isn't the one the row described.
  6892. persisted_log = None
  6893. else:
  6894. # Spoolman users get the tray-change log back but no in-memory
  6895. # session — see ``on_print_start`` on why that dict is load-bearing
  6896. # for the remain%-sync guard.
  6897. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6898. persisted_log = await restore_session(
  6899. db,
  6900. printer_id,
  6901. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  6902. )
  6903. # The slot pills (#1762) read the mapping captured from the print
  6904. # command, which dies with the process as well. One this process
  6905. # has captured since is newer.
  6906. if state.print_ams_mapping is None:
  6907. state.print_ams_mapping = await get_persisted_ams_mapping(db, printer_id)
  6908. # Spools swapped on a tray before the restart (#3325); anything this
  6909. # process has recorded since goes after them.
  6910. persisted_swaps = await get_persisted_spool_change_log(db, printer_id)
  6911. if persisted_swaps:
  6912. seen = getattr(state, "spool_change_log", None) or []
  6913. state.spool_change_log = persisted_swaps + [item for item in seen if item not in persisted_swaps]
  6914. if persisted_log:
  6915. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  6916. # Anything this process already observed goes after the persisted
  6917. # history — the log is ordered by layer, and a fresh process can
  6918. # only have seen changes from later in the print.
  6919. for entry in state.tray_change_log or []:
  6920. if tuple(entry) not in restored:
  6921. restored.append(tuple(entry))
  6922. state.tray_change_log = restored
  6923. tray_now = state.tray_now
  6924. if 0 <= tray_now <= 254:
  6925. if not state.tray_change_log:
  6926. # No persisted history — a print that started before this build,
  6927. # or before the row existed. Seed with the tray feeding right
  6928. # now so the remainder of the print is at least attributable to
  6929. # the right spool.
  6930. state.tray_change_log = [(tray_now, state.layer_num)]
  6931. logger.info(
  6932. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  6933. printer_id,
  6934. tray_now,
  6935. state.layer_num,
  6936. )
  6937. # The tray handler updates ``last_loaded_tray`` on every push
  6938. # regardless of whether it logged a change, so re-align it to avoid
  6939. # a duplicate entry on the next push. Only ever with a real tray:
  6940. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  6941. # 255" fallback, and writing 255 into it would defeat that.
  6942. state.last_loaded_tray = tray_now
  6943. except Exception:
  6944. # Never let attribution recovery cost the caller its timelapse
  6945. # baseline — that capture has to happen before the printer uploads
  6946. # the in-flight MP4 and there is no second chance at it.
  6947. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  6948. async def on_print_running_observed(printer_id: int, data: dict):
  6949. """Restart-recovery for a print that started before Bambuddy came up.
  6950. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  6951. after Bambuddy startup (#1304 guard, prevents duplicate archive
  6952. creation). This hook restores the persisted archive into ``_active_prints``
  6953. and captures the timelapse baseline that normally hangs off print start.
  6954. Fires once per session, in lieu of on_print_start when restart-recovery
  6955. kicks in. The printer doesn't upload the timelapse until after PRINT
  6956. COMPLETE, so a baseline captured any time during the print is still
  6957. pre-upload.
  6958. """
  6959. logger = logging.getLogger(__name__)
  6960. async with async_session() as db:
  6961. from backend.app.models.printer import Printer
  6962. state = printer_manager.get_status(printer_id)
  6963. if state is not None:
  6964. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  6965. if authorization is True:
  6966. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  6967. await _restore_usage_tracking_session(printer_id, state, db, logger)
  6968. await _restore_printable_objects(printer_id, state, db, logger)
  6969. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6970. printer = result.scalar_one_or_none()
  6971. if not printer:
  6972. logger.warning(
  6973. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  6974. printer_id,
  6975. )
  6976. return
  6977. # Avoid double-capture: ownership reconciliation above must still run when
  6978. # a baseline already exists, but the camera work itself is one-shot.
  6979. if printer_id in _timelapse_baselines:
  6980. logger.debug(
  6981. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  6982. printer_id,
  6983. )
  6984. return
  6985. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  6986. class _RunOfArchive:
  6987. """An archive as one of its runs printed it: the run's job id, start and
  6988. plate, the rest the archive's. What the reconcile judges and closes."""
  6989. def __init__(self, archive, run):
  6990. self._archive = archive
  6991. self.subtask_id = run.subtask_id
  6992. self.started_at = run.started_at
  6993. self.plate_id = run.plate_id if run.plate_id is not None else archive.plate_id
  6994. def __getattr__(self, name):
  6995. return getattr(self._archive, name)
  6996. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  6997. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  6998. against the printer's current MQTT state.
  6999. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  7000. COMPLETE events, typically a print finishing during an MQTT disconnect
  7001. window followed by a smart-plug power cycle):
  7002. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  7003. provably not running anymore — only branch that should fire under
  7004. normal disconnect-then-reconnect timing.
  7005. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  7006. firmware mints a fresh ``subtask_id`` for each print, including the
  7007. ghost replay it runs after a power cycle from a leftover SD file —
  7008. so a mismatch unambiguously means the in-DB archive is no longer
  7009. the print on the printer.
  7010. 3. Printer is running but ``subtask_name`` is empty. The printer
  7011. doesn't know what it's running; the archive's reference to it is
  7012. already broken.
  7013. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  7014. with matching subtask_id+subtask_name is left alone. The cost of a false
  7015. positive is a print closed while it still runs: the reconcile takes its
  7016. ``_active_prints`` entry and the archive is no longer ``printing``, so
  7017. the real PRINT COMPLETE later finds no archive to close (#1679). The
  7018. cost of a false negative is the ghost-print loop in #1542. What the
  7019. archive is closed as is ``_reconciled_outcome``'s call.
  7020. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  7021. MQTT has connected but the first ``push_status`` response hasn't been
  7022. applied yet — ``PrinterState`` is sitting on its construction defaults.
  7023. The reconcile caller in ``on_printer_status_change`` is already gated
  7024. on a real ``state.state``, so in normal operation this branch is
  7025. unreachable; it's kept as belt-and-braces for future callers and for
  7026. the narrow window where a partial state update could arrive
  7027. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  7028. ``not stale`` on degenerate input is strictly conservative: a real
  7029. stale archive will still be caught by the next push_status arriving
  7030. with terminal state.
  7031. """
  7032. current_state = (state.state or "").upper()
  7033. if current_state in ("", "UNKNOWN"):
  7034. # No real push_status yet — PrinterState defaults are not evidence.
  7035. return False, ""
  7036. if current_state in ("IDLE", "FINISH", "FAILED"):
  7037. return True, f"printer state {current_state}"
  7038. # Below here the printer is in a running / pre-running state (RUNNING /
  7039. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  7040. current_subtask_id = (state.subtask_id or "").strip()
  7041. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  7042. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  7043. current_subtask_name = (state.subtask_name or "").strip()
  7044. if not current_subtask_name:
  7045. return True, "printer subtask_name empty"
  7046. return False, ""
  7047. async def prime_kprofile_table(printer_id: int) -> int:
  7048. """Read the printer's calibration table once per connection.
  7049. The AMS slot card shows a K value per slot (#2854). On the printers whose
  7050. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  7051. report ``cali_idx`` and nothing else -- that number can only come from
  7052. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  7053. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  7054. backup, or the printer answering a query BambuStudio made on the report
  7055. topic we share. A Bambuddy that nobody visited showed a card with no K
  7056. values at all.
  7057. Only the diameters actually fitted are asked for, which is one request on a
  7058. single-nozzle printer and two on a dual. Probing the four sizes blind is
  7059. what the backup does, and it is both wasteful and the thing that used to
  7060. blank the table.
  7061. Returns the number of nozzles whose table was read.
  7062. """
  7063. client = printer_manager.get_client(printer_id)
  7064. state = printer_manager.get_status(printer_id)
  7065. if client is None or state is None or not state.connected:
  7066. return 0
  7067. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  7068. # ask once, and both entries are empty until the first push_status lands.
  7069. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  7070. if not diameters:
  7071. logging.getLogger(__name__).debug(
  7072. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  7073. printer_id,
  7074. )
  7075. return 0
  7076. primed = 0
  7077. for diameter in diameters:
  7078. try:
  7079. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  7080. except Exception as exc: # noqa: BLE001
  7081. # A printer that won't answer costs the card its K values, nothing
  7082. # more — never the connection this runs on the back of.
  7083. logging.getLogger(__name__).warning(
  7084. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  7085. )
  7086. continue
  7087. primed += 1
  7088. logging.getLogger(__name__).info(
  7089. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  7090. )
  7091. return primed
  7092. def _sd_files_in_use(state) -> set[str]:
  7093. """Names of the SD-card files the printer may be printing right now (#3009).
  7094. The post-print cleanup works out what to delete from the finished archive,
  7095. not from the printer. When reconciliation closes an old archive because the
  7096. printer has moved on to a new job, and that job is the same file reprinted
  7097. from the printer's screen, the cleanup would delete the file mid-print.
  7098. Empty unless the printer is busy: on an ordinary completion the state is
  7099. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  7100. name, a path or a URL depending on firmware, and some report only the
  7101. plate's G-code, so the job name is matched as well, in the same spellings
  7102. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  7103. ignores case.
  7104. """
  7105. def _text(value) -> str:
  7106. return value.strip() if isinstance(value, str) else ""
  7107. if state is None:
  7108. return set()
  7109. current_state = _text(getattr(state, "state", None)).upper()
  7110. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  7111. return set()
  7112. in_use: set[str] = set()
  7113. gcode_file = _text(getattr(state, "gcode_file", None))
  7114. if gcode_file:
  7115. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  7116. # both legal in a file name, and raises on some inputs.
  7117. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  7118. if name:
  7119. in_use.add(name.lower())
  7120. subtask_name = _text(getattr(state, "subtask_name", None))
  7121. if subtask_name:
  7122. for name in (subtask_name, subtask_name.replace(" ", "_")):
  7123. for ext in (".3mf", ".gcode"):
  7124. in_use.add(f"{name}{ext}".lower())
  7125. return in_use
  7126. def _reconciled_outcome(archive, state) -> str:
  7127. """What a stale archive is closed as at reconnect (#3310).
  7128. A print that ends while Bambuddy restarts is never seen to end: the new
  7129. MQTT client's first status is already FINISH, which is not a transition.
  7130. The printer keeps reporting the finished job's ``subtask_id`` until the
  7131. next print, so a matching id proves the FINISH or FAILED is this
  7132. archive's. Anything else -- IDLE, another job, an id of "0" (a print
  7133. started outside the cloud) or none -- says only that the print is over,
  7134. not how, and stays ``aborted``.
  7135. """
  7136. current_state = (state.state or "").upper()
  7137. if current_state not in ("FINISH", "FAILED"):
  7138. return "aborted"
  7139. archive_id = (archive.subtask_id or "").strip()
  7140. current_id = str(state.subtask_id or "").strip()
  7141. if archive_id in ("", "0") or archive_id != current_id:
  7142. return "aborted"
  7143. return "completed" if current_state == "FINISH" else "failed"
  7144. def _reconciled_end_time(archive, now: datetime, plate_id: int | None = None) -> datetime | None:
  7145. """When a print reconciled as completed most likely ended, or None (#3310).
  7146. The printer does not say when it finished, and the reconnect can be hours
  7147. later. Its start plus the slicer's estimate for the plate it printed,
  7148. never later than now, is the best guess; None when either is missing,
  7149. and the run then keeps no duration, as an aborted one does.
  7150. ``plate_id`` is the plate this run printed, from its queue job: a reprint
  7151. of another plate reuses the archive without changing ``archive.plate_id``.
  7152. """
  7153. started = archive.started_at
  7154. if not started:
  7155. return None
  7156. if started.tzinfo is None:
  7157. started = started.replace(tzinfo=timezone.utc)
  7158. plate = plate_id if plate_id is not None else archive.plate_id
  7159. estimate = None
  7160. if archive.file_path:
  7161. from backend.app.utils.threemf_tools import extract_print_time_from_3mf
  7162. full_path = (
  7163. app_settings.base_dir / archive.file_path
  7164. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7165. try:
  7166. estimate = extract_print_time_from_3mf(full_path, plate)
  7167. except Exception as exc: # noqa: BLE001
  7168. logging.getLogger(__name__).debug(
  7169. "Plate estimate for reconciled archive %s unreadable: %s", archive.id, exc
  7170. )
  7171. if plate is None and estimate != archive.print_time_seconds:
  7172. # Without a plate the first plate's estimate is read. The archive
  7173. # carries the sum over all plates (#1593), so a difference means
  7174. # several plates and no telling which one printed.
  7175. estimate = None
  7176. elif plate is None:
  7177. # Nothing to read the plate from; the archive's own estimate, as for
  7178. # a single-plate file.
  7179. estimate = archive.print_time_seconds
  7180. if not estimate or estimate <= 0:
  7181. return None
  7182. return min(started + timedelta(seconds=int(estimate)), now)
  7183. async def reconcile_stale_active_prints(printer_id: int) -> int:
  7184. """Synthesise ``on_print_complete`` for archives whose print can't be
  7185. running on the printer anymore.
  7186. Called once per MQTT (re)connection (from on_printer_status_change when
  7187. the connected edge flips False → True) and at Bambuddy startup (from
  7188. the FastAPI lifespan). Without this, a print that completes during a
  7189. disconnect window — followed by a smart-plug-driven power cycle — leaves
  7190. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  7191. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  7192. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  7193. power cycle until the operator notices (#1542 follow-up). Reconciliation
  7194. closes the loop by faking the missed PRINT COMPLETE — the existing
  7195. cleanup chain handles SD-file deletion, status updates, usage tracking,
  7196. and notifications.
  7197. The status is ``_reconciled_outcome``'s: ``completed`` or ``failed``
  7198. when the printer still reports the archive's own job as finished or
  7199. failed, ``aborted`` otherwise. Nothing corrects it later: the archive is
  7200. no longer ``printing``, so a later PRINT COMPLETE finds no archive, and
  7201. after a restart the printer's FINISH is not one (#3310).
  7202. Returns the number of archives reconciled.
  7203. """
  7204. state = printer_manager.get_status(printer_id)
  7205. if not state:
  7206. return 0
  7207. # Don't reconcile while disconnected — we'd be making a decision against
  7208. # stale cached state. The connected → reconcile edge handles this.
  7209. if not state.connected:
  7210. return 0
  7211. from backend.app.models.archive import PrintArchive
  7212. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
  7213. reconciled = 0
  7214. async with async_session() as db:
  7215. # The prints on this printer Bambuddy saw start: their runs open here.
  7216. # The archive row is shared by every plate of a file, its printer, job
  7217. # and start the latest start's, so each is judged as its run.
  7218. open_runs = (
  7219. await db.scalars(
  7220. select(PrintLogEntry)
  7221. .where(PrintLogEntry.printer_id == printer_id, PrintLogEntry.status == RUN_OPEN)
  7222. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7223. )
  7224. ).all()
  7225. by_run = {
  7226. archive.id: archive
  7227. for archive in (
  7228. await db.scalars(
  7229. select(PrintArchive).where(
  7230. PrintArchive.id.in_([run.archive_id for run in open_runs if run.archive_id is not None])
  7231. )
  7232. )
  7233. ).all()
  7234. }
  7235. active: list = [_RunOfArchive(by_run[run.archive_id], run) for run in open_runs if run.archive_id in by_run]
  7236. # And as before runs were opened at the start: a printing archive of
  7237. # this printer with no run open anywhere (printing since before).
  7238. archives_with_open_runs = select(PrintLogEntry.archive_id).where(
  7239. PrintLogEntry.status == RUN_OPEN, PrintLogEntry.archive_id.is_not(None)
  7240. )
  7241. result = await db.execute(
  7242. select(PrintArchive)
  7243. .where(
  7244. PrintArchive.printer_id == printer_id,
  7245. PrintArchive.status == "printing",
  7246. PrintArchive.id.not_in(archives_with_open_runs),
  7247. )
  7248. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7249. )
  7250. active.extend(result.scalars().all())
  7251. if not active:
  7252. return 0
  7253. # The plate each run printed, from its queue job (#3310).
  7254. from backend.app.models.print_queue import PrintQueueItem
  7255. async with async_session() as db:
  7256. plate_rows = await db.execute(
  7257. select(PrintQueueItem.archive_id, PrintQueueItem.plate_id).where(
  7258. PrintQueueItem.printer_id == printer_id,
  7259. PrintQueueItem.status == "printing",
  7260. PrintQueueItem.archive_id.in_([a.id for a in active]),
  7261. )
  7262. )
  7263. run_plates = {archive_id: plate for archive_id, plate in plate_rows.all() if plate is not None}
  7264. logger = logging.getLogger(__name__)
  7265. for archive in active:
  7266. is_stale, reason = _is_active_archive_stale(archive, state)
  7267. if not is_stale:
  7268. continue
  7269. logger.info(
  7270. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  7271. printer_id,
  7272. archive.id,
  7273. archive.filename,
  7274. reason,
  7275. )
  7276. # Synthesised payload: minimal fields the on_print_complete chain
  7277. # needs. `_reconciled` marker lets downstream code distinguish this
  7278. # from a real MQTT-driven completion if it ever needs to (e.g. for
  7279. # metrics / debug logging). raw_data is the live printer state so
  7280. # the usage tracker can compare end-of-print remain% against the
  7281. # captured start values.
  7282. outcome = _reconciled_outcome(archive, state)
  7283. payload = {
  7284. "status": outcome,
  7285. "filename": archive.filename,
  7286. "subtask_name": archive.print_name or "",
  7287. "subtask_id": archive.subtask_id or "",
  7288. "raw_data": state.raw_data or {},
  7289. "_reconciled": True,
  7290. }
  7291. if isinstance(archive, _RunOfArchive):
  7292. # The archive it closes, which its names and printer may not find:
  7293. # another printer's plate of it can have started since.
  7294. payload["_reconciled_archive_id"] = archive.id
  7295. if outcome != "aborted":
  7296. # The printer's progress and layer are this job's, so a partial
  7297. # run is charged what it printed rather than nothing.
  7298. if state.progress:
  7299. payload["last_progress"] = state.progress
  7300. if state.layer_num:
  7301. payload["last_layer_num"] = state.layer_num
  7302. if outcome == "failed":
  7303. payload["hms_errors"] = [e.completion_payload() for e in state.hms_errors or []]
  7304. if outcome == "completed":
  7305. ended = _reconciled_end_time(archive, datetime.now(timezone.utc), run_plates.get(archive.id))
  7306. if ended:
  7307. payload["_reconciled_completed_at"] = ended
  7308. try:
  7309. await on_print_complete(printer_id, payload)
  7310. reconciled += 1
  7311. except Exception as e:
  7312. # Catch-all: a reconciliation failure must not block the
  7313. # printer's normal status flow. The archive stays in
  7314. # ``status="printing"`` and the next reconnect retries.
  7315. logger.warning(
  7316. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  7317. archive.id,
  7318. e,
  7319. )
  7320. return reconciled
  7321. # #2547: clearance left between the nozzle and the top of the print when the
  7322. # plate is commanded back into camera framing. The nozzle is parked away from
  7323. # the part by then, so this is belt-and-braces against a max_z_height that
  7324. # under-reports (e.g. a slicer that excludes a final Z hop).
  7325. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  7326. # How far below the restored position to drop the plate again afterwards, so
  7327. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  7328. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  7329. # on machines with less headroom.
  7330. _PLATE_PARK_DROP_MM = 100.0
  7331. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  7332. # this axis, so it is a proven-safe speed for the full travel.
  7333. _PLATE_RESTORE_FEEDRATE = 600
  7334. # Time allowed for the plate to reach the restored position before the camera
  7335. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  7336. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  7337. # How long `_background_finish_photo` waits for this producer. Must cover the
  7338. # settle window plus a worst-case RTSP grab (15s), and stay below the
  7339. # notification path's own photo wait so a slow producer degrades to a
  7340. # photo-less notification rather than a missed one. The chamber light's
  7341. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  7342. # camera_light.MAX_DELAY_SECONDS stays below it.
  7343. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  7344. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  7345. """The ``_active_prints`` keys a finished print may be registered under.
  7346. Matching how they were registered in on_print_start. Shared by
  7347. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  7348. to find the same binding.
  7349. """
  7350. possible_keys = []
  7351. # Try subtask_name variations first (most reliable for matching)
  7352. if subtask_name:
  7353. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  7354. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  7355. possible_keys.append((printer_id, subtask_name))
  7356. # Try filename variations
  7357. if filename:
  7358. # Extract just the filename if it's a path
  7359. fname = filename.split("/")[-1] if "/" in filename else filename
  7360. if fname.endswith(".3mf"):
  7361. possible_keys.append((printer_id, fname))
  7362. elif fname.endswith(".gcode"):
  7363. base_name = fname.rsplit(".", 1)[0]
  7364. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  7365. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7366. possible_keys.append((printer_id, fname))
  7367. else:
  7368. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  7369. possible_keys.append((printer_id, f"{fname}.3mf"))
  7370. possible_keys.append((printer_id, fname))
  7371. # Also try full path versions
  7372. if filename.endswith(".3mf"):
  7373. possible_keys.append((printer_id, filename))
  7374. elif filename.endswith(".gcode"):
  7375. base_name = filename.rsplit(".", 1)[0]
  7376. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7377. possible_keys.append((printer_id, filename))
  7378. else:
  7379. possible_keys.append((printer_id, f"{filename}.3mf"))
  7380. possible_keys.append((printer_id, filename))
  7381. return possible_keys
  7382. def _archive_name_forms(archive) -> set[str]:
  7383. """The names an archive could be echoed back as, in normalised form (#3240).
  7384. Its print name, and its filename with and without the 3MF extension.
  7385. """
  7386. forms = set()
  7387. if archive.print_name:
  7388. forms.add(_normalise_subtask_name(archive.print_name))
  7389. if archive.filename:
  7390. forms.add(_normalise_subtask_name(archive.filename))
  7391. for suffix in (".gcode.3mf", ".3mf"):
  7392. if archive.filename.lower().endswith(suffix):
  7393. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  7394. forms.discard("")
  7395. return forms
  7396. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  7397. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  7398. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  7399. from the plate recorded when the job was dispatched. Neither is touched:
  7400. ``on_print_complete`` pops both, which is why the finish-photo producer
  7401. calls this before its first await, while they are still there.
  7402. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  7403. archive, or that it only knows by a name -- and on any error: the producer
  7404. calls this before the ``try`` that always releases the photo consumer, so
  7405. it must not raise.
  7406. """
  7407. try:
  7408. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  7409. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  7410. if archive_id is None:
  7411. return None, None
  7412. return archive_id, _print_plate_ids.get((printer_id, archive_id))
  7413. except Exception:
  7414. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  7415. return None, None
  7416. async def _max_z_for_current_print(
  7417. printer_id: int,
  7418. data: dict,
  7419. logger,
  7420. archive_id: int | None,
  7421. plate_id: int | None = None,
  7422. ) -> float | None:
  7423. """Height of the print that just finished on ``printer_id``, or None (#2547).
  7424. This number becomes the target of a real Z move, so every step here refuses
  7425. rather than guesses. A height belonging to some *other* print is the one
  7426. failure that could drive the nozzle into the model: 20 mm carried onto a
  7427. 200 mm print would command the plate up through the part.
  7428. Three independent things therefore have to agree before a height is
  7429. returned:
  7430. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  7431. when it started (see ``_bound_print``), never one found by name. A name
  7432. is not an identity: every plate of a multi-plate file shares one, and a
  7433. reprint reuses its archive row, so the newest archive with the right
  7434. name can be another plate of the same file. Support bundles show the
  7435. old name lookup doing exactly that (archive 288 for a print bound to
  7436. 169, 313 layers against 125), stopped only by the layer check below.
  7437. No binding, no move.
  7438. 2. **Identity.** The bound archive's name still has to be the finished
  7439. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  7440. because the printer echoes spaces as underscores (#3240). Exact: not a
  7441. substring, and not the completion check's tolerance for a truncated
  7442. echo.
  7443. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  7444. match the layer count the printer itself reported over MQTT for the print
  7445. that just ended. These come from genuinely different sources, so a
  7446. mismatch means the row is not this print, whatever its name says.
  7447. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  7448. plate of a multi-plate file reuses the archive row without updating its
  7449. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  7450. ``on_print_complete`` may already have flipped the status by the time we
  7451. run.
  7452. """
  7453. subtask_name = (data.get("subtask_name") or "").strip()
  7454. if not subtask_name:
  7455. # Nothing to identify the print by — refuse rather than fall back to
  7456. # "whatever ran last on this printer".
  7457. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  7458. return None
  7459. if archive_id is None:
  7460. logger.info(
  7461. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  7462. printer_id,
  7463. subtask_name,
  7464. )
  7465. return None
  7466. try:
  7467. from backend.app.models.archive import PrintArchive
  7468. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  7469. async with async_session() as db:
  7470. result = await db.execute(
  7471. select(PrintArchive).where(
  7472. PrintArchive.id == archive_id,
  7473. PrintArchive.printer_id == printer_id,
  7474. PrintArchive.status.in_(("printing", "completed")),
  7475. PrintArchive.deleted_at.is_(None),
  7476. )
  7477. )
  7478. archive = result.scalar_one_or_none()
  7479. if archive is None or not archive.file_path:
  7480. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  7481. return None
  7482. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  7483. logger.warning(
  7484. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  7485. printer_id,
  7486. archive_id,
  7487. subtask_name,
  7488. )
  7489. return None
  7490. client = printer_manager.get_client(printer_id)
  7491. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  7492. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  7493. logger.warning(
  7494. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  7495. "— refusing to move the plate on a height that may not be this print's",
  7496. printer_id,
  7497. archive.id,
  7498. archive.total_layers,
  7499. reported_layers,
  7500. )
  7501. return None
  7502. # Stored relative to the data directory, like every other archive path
  7503. # (#3240: this read a `data_dir` setting that does not exist).
  7504. path = app_settings.base_dir / archive.file_path
  7505. plate = plate_id or archive.plate_id or 1
  7506. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  7507. except Exception as e:
  7508. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  7509. return None
  7510. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  7511. """Raise the plate back into camera framing before the finish photo (#2547).
  7512. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  7513. the time ``gcode_state`` reaches FINISH the finished print sits far below
  7514. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  7515. This commands an absolute ``G1 Z`` back to just above the last printed
  7516. layer.
  7517. Absolute, not relative, is the whole safety argument. ``max_z_height +
  7518. clearance`` is a height the toolhead was physically at seconds earlier, so
  7519. it is inside the travel limits by construction and leaves the nozzle above
  7520. the part. It is also unambiguous across model families: Z is the
  7521. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  7522. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  7523. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  7524. (#2579).
  7525. Returns True if the move was sent and waited out, False if it was skipped.
  7526. """
  7527. client = printer_manager.get_client(printer_id)
  7528. if client is None:
  7529. return False
  7530. # Re-read state immediately before commanding motion. If the queue has
  7531. # already started the next print, the printer is no longer ours to move.
  7532. state = getattr(client, "state", None)
  7533. if state is None or state.state != "FINISH":
  7534. logger.info(
  7535. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  7536. printer_id,
  7537. getattr(state, "state", "unknown"),
  7538. )
  7539. return False
  7540. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  7541. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  7542. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  7543. return False
  7544. logger.info(
  7545. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  7546. printer_id,
  7547. target_z,
  7548. max_z_height,
  7549. _PLATE_RESTORE_CLEARANCE_MM,
  7550. _PLATE_RESTORE_SETTLE_SECONDS,
  7551. )
  7552. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  7553. return True
  7554. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  7555. """Drop the plate again after the finish photo (#2547).
  7556. Without this the user walks up to a finished print sitting just under the
  7557. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  7558. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  7559. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  7560. print homes anyway.
  7561. """
  7562. client = printer_manager.get_client(printer_id)
  7563. state = getattr(client, "state", None) if client else None
  7564. if client is None or state is None or state.state != "FINISH":
  7565. return
  7566. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  7567. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  7568. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  7569. """True if a queue item is about to take this printer (#2547).
  7570. The scheduler dispatches the next job the moment a print completes, and a
  7571. plate move interleaved with a print start is not a race worth having. The
  7572. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  7573. this window; this closes the head of it.
  7574. """
  7575. try:
  7576. from backend.app.models.print_queue import PrintQueueItem
  7577. async with async_session() as db:
  7578. result = await db.execute(
  7579. select(PrintQueueItem.id)
  7580. .where(
  7581. PrintQueueItem.printer_id == printer_id,
  7582. PrintQueueItem.status.in_(("pending", "printing")),
  7583. )
  7584. .limit(1)
  7585. )
  7586. return result.scalar_one_or_none() is not None
  7587. except Exception as e:
  7588. # Fail closed: if we can't tell, don't move the plate.
  7589. logging.getLogger(__name__).debug(
  7590. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  7591. )
  7592. return True
  7593. async def on_finish_photo_moment(printer_id: int, data: dict):
  7594. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  7595. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  7596. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  7597. fallback for prints that skip stage 22 (cancel, external-spool-only,
  7598. HMS halt, firmware variants). Grabs one frame via the same
  7599. external-camera / RTSP path the post-completion fallback uses, stores
  7600. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  7601. ``_background_finish_photo`` consume the cached bytes when it runs.
  7602. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  7603. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  7604. set to Smooth (#1721). No force-on now means the user's explicit
  7605. timelapse=off in the slicer send dialog is respected.
  7606. """
  7607. logger = logging.getLogger(__name__)
  7608. trigger = data.get("trigger", "unknown")
  7609. timelapse_was_active = bool(data.get("timelapse_was_active"))
  7610. logger.info(
  7611. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  7612. printer_id,
  7613. trigger,
  7614. timelapse_was_active,
  7615. )
  7616. # If a timelapse is actively recording, skip the pre-capture — the
  7617. # post-completion path will extract the last frame from the recorded
  7618. # video, which still provides the best framing (toolhead parked,
  7619. # before bed drop) without the per-layer parking side effects.
  7620. if timelapse_was_active:
  7621. logger.info(
  7622. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  7623. printer_id,
  7624. )
  7625. return
  7626. # #1790: register the producer-done event BEFORE the first await so the
  7627. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  7628. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  7629. # The `finally` below guarantees `set()` runs on every exit, including
  7630. # early returns and exceptions, so the consumer's bounded wait can't hang.
  7631. producer_done = asyncio.Event()
  7632. _stage22_finish_in_flight[printer_id] = producer_done
  7633. # #3240: also before the first await. On the FINISH-state path
  7634. # `on_print_complete` is dispatched right behind us and pops both the
  7635. # print's archive binding and its plate; read here, they are still there.
  7636. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  7637. # #2547: set once the plate has actually been raised, and read by the
  7638. # `finally` below. Declared out here so a failure anywhere after the move —
  7639. # a camera timeout, a DB error — still lowers the plate again.
  7640. restore_max_z: float | None = None
  7641. try:
  7642. async with async_session() as db:
  7643. from backend.app.api.routes.settings import get_setting
  7644. from backend.app.models.printer import Printer
  7645. capture_setting = await get_setting(db, "capture_finish_photo")
  7646. if capture_setting is not None and capture_setting.lower() != "true":
  7647. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  7648. return
  7649. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7650. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  7651. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7652. printer = result.scalar_one_or_none()
  7653. if printer is None:
  7654. logger.warning(
  7655. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  7656. printer_id,
  7657. )
  7658. return
  7659. frame_bytes: bytes | None = None
  7660. # #2708: the banked frame arrives already rotated — it comes from
  7661. # `_capture_snapshot_for_notification`, which rotates before returning.
  7662. # Every other source below is a raw grab. Tracking which lets us store
  7663. # exactly one rotation in `_stage22_finish_frames` either way.
  7664. frame_already_rotated = False
  7665. # On the FINISH-state path the End G-code has already run, and two very
  7666. # different situations arrive here needing opposite answers.
  7667. #
  7668. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  7669. # snippet may have ejected the plate — the scene in front of the camera
  7670. # is no longer the finished print, and no amount of moving the plate
  7671. # brings it back. Use the banked in-print frame instead.
  7672. #
  7673. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  7674. # than the camera frames well, and the toolhead is parked out of the
  7675. # way. That is the *best* moment available on firmware that never emits
  7676. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  7677. # back. Preferring the bank here unconditionally, as this code used to,
  7678. # is what shipped a mid-print photo with the toolhead over the part.
  7679. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  7680. banked = _inprint_frame_bank.get(printer_id)
  7681. if banked:
  7682. frame_bytes = banked
  7683. frame_already_rotated = True
  7684. logger.info(
  7685. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  7686. "frame (%d bytes) instead of a post-swap live grab",
  7687. len(banked),
  7688. )
  7689. else:
  7690. logger.warning(
  7691. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  7692. "in-print bank is empty — falling back to a live grab, which may show a "
  7693. "swapped or empty plate",
  7694. printer_id,
  7695. )
  7696. # `restore_max_z` is set only once the plate is actually up, because the
  7697. # `finally` reads it to decide whether it owes a move back down.
  7698. #
  7699. # Never on a print whose End G-code Bambuddy injected, even when the bank
  7700. # came up empty above: that machine may have just ejected its plate, and
  7701. # driving Z into whatever a swap mechanism is doing is not a risk worth
  7702. # taking for a photo of a bed we already know may be bare.
  7703. if (
  7704. frame_bytes is None
  7705. and trigger == "finish_state"
  7706. and restore_plate_enabled
  7707. and not print_dispatch_context.end_gcode_injected(printer_id)
  7708. ):
  7709. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  7710. if wants_restore is None:
  7711. logger.info(
  7712. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  7713. printer_id,
  7714. )
  7715. elif await _plate_restore_is_blocked_by_queue(printer_id):
  7716. logger.info(
  7717. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  7718. printer_id,
  7719. )
  7720. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  7721. restore_max_z = wants_restore
  7722. # Chamber light for the live capture below (#1655). The banked frame
  7723. # above was taken without it, like every in-print bank.
  7724. async with camera_light(printer if frame_bytes is None else None):
  7725. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  7726. from backend.app.api.routes.camera import live_frame_for_capture
  7727. from backend.app.services.external_camera import capture_frame
  7728. # #2707: this used to collide with the live view and fail, which is
  7729. # how finish-photo notifications went out with no image attached.
  7730. # Leaving frame_bytes None keeps the rest of the fallback chain.
  7731. defer, buffered = live_frame_for_capture(printer_id)
  7732. if defer:
  7733. frame_bytes = buffered
  7734. else:
  7735. frame_bytes = await capture_frame(
  7736. printer.external_camera_url,
  7737. printer.external_camera_type or "mjpeg",
  7738. snapshot_url=printer.external_camera_snapshot_url,
  7739. )
  7740. if frame_bytes:
  7741. logger.info(
  7742. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  7743. len(frame_bytes),
  7744. )
  7745. elif frame_bytes is None:
  7746. from backend.app.api.routes.camera import get_buffered_frame
  7747. buffered = get_buffered_frame(printer_id)
  7748. if buffered:
  7749. frame_bytes = buffered
  7750. logger.info(
  7751. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  7752. len(frame_bytes),
  7753. )
  7754. else:
  7755. from backend.app.services.camera import capture_camera_frame_bytes
  7756. frame_bytes = await capture_camera_frame_bytes(
  7757. ip_address=printer.ip_address,
  7758. access_code=printer.access_code,
  7759. model=printer.model,
  7760. timeout=15,
  7761. )
  7762. if frame_bytes:
  7763. logger.info(
  7764. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  7765. len(frame_bytes),
  7766. )
  7767. if frame_bytes:
  7768. if not frame_already_rotated:
  7769. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  7770. _stage22_finish_frames[printer_id] = frame_bytes
  7771. else:
  7772. logger.warning(
  7773. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  7774. printer_id,
  7775. )
  7776. except Exception as e:
  7777. logger.warning(
  7778. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  7779. printer_id,
  7780. e,
  7781. )
  7782. finally:
  7783. # #2547: we raised the plate, so we own lowering it — including when the
  7784. # capture above failed or threw partway through.
  7785. if restore_max_z is not None:
  7786. try:
  7787. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  7788. except Exception as e:
  7789. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7790. # #1790: always unblock the consumer's bounded wait — whether we stored
  7791. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  7792. # dict entry by the consumer doesn't affect signalling.
  7793. producer_done.set()
  7794. def _subtask_name_from_filename(filename: str) -> str:
  7795. """Recover the subtask name a print command would have carried for *filename*.
  7796. The dispatcher derives the printer-facing subtask name from the archive's
  7797. file name, so stripping the extensions back off gives the value MQTT echoes
  7798. on completion. Only the two extensions Bambuddy actually stores are removed,
  7799. and in the order they nest (``.gcode.3mf``), so a model whose own name
  7800. contains a dot -- ``My.Model.3mf`` -- keeps it.
  7801. """
  7802. name = PurePosixPath(filename).name
  7803. for suffix in (".3mf", ".gcode"):
  7804. if name.lower().endswith(suffix):
  7805. name = name[: -len(suffix)]
  7806. return name
  7807. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  7808. """Whether the subtask name is the printed 3MF's own file name.
  7809. A print started from the printer's screen reports the same full name, with
  7810. its extension, as both subtask and file (#3009). A dispatched print reports
  7811. a bare subtask name; one that merely ends in ".3mf" can be a model named
  7812. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  7813. """
  7814. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  7815. return False
  7816. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  7817. # How the printer marks a subtask name it had to cut short. Observed on real
  7818. # hardware at ~100 characters, but the cut-off is not a fixed character count
  7819. # (a name with multibyte characters came back at 98), so match the marker
  7820. # rather than a length.
  7821. _SUBTASK_TRUNCATION_MARKER = "..."
  7822. def _normalise_subtask_name(name: str) -> str:
  7823. """Canonical form for comparing a dispatched name against MQTT's echo.
  7824. The printer does not echo the name back verbatim: it substitutes
  7825. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  7826. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  7827. The 3MF lookup in this module has always known that -- it builds
  7828. space-to-underscore variants of every candidate filename, and its
  7829. directory search normalises both sides before comparing. This exists so
  7830. the completion check reads the same rule from the same place instead of
  7831. growing its own, which is exactly how it came to disagree (#2829).
  7832. A space at either end is substituted too: ``Part .gcode.3mf`` is
  7833. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  7834. are dropped after the substitution so both sides agree (#3241).
  7835. """
  7836. return name.strip().replace(" ", "_").strip("_").casefold()
  7837. def _3mf_files_for_print(paths: list[str], search_term: str) -> list[str]:
  7838. """The 3MF files of the printer's folder listings that are this print's.
  7839. A file of the print's own name wins, in whichever folder. Only without one
  7840. is a file that merely contains the name taken, and then only when it is
  7841. the one such file: "Cube_large.3mf" is not "Cube"'s file, and of several
  7842. candidates none can be told apart. Paths keep the listings' order.
  7843. """
  7844. threemf = [path for path in paths if path.lower().endswith(".3mf")]
  7845. exact = [path for path in threemf if _subtask_names_match(_subtask_name_from_filename(path), search_term)]
  7846. if exact:
  7847. return exact
  7848. term = _normalise_subtask_name(search_term)
  7849. partial = [path for path in threemf if term in _normalise_subtask_name(PurePosixPath(path).name)]
  7850. if len(partial) > 1:
  7851. logging.getLogger(__name__).info(
  7852. "Several 3MF files contain %r and none is named for it: %s", search_term, partial
  7853. )
  7854. return []
  7855. return partial
  7856. def _subtask_names_match(expected: str, observed: str) -> bool:
  7857. """Whether two subtask names describe the same print.
  7858. Beyond the space/underscore substitution, the printer truncates long names
  7859. and marks the cut with ``...``. A truncated echo has to count as a match or
  7860. every print with a long name strands its queue item the same way.
  7861. """
  7862. expected_n = _normalise_subtask_name(expected)
  7863. observed_n = _normalise_subtask_name(observed)
  7864. if expected_n == observed_n:
  7865. return True
  7866. # Either side can be the truncated one: the printer truncates what it
  7867. # echoes, and an archive whose own filename was recorded from a previous
  7868. # truncated echo carries the marker too.
  7869. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  7870. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  7871. continue
  7872. # The full side has lost its edge underscores; a cut that lands right
  7873. # after one keeps it, so drop it here too (#3241). Nothing left before
  7874. # the marker is no evidence of anything, and must not match every name.
  7875. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  7876. if kept and full.startswith(kept):
  7877. return True
  7878. return False
  7879. async def _queue_item_dispatched_name(db, item) -> str:
  7880. """The subtask name *item* was dispatched under, or "" when unknowable.
  7881. A row with no archive, or an archive with no file name, is unverifiable
  7882. rather than wrong; every caller answers that with its permissive branch.
  7883. """
  7884. if item.archive_id is None:
  7885. return ""
  7886. from backend.app.models.archive import PrintArchive
  7887. archive = await db.get(PrintArchive, item.archive_id)
  7888. if archive is None or not archive.filename:
  7889. return ""
  7890. return _subtask_name_from_filename(archive.filename)
  7891. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  7892. """Whether this completion event is plausibly about *item*'s print.
  7893. The caller finds its queue row by printer and ``status='printing'`` alone,
  7894. which is all a completion event gives it -- there is no run identifier in
  7895. the MQTT payload to match on. That makes the lookup indiscriminate: any
  7896. completion delivered for this printer closes whichever row happens to be
  7897. printing, however unrelated. Comparing the subtask name against the archive
  7898. the row was dispatched with costs one primary-key load and rules that out.
  7899. Deliberately permissive: it answers False only on a positive disagreement
  7900. between two names we actually have. A row with no archive, an archive with
  7901. no file name, or an event with no subtask name is unverifiable rather than
  7902. wrong, and refusing those would strand the item in ``printing`` and wedge
  7903. the printer's queue -- a worse failure than the one being prevented.
  7904. """
  7905. observed = (data.get("subtask_name") or "").strip()
  7906. if not observed or item.archive_id is None:
  7907. return True
  7908. from backend.app.models.archive import PrintArchive
  7909. archive = await db.get(PrintArchive, item.archive_id)
  7910. if archive is None or not archive.filename:
  7911. return True
  7912. expected = _subtask_name_from_filename(archive.filename)
  7913. if not expected or _subtask_names_match(expected, observed):
  7914. return True
  7915. logging.getLogger(__name__).warning(
  7916. "Ignoring print completion for queue item %s: it was dispatched as %r "
  7917. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  7918. "printing rather than closing a run this event is not about.",
  7919. item.id,
  7920. expected,
  7921. archive.id,
  7922. archive.filename,
  7923. observed,
  7924. )
  7925. return False
  7926. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  7927. """Spend the 3MF download cache on a still-empty fallback archive.
  7928. ``on_print_complete`` drops the cache as its first act, which deletes the
  7929. file. If the cover endpoint (or anything else) pulled the 3MF while the
  7930. print ran and the archive never got one, this is the last moment those bytes
  7931. exist (#2957).
  7932. """
  7933. logger = logging.getLogger(__name__)
  7934. names = [
  7935. n
  7936. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  7937. if n
  7938. ]
  7939. for name in names:
  7940. try:
  7941. cached = get_cached_3mf(printer_id, name)
  7942. # The print has ended: its completion prices the archive, so no
  7943. # print-start estimate is scheduled to race it.
  7944. if cached and await try_recover_fallback_archive(printer_id, name, cached, price=False):
  7945. return
  7946. except Exception as e:
  7947. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  7948. # Longest the print's end waits for its file to be deleted from the SD card
  7949. _SD_CLEANUP_BUDGET_SECONDS = 45.0
  7950. async def _cleanup_sd_card_after_print(
  7951. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  7952. ) -> None:
  7953. """Delete a finished print's file from the printer's SD card."""
  7954. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  7955. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  7956. # auto-start files found in root on power cycle, causing ghost prints.
  7957. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  7958. try:
  7959. if subtask_name:
  7960. archive_filename: str | None = None
  7961. async with async_session() as db:
  7962. from backend.app.models.archive import PrintArchive
  7963. from backend.app.models.printer import Printer
  7964. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7965. printer = result.scalar_one_or_none()
  7966. if archive_id:
  7967. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  7968. archive_filename = archive_row.scalar_one_or_none()
  7969. if printer:
  7970. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  7971. from backend.app.utils.filename import derive_remote_filename
  7972. # Primary candidate: the exact path the dispatcher uploaded to
  7973. # (derived from archive.filename via the same rule as upload).
  7974. # Without it, a library row that ended up with a doubled
  7975. # .gcode.3mf (#1542) leaves the real file behind because the
  7976. # subtask_name + ext fallbacks below don't match what's on the
  7977. # SD card. Fallbacks remain for archive-less prints (subtask
  7978. # never resolved to an archive) and for older naming variants.
  7979. candidate_paths: list[str] = []
  7980. if archive_filename:
  7981. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  7982. for ext in (".3mf", ".gcode"):
  7983. fallback = f"/{subtask_name}{ext}"
  7984. if fallback not in candidate_paths:
  7985. candidate_paths.append(fallback)
  7986. # Three outcomes track across all candidates so the final log
  7987. # line reflects what actually happened. The A1 in #1721 always
  7988. # ends here with ``any_not_found=True`` and the others False
  7989. # — its firmware auto-cleans the SD card before our cleanup
  7990. # runs, every candidate FTP-DELE returns 550, and the old
  7991. # code burned 3 retries × 2 s × 3 candidates per print
  7992. # logging a misleading "may linger" WARNING on a successful
  7993. # print.
  7994. any_deleted = False
  7995. any_real_failure = False
  7996. any_not_found = False
  7997. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  7998. for remote_path in candidate_paths:
  7999. if PurePosixPath(remote_path).name.lower() in files_in_use:
  8000. logger.info(
  8001. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  8002. remote_path,
  8003. printer.name,
  8004. )
  8005. continue
  8006. # Retry only the FAILED case — 550 NOT_FOUND will never
  8007. # recover by waiting, so a "file isn't here" answer
  8008. # advances immediately to the next candidate without
  8009. # consuming the retry budget.
  8010. for attempt in range(1, 4):
  8011. try:
  8012. delete_result = await delete_file_async(
  8013. printer.ip_address,
  8014. printer.access_code,
  8015. remote_path,
  8016. printer_model=printer.model,
  8017. )
  8018. except Exception as e:
  8019. delete_result = DeleteResult.FAILED
  8020. logger.warning(
  8021. "SD card cleanup attempt %d/3 raised for %s: %s",
  8022. attempt,
  8023. remote_path,
  8024. e,
  8025. )
  8026. if delete_result == DeleteResult.DELETED:
  8027. any_deleted = True
  8028. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  8029. break
  8030. if delete_result == DeleteResult.NOT_FOUND:
  8031. any_not_found = True
  8032. break # 550 will not recover; try next candidate
  8033. # FAILED: real error — retry with backoff, then give up
  8034. if attempt < 3:
  8035. await asyncio.sleep(2)
  8036. else:
  8037. any_real_failure = True
  8038. logger.warning(
  8039. "SD card cleanup failed after 3 attempts for %s "
  8040. "(network/auth/transient error — file may linger on SD card)",
  8041. remote_path,
  8042. )
  8043. if not any_deleted and not any_real_failure and any_not_found:
  8044. # Every candidate said "not here." Either the printer
  8045. # firmware swept the SD card itself (common on A1) or the
  8046. # dispatcher's upload path doesn't match our candidate
  8047. # rule. Either way: nothing to clean up, no warning.
  8048. logger.debug(
  8049. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  8050. "(printer likely self-cleaned)",
  8051. printer.name,
  8052. )
  8053. except Exception as e:
  8054. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  8055. async def on_print_complete(printer_id: int, data: dict):
  8056. """Handle print completion - update the archive status.
  8057. The printer counts as printing until the print's usage is booked (or this
  8058. ends), so the AMS remain% weight sync can't charge it a second time while
  8059. the usage tracker works (WU-3). Marked before the first await.
  8060. """
  8061. from backend.app.services.usage_tracker import done_completing, mark_completing
  8062. mark_completing(printer_id)
  8063. try:
  8064. await _close_out_print(printer_id, data)
  8065. finally:
  8066. done_completing(printer_id)
  8067. async def _close_out_print(printer_id: int, data: dict):
  8068. import time
  8069. logger = logging.getLogger(__name__)
  8070. start_time = time.time()
  8071. def log_timing(section: str):
  8072. elapsed = time.time() - start_time
  8073. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  8074. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  8075. # A kill-switch stop sends its provider notification immediately. Keep the
  8076. # task so the later notification path can await it and avoid a duplicate;
  8077. # if that immediate attempt failed, the regular completion path retries.
  8078. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  8079. # Last chance before the bytes go: if this print's archive is still an empty
  8080. # fallback and something downloaded the 3MF while it ran, fill the archive in
  8081. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  8082. # below deletes the file (#2957).
  8083. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  8084. # A pending cool-off retry has nothing left to recover for — the cache is
  8085. # about to be dropped and the print is over.
  8086. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  8087. if retry_task and not retry_task.done():
  8088. retry_task.cancel()
  8089. # Drop the 3MF download cache for this printer (#972). The print is over,
  8090. # nothing else legitimately needs the bytes; keeping them would only risk
  8091. # handing a stale file to the next print if it reuses the same name.
  8092. clear_3mf_cache(printer_id)
  8093. try:
  8094. ws_data = {
  8095. "status": data.get("status"),
  8096. "filename": data.get("filename"),
  8097. "subtask_name": data.get("subtask_name"),
  8098. "timelapse_was_active": data.get("timelapse_was_active"),
  8099. }
  8100. await ws_manager.send_print_complete(printer_id, ws_data)
  8101. log_timing("WebSocket send_print_complete")
  8102. except Exception as e:
  8103. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  8104. # Capture user info before clearing (needed for print log entry)
  8105. _print_user_info = printer_manager.get_current_print_user(printer_id)
  8106. # Clear current print user tracking (Issue #206)
  8107. printer_manager.clear_current_print_user(printer_id)
  8108. # If the user explicitly stopped this print from the queue UI the printer will
  8109. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  8110. # correct "print stopped" notification/email is sent instead of a failure alert.
  8111. _raw_status = data.get("status", "completed")
  8112. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  8113. logger.info(
  8114. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  8115. _raw_status,
  8116. printer_id,
  8117. )
  8118. data = {**data, "status": "cancelled"}
  8119. elif printer_id in _kill_switch_stopped and _raw_status in ("failed", "aborted"):
  8120. logger.info(
  8121. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (stopped by the printer kill switch)",
  8122. _raw_status,
  8123. printer_id,
  8124. )
  8125. data = {**data, "status": "cancelled", "_kill_switch": True}
  8126. _user_stopped_printers.discard(printer_id)
  8127. _kill_switch_stopped.discard(printer_id)
  8128. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  8129. # may have left material on the bed: a user can cancel ten hours into a
  8130. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  8131. # touchscreen-stop reports `aborted` rather than `cancelled` because
  8132. # `_user_stopped_printers` is only populated when the user stops via the
  8133. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  8134. # which auto-dispatched the next queued print onto a fouled bed two seconds
  8135. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  8136. # Auto Off power cycles and Bambuddy restarts.
  8137. try:
  8138. notify_live_activities.print_finished(printer_id, data)
  8139. except Exception:
  8140. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  8141. _final_status = data.get("status", "completed")
  8142. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  8143. printer_manager.set_awaiting_plate_clear(printer_id, True)
  8144. # MQTT relay - publish print complete
  8145. try:
  8146. printer_info = printer_manager.get_printer(printer_id)
  8147. if printer_info:
  8148. await mqtt_relay.on_print_complete(
  8149. printer_id,
  8150. printer_info.name,
  8151. printer_info.serial_number,
  8152. data.get("filename", ""),
  8153. data.get("subtask_name", ""),
  8154. data.get("status", "completed"),
  8155. )
  8156. except Exception:
  8157. pass # Don't fail print complete callback if MQTT fails
  8158. filename = data.get("filename", "")
  8159. subtask_name = data.get("subtask_name", "")
  8160. if not filename and not subtask_name:
  8161. # Which print ended can't be told: the printer reported no name since
  8162. # Bambuddy started (a print that failed while preparing, a calibration).
  8163. # Charge nothing, but close the print session, which otherwise kept the
  8164. # AMS weight sync off until the next print (AS-5). A print archived as
  8165. # running is closed and charged by the reconnect reconcile.
  8166. logger.warning("Print complete without filename or subtask_name")
  8167. try:
  8168. from backend.app.services.usage_tracker import discard_session
  8169. async with async_session() as db:
  8170. await discard_session(db, printer_id)
  8171. except Exception as e:
  8172. logger.warning("Failed to clear print session for printer %s: %s", printer_id, e)
  8173. return
  8174. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  8175. # Build list of possible keys to try (matching how they were registered in on_print_start)
  8176. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  8177. # Find the archive for this print
  8178. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  8179. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  8180. archive_id = None
  8181. for key in possible_keys:
  8182. archive_id = _active_prints.pop(key, None)
  8183. if archive_id:
  8184. _owned_print_archive_ids.discard(archive_id)
  8185. logger.info("Found archive %s with key %s", archive_id, key)
  8186. # Also clean up the printer's other keys pointing to this archive;
  8187. # another printer's are a plate of it still printing there.
  8188. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id and k[0] == printer_id]
  8189. for k in keys_to_remove:
  8190. _active_prints.pop(k, None)
  8191. break
  8192. # The archive bound when the print started, before the name search below.
  8193. # Only this one may give the finish-photo plate restore a height (#3240):
  8194. # the search matches names by substring.
  8195. bound_archive_id = archive_id
  8196. if not archive_id and data.get("_reconciled") and data.get("_reconciled_archive_id"):
  8197. # The reconcile names the archive whose run on this printer it
  8198. # closes. Only while that run is open: the print's real end may have
  8199. # closed it meanwhile, or closed the print without managing to write
  8200. # it, and either way there is nothing left to end twice.
  8201. if await _archive_of_open_run(printer_id) != data["_reconciled_archive_id"]:
  8202. logger.info(
  8203. "[RECONCILE] Archive %s has no run open on printer %s any more; nothing to close",
  8204. data["_reconciled_archive_id"],
  8205. printer_id,
  8206. )
  8207. return
  8208. archive_id = data["_reconciled_archive_id"]
  8209. ending_job = str(data.get("subtask_id") or "").strip()
  8210. if not archive_id and ending_job not in ("", "0"):
  8211. # Not bound (a restart since the start): this job's run, open on the
  8212. # printer. Only by its job id: a run open there can be of the print
  8213. # running now, while the end is of an earlier one closed late (the
  8214. # restart's reconcile of a missed end).
  8215. archive_id = await _archive_of_open_run(printer_id, subtask_id=ending_job)
  8216. if archive_id:
  8217. logger.info("Found archive %s by the run of job %s open on printer %s", archive_id, ending_job, printer_id)
  8218. if not archive_id:
  8219. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  8220. async with async_session() as db:
  8221. from backend.app.models.archive import PrintArchive
  8222. # Try matching by subtask_name (stored as print_name) first. The
  8223. # same name rule as the queue's completion check: a name inside
  8224. # another ("Clip" in "Cable Clip") is a different print, and the
  8225. # printer's underscores for spaces and truncation still match.
  8226. if subtask_name:
  8227. printing = await db.scalars(
  8228. select(PrintArchive)
  8229. .where(PrintArchive.printer_id == printer_id)
  8230. .where(PrintArchive.status == "printing")
  8231. .order_by(PrintArchive.created_at.desc())
  8232. )
  8233. # A print started from the printer's screen reports its file
  8234. # name, extensions included, as the subtask (#3009).
  8235. reported = {subtask_name, _subtask_name_from_filename(subtask_name)}
  8236. archive = next(
  8237. (
  8238. candidate
  8239. for candidate in printing
  8240. if any(
  8241. (candidate.print_name and _subtask_names_match(candidate.print_name, name))
  8242. or (
  8243. candidate.filename
  8244. and _subtask_names_match(_subtask_name_from_filename(candidate.filename), name)
  8245. )
  8246. for name in reported
  8247. )
  8248. ),
  8249. None,
  8250. )
  8251. if archive:
  8252. archive_id = archive.id
  8253. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  8254. # Also try by filename
  8255. if not archive_id and filename:
  8256. result = await db.execute(
  8257. select(PrintArchive)
  8258. .where(PrintArchive.printer_id == printer_id)
  8259. .where(PrintArchive.filename == filename)
  8260. .where(PrintArchive.status == "printing")
  8261. .order_by(PrintArchive.created_at.desc())
  8262. .limit(1)
  8263. )
  8264. archive = result.scalar_one_or_none()
  8265. if archive:
  8266. archive_id = archive.id
  8267. # Bounded: a printer whose FTP hangs on DELE took up to 3 candidates x 3
  8268. # attempts x a 60 s timeout, about nine minutes, before the queue item was
  8269. # closed below. The stranded-job closer gives up after five and closed it
  8270. # first, so the job's auto-off and its billing never ran. Inline rather
  8271. # than in the background, so the next job of the same file isn't released
  8272. # (and uploaded under the name being deleted) while the cleanup still
  8273. # works on it. A delete already sent may still finish in its FTP thread
  8274. # after the cutoff, as one past delete_file_async's own timeout always did.
  8275. try:
  8276. await asyncio.wait_for(
  8277. _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger),
  8278. timeout=_SD_CLEANUP_BUDGET_SECONDS,
  8279. )
  8280. except TimeoutError:
  8281. logger.warning(
  8282. "SD card cleanup on printer %s took over %ss; leaving the file there and closing the print",
  8283. printer_id,
  8284. _SD_CLEANUP_BUDGET_SECONDS,
  8285. )
  8286. log_timing("SD card cleanup")
  8287. # Update queue item status early — must run before the archive_id early-return
  8288. # so queue items don't get stuck in "printing" when archive lookup fails.
  8289. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  8290. queue_item_id = None
  8291. billing_run_id: str | None = None
  8292. billing_user_id: int | None = None
  8293. billing_cost_center_id: int | None = None
  8294. billing_plate_id: int | None = None
  8295. queue_status = None
  8296. queue_auto_off = False
  8297. try:
  8298. from backend.app.core.database import run_with_retry
  8299. from backend.app.models.print_queue import PrintQueueItem
  8300. async def _update_queue_status(db):
  8301. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  8302. nonlocal queue_item_id, queue_status, queue_auto_off
  8303. result = await db.execute(
  8304. select(PrintQueueItem)
  8305. .where(PrintQueueItem.printer_id == printer_id)
  8306. .where(PrintQueueItem.status == "printing")
  8307. )
  8308. printing_items = list(result.scalars().all())
  8309. if len(printing_items) > 1:
  8310. logger.warning(
  8311. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  8312. printer_id,
  8313. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  8314. )
  8315. item = printing_items[0] if printing_items else None
  8316. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  8317. return
  8318. if item:
  8319. queue_status = data.get("status", "completed")
  8320. # MQTT sends "aborted" for cancelled prints; normalise to
  8321. # "cancelled" so it matches the queue schema Literal.
  8322. if queue_status == "aborted":
  8323. queue_status = "cancelled"
  8324. item.status = queue_status
  8325. item.completed_at = datetime.now(timezone.utc)
  8326. if queue_status == "failed" and not item.error_message:
  8327. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  8328. # Bump usage counters on the source library file so admins can
  8329. # sort by "last printed" and (eventually) auto-purge stale
  8330. # files — #1008.
  8331. await _bump_library_file_usage_if_completed(db, item, queue_status)
  8332. await db.commit()
  8333. queue_item_id = item.id
  8334. billing_run_id = item.billing_run_id
  8335. billing_user_id = item.created_by_id
  8336. billing_cost_center_id = item.cost_center_id
  8337. billing_plate_id = item.plate_id
  8338. queue_auto_off = item.auto_off_after
  8339. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  8340. await run_with_retry(_update_queue_status, label="queue status update")
  8341. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  8342. # their own sessions and have their own error handling — no retry needed.
  8343. if queue_item_id is not None:
  8344. # Batch orders (#342): this run may have been the last one an order
  8345. # owed. Re-evaluate here rather than lazily on read, so a finished
  8346. # order reports itself complete without someone opening the page.
  8347. try:
  8348. from backend.app.services.print_batch import refresh_batch_status_for_item
  8349. async with async_session() as db:
  8350. await refresh_batch_status_for_item(db, queue_item_id)
  8351. await db.commit()
  8352. except Exception as e:
  8353. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  8354. # MQTT relay - publish queue job completed
  8355. try:
  8356. printer_info = printer_manager.get_printer(printer_id)
  8357. await mqtt_relay.on_queue_job_completed(
  8358. job_id=queue_item_id,
  8359. filename=filename or subtask_name,
  8360. printer_id=printer_id,
  8361. printer_name=printer_info.name if printer_info else "Unknown",
  8362. status=queue_status,
  8363. )
  8364. except Exception:
  8365. pass # Don't fail if MQTT fails
  8366. # Check if queue is now empty and send notification
  8367. try:
  8368. from sqlalchemy import func as sa_func
  8369. async with async_session() as db:
  8370. count_result = await db.execute(
  8371. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  8372. )
  8373. pending_count = count_result.scalar() or 0
  8374. if pending_count == 0:
  8375. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  8376. completed_result = await db.execute(
  8377. select(sa_func.count(PrintQueueItem.id)).where(
  8378. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  8379. PrintQueueItem.completed_at >= today_start,
  8380. )
  8381. )
  8382. completed_count = completed_result.scalar() or 1
  8383. await notification_service.on_queue_completed(
  8384. completed_count=completed_count,
  8385. db=db,
  8386. )
  8387. except Exception:
  8388. pass # Don't fail if notification fails
  8389. # Handle auto_off_after - power off printer if the queue item opted
  8390. # in. Delegates to the smart-plug manager so the off honours each
  8391. # plug's configured strategy (time delay or temperature threshold),
  8392. # is cancelled if the printer starts printing again, and never cuts
  8393. # power on a loaded print (#1890). Previously an inline block here
  8394. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  8395. # timeout regardless of print state — cutting a touchscreen reprint.
  8396. if queue_auto_off:
  8397. try:
  8398. async with async_session() as db:
  8399. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  8400. except Exception as e:
  8401. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  8402. except Exception as e:
  8403. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  8404. log_timing("Queue item update")
  8405. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  8406. # Must run before archive_id early-return so it fires for all prints (including
  8407. # prints started from BambuStudio/touchscreen that have no archive).
  8408. if data.get("status") == "completed":
  8409. try:
  8410. from backend.app.api.routes.settings import get_setting
  8411. async with async_session() as db:
  8412. threshold_str = await get_setting(db, "bed_cooled_threshold")
  8413. threshold = float(threshold_str) if threshold_str else 35.0
  8414. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  8415. async with async_session() as db:
  8416. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  8417. if providers:
  8418. _bed_cool_waiters[printer_id] = {
  8419. "threshold": threshold,
  8420. "filename": filename or subtask_name or "",
  8421. "registered_at": time.time(),
  8422. }
  8423. logger.info(
  8424. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  8425. printer_id,
  8426. threshold,
  8427. )
  8428. else:
  8429. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  8430. except Exception as e:
  8431. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  8432. # Capture the slicer estimate before usage tracking runs. The tracker may
  8433. # update archive.cost with this run's measured cost; billing partial runs
  8434. # against that already-partial value would discount the charge twice.
  8435. billing_planned_grams: float | None = None
  8436. billing_base_cost: float | None = None
  8437. if archive_id:
  8438. try:
  8439. async with async_session() as db:
  8440. from backend.app.models.archive import PrintArchive
  8441. billing_archive = await db.get(PrintArchive, archive_id)
  8442. if billing_archive:
  8443. billing_path = (
  8444. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  8445. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8446. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  8447. billing_archive,
  8448. billing_path,
  8449. billing_plate_id
  8450. if billing_plate_id is not None
  8451. else _get_start_plate_id(printer_id, archive_id),
  8452. )
  8453. except Exception as e:
  8454. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  8455. # --- Track filament consumption (must run before archive_id early-return so usage
  8456. # is recorded even when auto-archive is disabled) ---
  8457. usage_results: list[dict] = []
  8458. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  8459. stored_ams_mapping = data.get("ams_mapping")
  8460. # Fallback to _print_ams_mappings for queue/reprint (set before print starts).
  8461. # Drained either way, like the plate below: left over, it would be read by
  8462. # the archive's next run, dispatched without a mapping.
  8463. registered_ams_mapping = _print_ams_mappings.pop((printer_id, archive_id), None) if archive_id else None
  8464. if not stored_ams_mapping:
  8465. stored_ams_mapping = registered_ams_mapping
  8466. # Always drain the plate_id register on completion — the session already
  8467. # consumed it at print-start injection; leaving it would leak into the next
  8468. # print on the same archive_id (rare but possible with reprints) (#1697).
  8469. # Capture the popped value so the completion notification can scope the
  8470. # archive-level (summed-across-plates per #1593) filament + time totals
  8471. # down to the single plate that was actually printed (#1785).
  8472. notify_plate_id: int | None = None
  8473. if archive_id:
  8474. notify_plate_id = _print_plate_ids.pop((printer_id, archive_id), None)
  8475. # The start estimate must not outlive the real cost written below (COST-4).
  8476. if archive_id:
  8477. await _settle_archive_cost_estimate(archive_id)
  8478. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  8479. try:
  8480. async with async_session() as db:
  8481. from backend.app.api.routes.settings import get_setting
  8482. _spoolman_on = await get_setting(db, "spoolman_enabled")
  8483. if not _spoolman_on or _spoolman_on.lower() != "true":
  8484. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  8485. async with async_session() as db:
  8486. usage_results = await usage_on_print_complete(
  8487. printer_id,
  8488. data,
  8489. printer_manager,
  8490. db,
  8491. archive_id=archive_id,
  8492. ams_mapping=stored_ams_mapping,
  8493. )
  8494. if usage_results:
  8495. await ws_manager.broadcast(
  8496. {
  8497. "type": "spool_usage_logged",
  8498. "printer_id": printer_id,
  8499. "usage": usage_results,
  8500. }
  8501. )
  8502. log_timing("Usage tracker")
  8503. except Exception as e:
  8504. logger.warning("Usage tracker on_print_complete failed: %s", e)
  8505. # Drop the print-start context unconditionally — the Spoolman branch above
  8506. # skips the internal tracker entirely, so nothing else would clear what
  8507. # print start captured, and a row surviving its print would be restored
  8508. # onto the next one after a restart.
  8509. try:
  8510. from backend.app.services.usage_tracker import discard_session
  8511. async with async_session() as db:
  8512. await discard_session(db, printer_id)
  8513. except Exception as e:
  8514. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  8515. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  8516. # A partial run's cost from the Spoolman spools it was charged to; the
  8517. # built-in inventory's comes in usage_results.
  8518. spoolman_run_cost: float | None = None
  8519. if archive_id:
  8520. if data.get("status") == "completed":
  8521. try:
  8522. await _report_spoolman_usage(printer_id, archive_id)
  8523. log_timing("Spoolman usage report")
  8524. except Exception as e:
  8525. logger.warning("Spoolman usage reporting failed: %s", e)
  8526. else:
  8527. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  8528. try:
  8529. async with async_session() as db:
  8530. spoolman_run_cost = await _cleanup_spoolman_tracking(
  8531. printer_id,
  8532. archive_id,
  8533. db,
  8534. last_layer_num=data.get("last_layer_num"),
  8535. last_progress=data.get("last_progress"),
  8536. status=data.get("status") or "failed",
  8537. )
  8538. except Exception as e:
  8539. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  8540. await _release_archived_spoolman_slots(printer_id)
  8541. log_timing("Filament usage tracking")
  8542. if not archive_id:
  8543. # The printer's own calibration run has no archive by design, so this
  8544. # arrives here every time one finishes. Returning before the no-archive
  8545. # notification keeps a calibration from being announced as a finished
  8546. # print. Everything above this point has already run — the plate-clear
  8547. # gate, the queue reconciliation, the SD-card cleanup — so only the
  8548. # notification is skipped.
  8549. if is_internal_printer_job(filename, subtask_name):
  8550. logger.info(
  8551. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  8552. filename,
  8553. subtask_name,
  8554. )
  8555. return
  8556. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  8557. # Still send print-complete/failed/stopped notifications even without an archive.
  8558. # Try to enrich with queue/library-file data so user-specific emails work too.
  8559. async def _notify_no_archive():
  8560. try:
  8561. async with async_session() as db:
  8562. from backend.app.models.library import LibraryFile
  8563. from backend.app.models.print_queue import PrintQueueItem
  8564. from backend.app.models.printer import Printer
  8565. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8566. printer_obj = result.scalar_one_or_none()
  8567. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  8568. # Only the queue item this completion itself closed (the
  8569. # reconciliation above, which checks the run belongs to it).
  8570. # A print started outside Bambuddy closed none, and must not
  8571. # borrow an earlier job's owner, email or times.
  8572. no_archive_data: dict | None = None
  8573. try:
  8574. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  8575. if queue_item:
  8576. no_archive_data = {"created_by_id": queue_item.created_by_id}
  8577. # How long it really ran, as the archive path reports it (#1198).
  8578. started = to_naive_utc(queue_item.started_at)
  8579. ended = to_naive_utc(queue_item.completed_at)
  8580. # Not for a completion reconciled at reconnect: it
  8581. # ended at an unknown time while the printer was
  8582. # offline, and "now" is the reconnect (DB-C9).
  8583. if (
  8584. not data.get("_reconciled")
  8585. and started
  8586. and ended
  8587. and (ended - started).total_seconds() > 0
  8588. ):
  8589. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  8590. # Estimated time: the queue item caches it from its
  8591. # archive or library file; otherwise read the library
  8592. # file's metadata (LibraryFile has no column for it).
  8593. if queue_item.print_time_seconds:
  8594. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  8595. elif queue_item.library_file_id:
  8596. lib_result = await db.execute(
  8597. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  8598. )
  8599. lib_file = lib_result.scalar_one_or_none()
  8600. estimate = (
  8601. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  8602. )
  8603. if estimate:
  8604. no_archive_data["print_time_seconds"] = estimate
  8605. except Exception as lookup_err:
  8606. logger.debug(
  8607. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  8608. )
  8609. # Enrich with usage tracker results (captured in enclosing scope)
  8610. if usage_results:
  8611. if no_archive_data is None:
  8612. no_archive_data = {}
  8613. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8614. if total_from_usage > 0:
  8615. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8616. no_archive_data["usage_results"] = usage_results
  8617. # Try MQTT remaining_time for print duration when no queue/library data
  8618. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  8619. mqtt_remaining = data.get("remaining_time")
  8620. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  8621. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  8622. ps = data.get("status", "completed")
  8623. logger.info(
  8624. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  8625. )
  8626. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8627. await notification_service.on_print_complete(
  8628. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  8629. )
  8630. else:
  8631. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8632. # Send user-specific email if we have a created_by_id
  8633. if no_archive_data and no_archive_data.get("created_by_id"):
  8634. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8635. await _dispatch_user_print_email(
  8636. ps,
  8637. no_archive_data["created_by_id"],
  8638. p_name,
  8639. raw_filename,
  8640. db,
  8641. )
  8642. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  8643. except Exception as e:
  8644. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  8645. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  8646. return
  8647. log_timing("Archive lookup")
  8648. # Update archive status
  8649. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  8650. try:
  8651. async with async_session() as db:
  8652. service = ArchiveService(db)
  8653. status = data.get("status", "completed")
  8654. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  8655. if hms_errors:
  8656. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  8657. failure_reason = derive_failure_reason(status, hms_errors)
  8658. if data.get("_reconciled") and (status == "aborted" or (status == "failed" and not failure_reason)):
  8659. # A reconciled completion closes out a stale archive at
  8660. # reconnect — it is not a user action, so don't mislabel it
  8661. # "userCancelled". It shares the stale-cleanup path's key
  8662. # (issue #2974) and records that the real end time is unknown,
  8663. # which is also why its logged duration is 0 (#2592). A failed
  8664. # one the printer's errors explain keeps their reason (#3310).
  8665. failure_reason = "noStatusUpdate"
  8666. elif data.get("_kill_switch"):
  8667. # Not the user's cancel: the kill switch stopped a print that did
  8668. # not come from Bambuddy.
  8669. failure_reason = "killSwitch"
  8670. if failure_reason:
  8671. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  8672. elif status == "failed" and hms_errors:
  8673. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  8674. await service.update_archive_status(
  8675. archive_id,
  8676. status=status,
  8677. completed_at=(
  8678. # A reconciled completed print ended at an estimated time,
  8679. # not at the reconnect (#3310).
  8680. data.get("_reconciled_completed_at") or datetime.now(timezone.utc)
  8681. if status in ("completed", "failed", "aborted", "cancelled")
  8682. else None
  8683. ),
  8684. failure_reason=failure_reason,
  8685. )
  8686. logger.info(
  8687. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  8688. )
  8689. await ws_manager.send_archive_updated(
  8690. {
  8691. "id": archive_id,
  8692. "status": status,
  8693. }
  8694. )
  8695. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  8696. # MQTT relay - publish archive updated
  8697. try:
  8698. await mqtt_relay.on_archive_updated(
  8699. archive_id=archive_id,
  8700. print_name=filename or subtask_name,
  8701. status=status,
  8702. )
  8703. except Exception:
  8704. pass # Don't fail if MQTT fails
  8705. except Exception as e:
  8706. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  8707. # Continue with other operations even if archive update fails
  8708. log_timing("Archive status update")
  8709. # Apply finance wallet charge or release reservations once. For all partial
  8710. # terminal states (failed, aborted at the printer display, or cancelled via
  8711. # Bambuddy) use this run's measured spool delta, falling back to the last
  8712. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  8713. # estimate and therefore cannot represent an interrupted run.
  8714. try:
  8715. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  8716. async with async_session() as db:
  8717. from backend.app.models.archive import PrintArchive
  8718. from backend.app.services.finance_billing import apply_print_charge_for_archive
  8719. from backend.app.services.print_log import run_being_ended
  8720. archive = await db.get(PrintArchive, archive_id)
  8721. # The run this end fills in below: charged as its own, not as
  8722. # the archive's latest dispatch (another plate of it, maybe).
  8723. charged_run = await run_being_ended(db, archive_id, printer_id, archive.started_at) if archive else None
  8724. if archive and billing_run_id is None and charged_run is None:
  8725. billing_run_id = getattr(archive, "billing_run_id", None)
  8726. if archive and archive.created_by_id is None and _print_user_info:
  8727. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  8728. await db.flush()
  8729. run_status = data.get("status", "completed")
  8730. last_progress = data.get("last_progress")
  8731. if last_progress is None:
  8732. last_progress = data.get("progress")
  8733. actual_run_grams = _compute_run_filament_grams(
  8734. run_status,
  8735. billing_planned_grams,
  8736. last_progress,
  8737. usage_results,
  8738. )
  8739. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  8740. in_memory_cost_center_id = _print_cost_center_ids.pop((printer_id, archive_id), None)
  8741. charged = await apply_print_charge_for_archive(
  8742. db,
  8743. archive_id,
  8744. charged_user_id=billing_user_id,
  8745. cost_center_id=(
  8746. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  8747. ),
  8748. print_queue_id=queue_item_id,
  8749. print_run_id=billing_run_id,
  8750. base_cost_override=billing_base_cost,
  8751. filament_usage=filament_usage,
  8752. run_entry_id=charged_run.id if charged_run is not None else None,
  8753. run_status=run_status,
  8754. )
  8755. await db.commit()
  8756. if charged:
  8757. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  8758. except Exception as e:
  8759. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  8760. printer_info = printer_manager.get_printer(printer_id)
  8761. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8762. billing_filename = filename or subtask_name or "Unknown"
  8763. billing_error = str(e)
  8764. try:
  8765. await ws_manager.broadcast(
  8766. {
  8767. "type": "billing_charge_failed",
  8768. "printer_id": printer_id,
  8769. "printer_name": billing_printer_name,
  8770. "filename": billing_filename,
  8771. "archive_id": archive_id,
  8772. }
  8773. )
  8774. except Exception as notification_error:
  8775. logger.error(
  8776. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  8777. archive_id,
  8778. notification_error,
  8779. )
  8780. async def _notify_billing_charge_failed() -> None:
  8781. try:
  8782. async with async_session() as notification_db:
  8783. await notification_service.on_billing_charge_failed(
  8784. printer_id,
  8785. billing_printer_name,
  8786. billing_filename,
  8787. archive_id,
  8788. billing_error,
  8789. notification_db,
  8790. )
  8791. except Exception as provider_error:
  8792. logger.error(
  8793. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  8794. archive_id,
  8795. provider_error,
  8796. exc_info=True,
  8797. )
  8798. spawn_background_task(
  8799. _notify_billing_charge_failed(),
  8800. name=f"billing-charge-failed-{archive_id}",
  8801. )
  8802. log_timing("Finance charge update")
  8803. # Write independent print log entry (separate table, never touches archives)
  8804. # The run's id, for the energy work below: the archive's newest run is
  8805. # the one started last, which with plates of it on two printers need not
  8806. # be the one that just ended.
  8807. completed_run_id: int | None = None
  8808. async def _write_run(db):
  8809. # Retried on a locked SQLite database: a run left open here would be
  8810. # closed again by the next reconnect's reconcile.
  8811. nonlocal completed_run_id
  8812. from backend.app.models.archive import PrintArchive
  8813. from backend.app.services.print_log import discard_open_runs, record_archive_wear, write_log_entry
  8814. archive = await db.get(PrintArchive, archive_id)
  8815. if archive is None:
  8816. # Deleted while it printed: its run has nothing left to end on.
  8817. discarded = await discard_open_runs(db, printer_id)
  8818. await db.commit()
  8819. await _announce_discarded_runs(discarded, printer_id)
  8820. if archive:
  8821. # Back-fill created_by_id on reprint (#730): reprint reuses the
  8822. # source archive row rather than creating a new one, so an
  8823. # archive that was auto-created from a printer-initiated
  8824. # print (created_by_id=NULL) would otherwise stay unattributed
  8825. # forever. When we have a print-session user AND the archive
  8826. # has no attribution yet, credit the current user. Never
  8827. # overwrite an existing attribution — the original uploader
  8828. # keeps ownership.
  8829. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  8830. if archive.created_by_id is None and _print_user_id is not None:
  8831. archive.created_by_id = _print_user_id
  8832. p_info = printer_manager.get_printer(printer_id)
  8833. # Per-run actuals — written to PrintLogEntry so stats reflect
  8834. # what THIS print actually used, not the source archive's
  8835. # first-run values (#1378). Helper handles the partial-print
  8836. # math (failed / cancelled / stopped get scaled to progress
  8837. # or to tracked spool deltas).
  8838. _run_status = data.get("status", "completed")
  8839. # #2614: scope the per-run estimate to the printed plate. For a
  8840. # multi-plate 3MF dispatched one plate at a time, the archive's
  8841. # filament/cost are the whole-file totals; the PrintLogEntry must
  8842. # reflect only this plate. No effect on single-plate archives (the
  8843. # plate estimate equals the whole-file value) or on the tracker
  8844. # path (measured spool deltas win in _compute_run_filament_grams).
  8845. _est_full_path = (
  8846. app_settings.base_dir / archive.file_path if archive.file_path else None
  8847. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8848. # The plate that printed, as billing reads it: a reprint of
  8849. # another plate must not log the archive's first plate.
  8850. _run_plate_id = billing_plate_id if billing_plate_id is not None else notify_plate_id
  8851. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path, _run_plate_id)
  8852. if _run_plate_id is None:
  8853. _run_plate_id = archive.plate_id
  8854. _run_grams = _compute_run_filament_grams(
  8855. _run_status,
  8856. _est_grams,
  8857. data.get("last_progress", data.get("progress")),
  8858. usage_results,
  8859. )
  8860. # Per-run cost — prefer usage_results sum. For partial prints
  8861. # we deliberately skip the topup-to-estimate logic in
  8862. # usage_tracker (which assumes the print completed); the raw
  8863. # tracked-spool sum is closer to what THIS run actually cost.
  8864. _run_cost: float | None = None
  8865. if usage_results:
  8866. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  8867. if _run_cost is None and _run_status != "completed":
  8868. _run_cost = spoolman_run_cost
  8869. if _run_cost is None and _run_status == "completed":
  8870. _run_cost = _est_cost
  8871. from backend.app.models.printer import Printer as _Printer
  8872. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  8873. run_entry = await write_log_entry(
  8874. db,
  8875. archive_id=archive.id,
  8876. # Captured by _update_queue_status above; None for
  8877. # printer-initiated prints with no queue row. Batch
  8878. # cost/energy roll-up joins on it (#342).
  8879. queue_item_id=queue_item_id,
  8880. status=_run_status,
  8881. print_name=archive.print_name,
  8882. # The plate this run printed, as the estimate above takes
  8883. # it; the archive's own is the latest run's.
  8884. plate_id=_run_plate_id,
  8885. printer_name=p_info.name if p_info else None,
  8886. printer_id=printer_id,
  8887. started_at=archive.started_at,
  8888. completed_at=archive.completed_at,
  8889. filament_type=archive.filament_type,
  8890. filament_color=archive.filament_color,
  8891. filament_used_grams=_run_grams,
  8892. cost=_run_cost,
  8893. wear_cost_per_hour=_wear_rate,
  8894. failure_reason=archive.failure_reason,
  8895. thumbnail_path=archive.thumbnail_path,
  8896. created_by_id=archive.created_by_id,
  8897. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  8898. # Reconciled completions have an unknown real end time —
  8899. # log 0 duration instead of the whole disconnect gap (#2592),
  8900. # unless it was estimated (#3310).
  8901. reconciled=bool(data.get("_reconciled")) and not data.get("_reconciled_completed_at"),
  8902. # Its time is the estimate or nothing, never measured (#3310).
  8903. duration_unmeasured=bool(data.get("_reconciled")),
  8904. # The real end of a print stopped while its printer was offline.
  8905. replaces_offline_stop=True,
  8906. )
  8907. await record_archive_wear(db, archive, run_entry)
  8908. await db.commit()
  8909. completed_run_id = run_entry.id
  8910. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  8911. try:
  8912. from backend.app.core.database import run_with_retry
  8913. await run_with_retry(_write_run, label="print log entry")
  8914. except Exception as e:
  8915. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  8916. await _publish_run_completed(completed_run_id, printer_id)
  8917. log_timing("Print log entry")
  8918. # Run slow operations as background tasks to avoid blocking the event loop
  8919. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  8920. async def _background_energy_calculation():
  8921. """Calculate and save energy usage in background.
  8922. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  8923. backend restart no longer loses per-print energy data).
  8924. """
  8925. try:
  8926. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  8927. async with async_session() as db:
  8928. from backend.app.models.archive import PrintArchive
  8929. from backend.app.models.print_log import PrintLogEntry
  8930. from backend.app.services.print_log import energy_start_of
  8931. archive = await db.get(PrintArchive, archive_id)
  8932. if archive is None:
  8933. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  8934. return
  8935. # The ended run's own start reading: the archive's is its
  8936. # latest start's, maybe another plate's on another printer.
  8937. run_row = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  8938. start = energy_start_of(run_row, archive)
  8939. if start is None:
  8940. logger.info("[ENERGY-BG] No start kWh recorded for archive %s's run", archive_id)
  8941. return
  8942. starting_kwh = start.kwh
  8943. candidates = await energy_plug_candidates(db, printer_id)
  8944. if not candidates:
  8945. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  8946. return
  8947. # Same ordering as the start reading, so the delta below is
  8948. # against the counter that produced `starting_kwh` (#2859).
  8949. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  8950. if selected is None:
  8951. logger.warning(
  8952. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  8953. printer_id,
  8954. ", ".join(plug.name for plug in candidates),
  8955. )
  8956. return
  8957. plug, energy = selected
  8958. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  8959. energy_used = round(energy["total"] - starting_kwh, 4)
  8960. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  8961. if energy_used < 0:
  8962. logger.warning(
  8963. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  8964. archive_id,
  8965. starting_kwh,
  8966. energy["total"],
  8967. )
  8968. return
  8969. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  8970. # Each hour of the print at the price of that hour (#1251). If
  8971. # that fails, the last price known, as before, rather than no
  8972. # energy at all. Read first: the session may be unusable after.
  8973. last_price = await stored_price(db)
  8974. try:
  8975. energy_cost_value = round(
  8976. await print_energy_cost(
  8977. db,
  8978. plug_id=start.plug_id,
  8979. start_at=start.at,
  8980. start_kwh=starting_kwh,
  8981. start_price=start.price,
  8982. end_kwh=energy["total"],
  8983. end_plug_id=plug.id,
  8984. price_now=await current_price(db),
  8985. ),
  8986. 3,
  8987. )
  8988. except Exception as e:
  8989. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  8990. energy_cost_value = round(energy_used * last_price, 3)
  8991. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  8992. # reprint doesn't visually clobber the source archive's energy data
  8993. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  8994. from sqlalchemy import func
  8995. existing_runs = await db.scalar(
  8996. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  8997. )
  8998. if (existing_runs or 0) <= 1:
  8999. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  9000. # we just wrote for THIS print. Either way it's the first run.
  9001. archive.energy_kwh = energy_used
  9002. archive.energy_cost = energy_cost_value
  9003. # The ended run's energy (write_log_entry above ran before this
  9004. # background task, so its energy fields are still NULL). With
  9005. # no run written, none: the archive's newest is another print's.
  9006. if run_row is not None:
  9007. run_row.energy_kwh = energy_used
  9008. run_row.energy_cost = energy_cost_value
  9009. await db.commit()
  9010. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  9011. except Exception as e:
  9012. logger.warning("[ENERGY-BG] Failed: %s", e)
  9013. async def _background_finish_photo() -> str | None:
  9014. """Capture finish photo in background. Returns photo filename if captured."""
  9015. # #2547: set once this function has raised the plate itself (the
  9016. # timelapse path, where the moment producer returned without doing it).
  9017. # Declared out here so the `finally` can lower it again no matter where
  9018. # the capture below fails.
  9019. plate_restored_z: float | None = None
  9020. try:
  9021. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  9022. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  9023. # Read phase: settings + printer + archive in a short session, released
  9024. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  9025. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  9026. # tens of seconds; holding this session across it pinned one pooled
  9027. # connection idle-in-transaction per finishing print (issue #2572).
  9028. async with async_session() as db:
  9029. from backend.app.api.routes.settings import get_setting
  9030. from backend.app.models.archive import PrintArchive
  9031. from backend.app.models.printer import Printer
  9032. capture_enabled = await get_setting(db, "capture_finish_photo")
  9033. if capture_enabled is not None and capture_enabled.lower() != "true":
  9034. return None
  9035. if not archive_id:
  9036. return None
  9037. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  9038. archive = (
  9039. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  9040. ).scalar_one_or_none()
  9041. if not printer or not archive:
  9042. return None
  9043. import uuid
  9044. from datetime import datetime
  9045. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  9046. if not archive.file_path:
  9047. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  9048. archive_dir = resolve_archive_dir(archive)
  9049. photo_filename = None
  9050. # Prefer the timelapse last-frame source when a timelapse was
  9051. # recording — it captures the moment after the toolhead parks
  9052. # but before the bed drops, which the live-camera grab below
  9053. # would miss (#1397). Skipped for external cameras (those have
  9054. # their own framing and don't see a Bambu timelapse). Only
  9055. # runs when the USER explicitly enabled timelapse for this
  9056. # print — #1721 removed Bambuddy's force-on at dispatch
  9057. # because it caused per-layer nozzle parking on Smooth-mode
  9058. # slicer profiles.
  9059. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  9060. printer.external_camera_enabled and printer.external_camera_url
  9061. )
  9062. timelapse_still_pending = False
  9063. if prefer_timelapse_source:
  9064. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  9065. archive_id=archive_id,
  9066. archive_dir=archive_dir,
  9067. rotation=getattr(printer, "camera_rotation", 0),
  9068. run_id=completed_run_id,
  9069. )
  9070. # #1721: replacement framing path — on_finish_photo_moment
  9071. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  9072. # parked, bed not yet dropped) and cached the JPEG bytes in
  9073. # _stage22_finish_frames. Consume them now so the saved photo
  9074. # has the better framing instead of the post-bed-drop angle
  9075. # the live-camera fallback below would give.
  9076. if not photo_filename:
  9077. # #1790: on the FINISH-state fallback path the producer
  9078. # task is dispatched back-to-back with this consumer, so
  9079. # a bare pop would race past with an empty result and
  9080. # the RTSP fallback below would collide with the
  9081. # producer's still-in-flight grab (single-client RTSP
  9082. # on Bambu printers). Wait for the producer to finish
  9083. # or give up before touching the cache.
  9084. #
  9085. # #2547: 20s was enough when the producer only ever grabbed a
  9086. # frame. It now also raises the plate first, which costs the
  9087. # settle window before the grab even starts — so the budget has
  9088. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  9089. # under the notification's own photo wait below.
  9090. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  9091. if in_flight is not None:
  9092. try:
  9093. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  9094. except TimeoutError:
  9095. logger.warning(
  9096. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  9097. printer_id,
  9098. )
  9099. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  9100. if cached_frame:
  9101. # Already rotated by the producer (#2708) — rotating again
  9102. # here would undo the fix on the banked-frame path, whose
  9103. # bytes reach the cache having been rotated once already.
  9104. photos_dir = archive_dir / "photos"
  9105. photos_dir.mkdir(parents=True, exist_ok=True)
  9106. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9107. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9108. photo_path = photos_dir / photo_filename
  9109. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  9110. logger.info(
  9111. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  9112. photo_filename,
  9113. len(cached_frame),
  9114. )
  9115. # #2547: the timelapse path reaches the live grab below whenever the
  9116. # video hasn't landed in time — the documented usual outcome on
  9117. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  9118. # returned early for those prints without raising the plate, so
  9119. # without this the photo that actually ships in the notification is
  9120. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  9121. # asked us to fix. The archive still gets the better video frame
  9122. # later; this is about the image the user is sent.
  9123. #
  9124. # Gated on `timelapse_was_active` precisely because that is the
  9125. # condition under which the producer skipped. On every other path it
  9126. # has already raised and lowered the plate, and repeating that here
  9127. # would be a second pointless round trip.
  9128. if (
  9129. not photo_filename
  9130. and data.get("timelapse_was_active")
  9131. and not print_dispatch_context.end_gcode_injected(printer_id)
  9132. ):
  9133. try:
  9134. async with async_session() as db:
  9135. from backend.app.api.routes.settings import get_setting
  9136. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  9137. if restore_setting is None or restore_setting.lower() == "true":
  9138. max_z = await _max_z_for_current_print(
  9139. printer_id, data, logger, bound_archive_id, notify_plate_id
  9140. )
  9141. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  9142. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  9143. plate_restored_z = max_z
  9144. except Exception as e:
  9145. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  9146. # Fallback chain: external camera → buffered live frame →
  9147. # fresh RTSP capture. Only runs if the timelapse path above
  9148. # didn't already produce a photo.
  9149. # Chamber light for the live capture below (#1655).
  9150. async with camera_light(printer if not photo_filename else None):
  9151. if not photo_filename:
  9152. if printer.external_camera_enabled and printer.external_camera_url:
  9153. logger.info("[PHOTO-BG] Using external camera")
  9154. from backend.app.api.routes.camera import live_frame_for_capture
  9155. from backend.app.services.external_camera import capture_frame
  9156. # #2707: the second half of the finish-photo failure — the
  9157. # pre-capture and this fallback both collided with the live
  9158. # view. None here continues down the fallback chain.
  9159. defer, buffered = live_frame_for_capture(printer_id)
  9160. if defer:
  9161. frame_data = buffered
  9162. else:
  9163. frame_data = await capture_frame(
  9164. printer.external_camera_url,
  9165. printer.external_camera_type or "mjpeg",
  9166. snapshot_url=printer.external_camera_snapshot_url,
  9167. )
  9168. if frame_data:
  9169. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  9170. photos_dir = archive_dir / "photos"
  9171. photos_dir.mkdir(parents=True, exist_ok=True)
  9172. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9173. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9174. photo_path = photos_dir / photo_filename
  9175. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  9176. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  9177. else:
  9178. # Check if camera stream is active - use buffered frame to avoid freeze
  9179. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  9180. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  9181. active_chamber_for_printer = [
  9182. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  9183. ]
  9184. buffered_frame = get_buffered_frame(printer_id)
  9185. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  9186. # Use frame from active stream
  9187. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  9188. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  9189. photos_dir = archive_dir / "photos"
  9190. photos_dir.mkdir(parents=True, exist_ok=True)
  9191. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9192. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9193. photo_path = photos_dir / photo_filename
  9194. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  9195. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  9196. else:
  9197. # No active stream - capture new frame
  9198. from backend.app.services.camera import capture_finish_photo
  9199. photo_filename = await capture_finish_photo(
  9200. printer_id=printer_id,
  9201. ip_address=printer.ip_address,
  9202. access_code=printer.access_code,
  9203. model=printer.model,
  9204. archive_dir=archive_dir,
  9205. rotation=getattr(printer, "camera_rotation", 0),
  9206. )
  9207. # Write phase: attach the photo in a fresh short-lived session.
  9208. if photo_filename:
  9209. async with async_session() as db:
  9210. from backend.app.models.archive import PrintArchive
  9211. from backend.app.services.print_log import add_run_photo, run_of
  9212. arch = await db.get(PrintArchive, archive_id)
  9213. # The ended print's own list takes it too: the archive's
  9214. # holds every print's.
  9215. run = await run_of(db, archive_id, completed_run_id) if completed_run_id is not None else None
  9216. if arch is not None:
  9217. photos = arch.photos or []
  9218. photos.append(photo_filename)
  9219. arch.photos = photos
  9220. add_run_photo(run, photo_filename)
  9221. await db.commit()
  9222. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  9223. # The short wait above is bounded so a slow printer can't hold up
  9224. # the print-complete notification, which is what the caller is
  9225. # blocking on. When it ran out with the video still on its way,
  9226. # keep waiting off to the side and add the better frame to the
  9227. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  9228. # users, whose videos routinely take minutes to transfer, never get
  9229. # the pre-bed-drop framing this path exists to provide.
  9230. #
  9231. # Spawned here rather than at the point the wait gave up: both this
  9232. # function and the upgrade do a read-modify-write on `photos`, and
  9233. # the live-camera fallback above can take tens of seconds. Starting
  9234. # the upgrade before that write means the two can interleave and one
  9235. # silently drops the other's entry, leaving a JPEG on disk that the
  9236. # gallery never lists.
  9237. if timelapse_still_pending:
  9238. from backend.app.services import archive_work
  9239. spawn_background_task(
  9240. archive_work.held_while(
  9241. archive_id,
  9242. _upgrade_finish_photo_from_timelapse(
  9243. archive_id,
  9244. archive_dir,
  9245. rotation=getattr(printer, "camera_rotation", 0),
  9246. run_id=completed_run_id,
  9247. ),
  9248. ),
  9249. name=f"finish-photo-upgrade-{archive_id}",
  9250. )
  9251. return photo_filename
  9252. except Exception as e:
  9253. logger.warning("[PHOTO-BG] Failed: %s", e)
  9254. return None
  9255. finally:
  9256. # #2547: we raised the plate, so we owe the move back down — even if
  9257. # the capture in between threw. Otherwise the user finds the print
  9258. # pinned under the nozzle.
  9259. if plate_restored_z is not None:
  9260. try:
  9261. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  9262. except Exception as e:
  9263. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  9264. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  9265. # Photo capture task - result will be used by notifications
  9266. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  9267. log_timing("Background tasks scheduled (energy, photo)")
  9268. # Also run smart plug, notifications, and maintenance as background tasks
  9269. print_status = data.get("status", "completed")
  9270. async def _background_smart_plug():
  9271. """Handle smart plug automation in background."""
  9272. try:
  9273. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  9274. async with async_session() as db:
  9275. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  9276. logger.info("[AUTO-OFF-BG] Completed")
  9277. except Exception as e:
  9278. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  9279. async def _background_notifications(finish_photo_filename: str | None = None):
  9280. """Send print complete notifications in background."""
  9281. try:
  9282. logger.info(
  9283. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  9284. )
  9285. async with async_session() as db:
  9286. from backend.app.models.archive import PrintArchive
  9287. from backend.app.models.printer import Printer
  9288. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9289. printer = result.scalar_one_or_none()
  9290. printer_name = printer.name if printer else f"Printer {printer_id}"
  9291. archive_data = None
  9292. if archive_id:
  9293. from backend.app.models.print_log import PrintLogEntry
  9294. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  9295. archive = archive_result.scalar_one_or_none()
  9296. # The run that ended: the archive shows its latest, which
  9297. # with another plate of it printing elsewhere is not this.
  9298. run = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  9299. run_started = run.started_at if run is not None else archive.started_at if archive else None
  9300. run_completed = run.completed_at if run is not None else archive.completed_at if archive else None
  9301. if archive:
  9302. # Actual elapsed time from started_at/completed_at when both are
  9303. # populated (every terminal status sets completed_at after #1198).
  9304. # Falls back to None so the notification path can decide whether to
  9305. # render the slicer estimate as a last resort.
  9306. actual_time_seconds = None
  9307. # Unknown for a completion reconciled at reconnect: the
  9308. # print ended while the printer was offline and
  9309. # completed_at is the reconnect, so the gap would read
  9310. # as the duration -- 14 h for a night offline (DB-C9).
  9311. # An estimated end (#3310) gives the estimate.
  9312. if (
  9313. run_started
  9314. and run_completed
  9315. and (not data.get("_reconciled") or data.get("_reconciled_completed_at"))
  9316. ):
  9317. elapsed = (run_completed - run_started).total_seconds()
  9318. if elapsed > 0:
  9319. actual_time_seconds = int(elapsed)
  9320. archive_data = {
  9321. "print_time_seconds": archive.print_time_seconds,
  9322. "actual_time_seconds": actual_time_seconds,
  9323. "actual_filament_grams": archive.filament_used_grams,
  9324. "failure_reason": run.failure_reason if run is not None else archive.failure_reason,
  9325. "created_by_id": archive.created_by_id,
  9326. }
  9327. # Scale filament usage for partial prints
  9328. if print_status != "completed" and archive.filament_used_grams:
  9329. progress = data.get("progress") or 0
  9330. scale = _partial_progress_scale(progress)
  9331. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  9332. archive_data["progress"] = progress
  9333. # Pass per-slot data from archive.extra_data
  9334. if archive.extra_data and archive.extra_data.get("filament_slots"):
  9335. slots = archive.extra_data["filament_slots"]
  9336. if print_status != "completed":
  9337. scale = _partial_progress_scale(data.get("progress"))
  9338. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  9339. archive_data["filament_slots"] = slots
  9340. # Scope project-summed totals down to the plate that was
  9341. # actually printed — see _scope_notification_archive_data_to_plate
  9342. # for the why (#1785).
  9343. archive_data = _scope_notification_archive_data_to_plate(
  9344. archive_data,
  9345. archive.file_path,
  9346. notify_plate_id,
  9347. print_status,
  9348. data.get("progress"),
  9349. app_settings.base_dir,
  9350. )
  9351. # Enrich filament_grams from usage_results when archive has no 3MF data
  9352. if not archive_data.get("actual_filament_grams") and usage_results:
  9353. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  9354. if total_from_usage > 0:
  9355. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  9356. # Pass usage tracker results for AMS slot info in notifications
  9357. if usage_results:
  9358. archive_data["usage_results"] = usage_results
  9359. # Which archive and print it was (archive redesign).
  9360. archive_data["archive_id"] = archive_id
  9361. archive_data["run_id"] = completed_run_id
  9362. # Add finish photo URL and image bytes if available
  9363. if finish_photo_filename:
  9364. photo_url, photo_bytes = await _finish_photo_for_notification(
  9365. db, archive, archive_id, finish_photo_filename
  9366. )
  9367. if photo_url:
  9368. archive_data["finish_photo_url"] = photo_url
  9369. if photo_bytes:
  9370. archive_data["image_data"] = photo_bytes
  9371. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  9372. await notification_service.on_print_complete(
  9373. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  9374. )
  9375. else:
  9376. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  9377. # Post-print outcome confirmation (#1898). Runs in this
  9378. # background task so the finish photo fetched above rides
  9379. # along with the prompt.
  9380. if print_status == "completed" and archive_id:
  9381. await _dispatch_outcome_confirmation_safely(
  9382. db, printer_id, printer_name, data, archive_id, archive_data, run_id=completed_run_id
  9383. )
  9384. # Send user-specific email notification
  9385. if archive_data:
  9386. created_by_id = archive_data.get("created_by_id")
  9387. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  9388. await _dispatch_user_print_email(
  9389. print_status,
  9390. created_by_id,
  9391. printer_name,
  9392. raw_filename,
  9393. db,
  9394. image_data=archive_data.get("image_data"),
  9395. finish_photo_url=archive_data.get("finish_photo_url"),
  9396. )
  9397. logger.info("[NOTIFY-BG] Completed")
  9398. except Exception as e:
  9399. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  9400. async def _background_maintenance_check():
  9401. """Check for maintenance due in background."""
  9402. if print_status != "completed":
  9403. return
  9404. try:
  9405. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  9406. async with async_session() as db:
  9407. from backend.app.models.printer import Printer
  9408. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9409. printer = result.scalar_one_or_none()
  9410. printer_name = printer.name if printer else f"Printer {printer_id}"
  9411. await ensure_default_types(db)
  9412. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  9413. attention = [
  9414. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  9415. ]
  9416. items_needing_attention = [
  9417. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  9418. for item in attention
  9419. ]
  9420. if items_needing_attention:
  9421. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  9422. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  9423. # MQTT relay - publish maintenance alerts
  9424. for item in attention:
  9425. current_value, threshold, unit = maintenance_alert_values(item)
  9426. try:
  9427. await mqtt_relay.on_maintenance_alert(
  9428. printer_id=printer_id,
  9429. printer_name=printer_name,
  9430. maintenance_type=item.maintenance_type_name,
  9431. current_value=current_value,
  9432. threshold=threshold,
  9433. unit=unit,
  9434. )
  9435. except Exception:
  9436. pass # Don't fail if MQTT fails
  9437. else:
  9438. logger.info("[MAINT-BG] Completed (no items need attention)")
  9439. except Exception as e:
  9440. logger.warning("[MAINT-BG] Failed: %s", e)
  9441. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  9442. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  9443. # Notification task waits for photo capture to complete first (with timeout).
  9444. # When a timelapse was recording, photo sourcing polls the per-print
  9445. # timelapse for up to 60s (#1397) — extend the budget so the notification
  9446. # carries the correct bed-up photo instead of falling through to the
  9447. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  9448. #
  9449. # #2547: both budgets now have to cover a plate restore as well.
  9450. #
  9451. # Without timelapse, the wait is on the moment producer, which raises the
  9452. # plate before its grab — so this has to outlast that producer's own budget.
  9453. #
  9454. # With timelapse, the capture polls up to
  9455. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  9456. # falls back to a live grab, which is the case that raises the plate. At the
  9457. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  9458. # restore would have moved the plate for a photo nobody waited for.
  9459. photo_wait_timeout = (
  9460. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  9461. if data.get("timelapse_was_active")
  9462. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  9463. )
  9464. async def _photo_then_notify():
  9465. """Wait for photo capture, then send notification with photo URL."""
  9466. finish_photo = None
  9467. try:
  9468. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  9469. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  9470. except TimeoutError:
  9471. logger.warning(
  9472. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  9473. photo_wait_timeout,
  9474. )
  9475. except Exception as e:
  9476. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  9477. try:
  9478. await _background_notifications(finish_photo)
  9479. except Exception as e:
  9480. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  9481. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  9482. # Stitch external camera layer timelapse if session was active
  9483. print_status = data.get("status", "completed")
  9484. async def _background_layer_timelapse():
  9485. """Stitch layer timelapse and attach to archive."""
  9486. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  9487. try:
  9488. if print_status == "completed":
  9489. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  9490. # The run the frames belong to, read before the stitch: it can
  9491. # take long enough for the archive to start printing again.
  9492. run_started_at = None
  9493. if archive_id:
  9494. async with async_session() as db:
  9495. run_archive = await ArchiveService(db).get_archive(archive_id)
  9496. run_started_at = run_archive.started_at if run_archive else None
  9497. timelapse_path = await tl_complete(printer_id)
  9498. if timelapse_path and archive_id:
  9499. await _attach_layer_timelapse(
  9500. archive_id, timelapse_path, notify_plate_id, run_started_at, run_id=completed_run_id
  9501. )
  9502. elif timelapse_path:
  9503. # Timelapse created but no archive - just clean up
  9504. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  9505. else:
  9506. # Print failed or cancelled - cancel timelapse session
  9507. cancel_session(printer_id)
  9508. logger.info(
  9509. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  9510. )
  9511. except Exception as e:
  9512. logger.warning("[LAYER-TL] Failed: %s", e)
  9513. # A completed print's session left _active_sessions when its stitch
  9514. # began: the one there now belongs to the next print, which may have
  9515. # started during the stitch, and must not lose its frames.
  9516. if print_status != "completed":
  9517. try:
  9518. cancel_session(printer_id)
  9519. except Exception:
  9520. pass # Best-effort timelapse session cancellation on error
  9521. from backend.app.services import archive_work
  9522. # Held through the stitch, which can take longer than a merge waits after
  9523. # a print (archive redesign P2).
  9524. layer_timelapse = _background_layer_timelapse()
  9525. if archive_id:
  9526. layer_timelapse = archive_work.held_while(archive_id, layer_timelapse)
  9527. spawn_background_task(layer_timelapse, name="background-layer-timelapse")
  9528. log_timing("All background tasks scheduled")
  9529. # Auto-scan for timelapse if recording was active during the print
  9530. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  9531. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  9532. # Schedule timelapse scan as background task with retries
  9533. # The printer needs time to encode the video after print completion
  9534. _schedule_timelapse_scan(archive_id, printer_id, plate_id=notify_plate_id, run_id=completed_run_id)
  9535. log_timing("Timelapse scan scheduled")
  9536. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  9537. # AMS sensor history recording
  9538. _ams_history_task: asyncio.Task | None = None
  9539. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  9540. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  9541. def _retention_days(stored: str | None, default: int) -> int:
  9542. """A history retention setting as days to keep: at least 1, the default
  9543. when unset or unreadable. A stored 0 or less (the API took one before it
  9544. had a minimum) would put the cutoff at now and delete all history."""
  9545. try:
  9546. return max(1, int(stored)) if stored is not None else default
  9547. except (TypeError, ValueError):
  9548. return default
  9549. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  9550. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  9551. _ams_alarm_cooldown: dict[str, datetime] = {}
  9552. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  9553. # (printer_id, ams_id) already reported as sending the drop index and no
  9554. # percentage. Logged once each so a supported printer that turns out to do this
  9555. # shows up in a support bundle rather than as a user wondering where the
  9556. # humidity reading went -- see the note at the read site below (#3140).
  9557. _ams_index_only_logged: set[tuple[int, int]] = set()
  9558. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  9559. """Temperature at which the AMS alarm fires, falling back to the display band.
  9560. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  9561. when a notification was sent as well, which is why a room above it made the
  9562. alarm fire once an hour for as long as the weather lasted -- and the only way
  9563. to stop that was to raise the display band and lose the colour that says the
  9564. unit is warm (#2905).
  9565. Unset resolves to the fair threshold, so an install that never sets one is
  9566. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  9567. so that arrives here as a string and is handled by the same branch as any
  9568. other unparseable value -- there is no separate sentinel to keep in sync.
  9569. A non-positive value is refused rather than honoured: zero would alarm
  9570. permanently, and it is far more likely to be a cleared field than a
  9571. deliberate choice.
  9572. """
  9573. if raw_alarm_value is None:
  9574. return fair_threshold
  9575. try:
  9576. value = float(raw_alarm_value)
  9577. except (TypeError, ValueError):
  9578. return fair_threshold
  9579. if not math.isfinite(value) or value <= 0:
  9580. return fair_threshold
  9581. return value
  9582. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  9583. # through a cycle and the cool-down after it (#1802). Stored in the settings
  9584. # table rather than alongside _ams_alarm_cooldown above, because a restart
  9585. # partway through a cool-down would otherwise resume alarming about heat the
  9586. # user asked for — the same internal-timestamp-row pattern as
  9587. # support.py's debug_logging_enabled_at.
  9588. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  9589. # Upper bound on that suppression. The latch normally clears as soon as the unit
  9590. # reads at or below the threshold; see utils.ams_drying for why this cap only
  9591. # matters when it never does.
  9592. AMS_DRYING_GRACE_MINUTES = 120
  9593. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  9594. """Read the persisted per-AMS drying latch, dropping entries out of window.
  9595. Anything older than the grace cap would expire on its next visit anyway, so
  9596. discarding it here costs nothing and stops rows for deleted printers from
  9597. accumulating.
  9598. Stamps ahead of now get two defences, because a box whose clock jumps
  9599. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  9600. ones are discarded outright, and the rest are clamped to now. Without the
  9601. clamp the cap would measure from a moment that has not happened yet and hold
  9602. the alarm quiet for the skew on top of the cap. One unnecessary notification
  9603. after a clock jump is a far better failure than an alarm silently disabled
  9604. for hours.
  9605. """
  9606. from backend.app.models.settings import Settings
  9607. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9608. setting = result.scalar_one_or_none()
  9609. if not setting or not setting.value:
  9610. return {}
  9611. try:
  9612. raw = json.loads(setting.value)
  9613. except (ValueError, TypeError):
  9614. return {} # Corrupted row → no latch, alarms behave as they did before
  9615. if not isinstance(raw, dict):
  9616. return {}
  9617. now = datetime.now(timezone.utc)
  9618. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  9619. latch: dict[str, datetime] = {}
  9620. for key, value in raw.items():
  9621. try:
  9622. stamp = datetime.fromisoformat(str(value))
  9623. except (ValueError, TypeError):
  9624. continue
  9625. if stamp.tzinfo is None:
  9626. stamp = stamp.replace(tzinfo=timezone.utc)
  9627. if not (now - window <= stamp <= now + window):
  9628. continue
  9629. # Nothing may sit in the future: suppression is measured as now minus
  9630. # the stamp, so a stamp ahead of now would extend it by the skew on top
  9631. # of the cap. Clamping the survivors keeps the cap an actual cap.
  9632. latch[str(key)] = min(stamp, now)
  9633. return latch
  9634. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  9635. """Persist the latch, writing only when it actually changed.
  9636. Adds the session change but does not commit — the caller's own commit
  9637. carries it, so the latch lands in the same transaction as the sensor rows
  9638. that produced it.
  9639. """
  9640. from backend.app.models.settings import Settings
  9641. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  9642. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9643. setting = result.scalar_one_or_none()
  9644. if setting is None:
  9645. # Don't create the row on installs that never dry anything.
  9646. if payload != "{}":
  9647. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  9648. elif setting.value != payload:
  9649. setting.value = payload
  9650. def _ams_has_filament(ams_data: dict) -> bool:
  9651. """True if this AMS unit has at least one tray slot holding filament.
  9652. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  9653. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  9654. still report sensor readings, but those readings are ambient and not
  9655. actionable: no filament to dry, no humidity to push down. #1619 — gate
  9656. humidity/temperature alarms on this check so empty units don't generate
  9657. hourly noise. Sensor history still records regardless so the UI charts
  9658. stay continuous.
  9659. Fallback path inspects the `tray` array's `tray_type` fields for setups
  9660. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  9661. """
  9662. bits = ams_data.get("tray_exist_bits")
  9663. if isinstance(bits, str) and bits.strip():
  9664. try:
  9665. return int(bits, 16) > 0
  9666. except ValueError:
  9667. pass
  9668. trays = ams_data.get("tray")
  9669. if isinstance(trays, list):
  9670. return any(
  9671. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  9672. )
  9673. return False
  9674. async def record_ams_history():
  9675. """Background task to record AMS humidity and temperature data."""
  9676. logger = logging.getLogger(__name__)
  9677. # Wait a short time for MQTT connections to establish on startup
  9678. await asyncio.sleep(10)
  9679. while True:
  9680. try:
  9681. from backend.app.models.ams_history import AMSSensorHistory
  9682. from backend.app.models.printer import Printer
  9683. from backend.app.models.settings import Settings
  9684. async with async_session() as db:
  9685. # Get all active printers
  9686. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9687. printers = result.scalars().all()
  9688. # Get alarm thresholds from settings
  9689. humidity_threshold = 60.0 # Default: fair threshold
  9690. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  9691. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  9692. setting = result.scalar_one_or_none()
  9693. if setting:
  9694. try:
  9695. humidity_threshold = float(setting.value)
  9696. except (ValueError, TypeError):
  9697. pass # Keep default threshold if stored value is invalid
  9698. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  9699. setting = result.scalar_one_or_none()
  9700. if setting:
  9701. try:
  9702. temp_fair_threshold = float(setting.value)
  9703. except (ValueError, TypeError):
  9704. pass # Keep default threshold if stored value is invalid
  9705. # The alarm gets its own threshold, seeded from the resolved fair
  9706. # value so an install that has never set one behaves exactly as
  9707. # it did before (#2905). ams_temp_fair decides when the card turns
  9708. # amber; 35 C is a reasonable place to change a colour and not a
  9709. # reasonable place to page someone. A room above it makes the
  9710. # alarm fire once an hour for as long as the weather lasts, and
  9711. # the only way to stop it was to raise the display band and lose
  9712. # the colour that says the unit is warm.
  9713. #
  9714. # An unset value is stored as the literal "None", which the except
  9715. # below swallows the same way it swallows garbage -- so the
  9716. # fallback costs nothing and needs no sentinel of its own.
  9717. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  9718. setting = result.scalar_one_or_none()
  9719. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  9720. temp_fair_threshold, setting.value if setting else None
  9721. )
  9722. # Per-filament humidity threshold overrides (#1605) — resolved
  9723. # per-AMS below from the loaded tray types. Reuses the same
  9724. # resolver as the auto-drying scheduler so behavior stays in
  9725. # lockstep across both consumers.
  9726. from backend.app.services.print_scheduler import PrintScheduler
  9727. per_type_humidity_thresholds: dict[str, int] = {}
  9728. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  9729. setting = result.scalar_one_or_none()
  9730. if setting and setting.value:
  9731. try:
  9732. raw = json.loads(setting.value)
  9733. if isinstance(raw, dict):
  9734. for k, v in raw.items():
  9735. try:
  9736. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  9737. v
  9738. )
  9739. except (TypeError, ValueError):
  9740. continue
  9741. except (ValueError, TypeError):
  9742. pass # Invalid JSON → no overrides, fall through to global threshold
  9743. # Per-AMS drying latch (#1802), loaded once per pass and written
  9744. # back below only if a unit changed it.
  9745. drying_latch = await _load_ams_drying_latch(db)
  9746. drying_latch_before = dict(drying_latch)
  9747. recorded_count = 0
  9748. for printer in printers:
  9749. # Get current state from printer manager
  9750. state = printer_manager.get_status(printer.id)
  9751. if not state or not state.connected or not state.raw_data:
  9752. continue # Skip disconnected printers - don't use stale data
  9753. raw_data = state.raw_data
  9754. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  9755. continue
  9756. # Record data for each AMS unit
  9757. for ams_data in raw_data["ams"]:
  9758. ams_id = int(ams_data.get("id", 0))
  9759. # Percentage only. The 1-5 index is inverted, so
  9760. # charting it as a percentage drew the wettest units as
  9761. # the driest (#3140); a unit that reports no percentage
  9762. # leaves a gap in the chart instead. See
  9763. # utils/ams_humidity.
  9764. humidity = ams_humidity_percent(ams_data)
  9765. # No supported printer is known to send the index
  9766. # alone -- the report came from unsupported firmware,
  9767. # and no install has been seen using the old fallback.
  9768. # "Known" is doing work there, so say so once per unit:
  9769. # the alternative is a silent blank card.
  9770. if humidity is None and ams_data.get("humidity") is not None:
  9771. unit_key = (printer.id, ams_id)
  9772. if unit_key not in _ams_index_only_logged:
  9773. _ams_index_only_logged.add(unit_key)
  9774. logger.info(
  9775. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  9776. "percentage. The index is inverted and is not shown as a percentage "
  9777. "(#3140), so this unit has no humidity reading, chart or alarm. "
  9778. "Please report this with the printer and AMS firmware versions.",
  9779. printer.name,
  9780. ams_id,
  9781. )
  9782. # Get temperature
  9783. temperature = None
  9784. temp_str = ams_data.get("temp")
  9785. if temp_str is not None:
  9786. try:
  9787. temperature = float(temp_str)
  9788. except (ValueError, TypeError):
  9789. pass # Skip unparseable temperature value
  9790. # Skip if no data
  9791. if humidity is None and temperature is None:
  9792. continue
  9793. # Record the data point
  9794. history = AMSSensorHistory(
  9795. printer_id=printer.id,
  9796. ams_id=ams_id,
  9797. humidity=humidity,
  9798. # Both columns hold the same reading now that the
  9799. # index can no longer reach ``humidity``. Writing it
  9800. # through the same value also stops a genuine 0%
  9801. # from being stored as NULL, which the old truthiness
  9802. # test did.
  9803. humidity_raw=humidity,
  9804. temperature=temperature,
  9805. )
  9806. db.add(history)
  9807. recorded_count += 1
  9808. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  9809. is_ams_ht = ams_id >= 128
  9810. if is_ams_ht:
  9811. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  9812. else:
  9813. ams_label = f"AMS-{chr(65 + ams_id)}"
  9814. # Skip alarm dispatch for empty AMS units — humidity /
  9815. # temperature readings are ambient with no filament to
  9816. # protect, and the hourly notification just becomes
  9817. # noise. Sensor history was already recorded above so
  9818. # the UI charts stay continuous (#1619). Per-AMS check
  9819. # so a multi-AMS setup with one loaded + one empty
  9820. # still alarms on the loaded unit.
  9821. if not _ams_has_filament(ams_data):
  9822. continue
  9823. # Resolve per-filament humidity threshold for this AMS
  9824. # unit (#1605). Falls back to the global ams_humidity_fair
  9825. # when no per-type overrides are configured.
  9826. trays = ams_data.get("tray", []) or []
  9827. effective_humidity_threshold = float(
  9828. PrintScheduler.resolve_humidity_threshold(
  9829. trays, per_type_humidity_thresholds, int(humidity_threshold)
  9830. )
  9831. )
  9832. # Check humidity alarm (only if above threshold)
  9833. if humidity is not None and humidity > effective_humidity_threshold:
  9834. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  9835. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9836. now = datetime.now(timezone.utc)
  9837. if (
  9838. last_alarm is None
  9839. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9840. ):
  9841. _ams_alarm_cooldown[cooldown_key] = now
  9842. logger.info(
  9843. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  9844. )
  9845. try:
  9846. # Call different notification method based on AMS type
  9847. if is_ams_ht:
  9848. await notification_service.on_ams_ht_humidity_high(
  9849. printer.id,
  9850. printer.name,
  9851. ams_label,
  9852. humidity,
  9853. effective_humidity_threshold,
  9854. db,
  9855. )
  9856. else:
  9857. await notification_service.on_ams_humidity_high(
  9858. printer.id,
  9859. printer.name,
  9860. ams_label,
  9861. humidity,
  9862. effective_humidity_threshold,
  9863. db,
  9864. )
  9865. except Exception as e:
  9866. logger.warning("Failed to send humidity alarm: %s", e)
  9867. # A drying cycle heats the unit far past ams_temp_fair on
  9868. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  9869. # AMS-HT, against a 35 C default — so the alarm fired
  9870. # once an hour for the whole cycle and kept firing while
  9871. # the unit cooled back down (#1802). Latch on the
  9872. # firmware's own drying state and hold until the reading
  9873. # returns to normal. Humidity is deliberately left alone:
  9874. # it falls during drying, which is the whole point.
  9875. latch_key = f"{printer.id}:{ams_id}"
  9876. # The latch releases at `threshold`, so it takes the alarm
  9877. # number too. Handing it the display band would strand the
  9878. # latch on any unit that settles back above it -- a room
  9879. # where the AMS rests at 37.7 C never returns under a 35 C
  9880. # band, so the latch could only expire on the grace cap
  9881. # rather than releasing when the unit had actually cooled.
  9882. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  9883. drying_active=is_drying_active(ams_data),
  9884. temperature=temperature,
  9885. threshold=temp_alarm_threshold,
  9886. latched_at=drying_latch.get(latch_key),
  9887. now=datetime.now(timezone.utc),
  9888. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  9889. )
  9890. if new_latch is None:
  9891. drying_latch.pop(latch_key, None)
  9892. else:
  9893. drying_latch[latch_key] = new_latch
  9894. # Check temperature alarm (only if above threshold)
  9895. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  9896. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  9897. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9898. now = datetime.now(timezone.utc)
  9899. if (
  9900. last_alarm is None
  9901. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9902. ):
  9903. _ams_alarm_cooldown[cooldown_key] = now
  9904. logger.info(
  9905. f"Sending temperature alarm for {printer.name} {ams_label}: "
  9906. f"{temperature}°C > {temp_alarm_threshold}°C"
  9907. )
  9908. try:
  9909. # Call different notification method based on AMS type
  9910. if is_ams_ht:
  9911. # The reported threshold has to be the one
  9912. # that fired, or the message says "> 35 °C"
  9913. # while firing at 45.
  9914. await notification_service.on_ams_ht_temperature_high(
  9915. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9916. )
  9917. else:
  9918. await notification_service.on_ams_temperature_high(
  9919. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9920. )
  9921. except Exception as e:
  9922. logger.warning("Failed to send temperature alarm: %s", e)
  9923. if drying_latch != drying_latch_before:
  9924. await _save_ams_drying_latch(db, drying_latch)
  9925. await db.commit()
  9926. if recorded_count > 0:
  9927. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  9928. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  9929. global _ams_cleanup_counter
  9930. _ams_cleanup_counter += 1
  9931. if _ams_cleanup_counter >= 288:
  9932. _ams_cleanup_counter = 0
  9933. # Get retention days from settings
  9934. from backend.app.models.settings import Settings
  9935. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  9936. setting = result.scalar_one_or_none()
  9937. retention_days = _retention_days(setting.value if setting else None, AMS_HISTORY_RETENTION_DAYS)
  9938. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9939. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  9940. await db.commit()
  9941. if result.rowcount > 0:
  9942. logger.info(
  9943. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  9944. )
  9945. # Wait until next recording interval
  9946. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  9947. except asyncio.CancelledError:
  9948. break
  9949. except Exception as e:
  9950. logger.warning("AMS history recording failed: %s", e)
  9951. await asyncio.sleep(60) # Wait a bit before retrying
  9952. def start_ams_history_recording():
  9953. """Start the AMS history recording background task."""
  9954. global _ams_history_task
  9955. if _ams_history_task is None:
  9956. _ams_history_task = asyncio.create_task(record_ams_history())
  9957. logging.getLogger(__name__).info("AMS history recording started")
  9958. def stop_ams_history_recording():
  9959. """Stop the AMS history recording background task."""
  9960. global _ams_history_task
  9961. if _ams_history_task:
  9962. _ams_history_task.cancel()
  9963. _ams_history_task = None
  9964. logging.getLogger(__name__).info("AMS history recording stopped")
  9965. # Printer sensor history recording (nozzle / bed / chamber)
  9966. _printer_sensor_history_task: asyncio.Task | None = None
  9967. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  9968. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  9969. _printer_sensor_cleanup_counter = 0
  9970. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  9971. # MQTT parser writes, so we don't need to handle per-model field aliases here
  9972. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  9973. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  9974. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  9975. _SENSOR_TARGET_KEYS = {
  9976. "nozzle": "nozzle_target",
  9977. "nozzle_2": "nozzle_2_target",
  9978. "bed": "bed_target",
  9979. "chamber": "chamber_target",
  9980. }
  9981. async def record_printer_sensor_history():
  9982. """Background task to record nozzle / bed / chamber readings.
  9983. Pulls from `state.temperatures` (already normalised across all printer
  9984. models by the MQTT parser) rather than re-parsing raw_data, so we get
  9985. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  9986. """
  9987. logger = logging.getLogger(__name__)
  9988. await asyncio.sleep(10)
  9989. while True:
  9990. try:
  9991. from backend.app.models.printer import Printer
  9992. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  9993. from backend.app.models.settings import Settings
  9994. async with async_session() as db:
  9995. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9996. printers = result.scalars().all()
  9997. recorded_count = 0
  9998. for printer in printers:
  9999. state = printer_manager.get_status(printer.id)
  10000. if not state or not state.connected:
  10001. continue
  10002. temps = getattr(state, "temperatures", None) or {}
  10003. if not isinstance(temps, dict):
  10004. continue
  10005. for kind in _SENSOR_KINDS:
  10006. if kind not in temps:
  10007. continue
  10008. try:
  10009. value = float(temps[kind])
  10010. except (ValueError, TypeError):
  10011. continue
  10012. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  10013. target_val: float | None = None
  10014. if target_raw is not None:
  10015. try:
  10016. target_val = float(target_raw)
  10017. except (ValueError, TypeError):
  10018. target_val = None
  10019. db.add(
  10020. PrinterSensorHistory(
  10021. printer_id=printer.id,
  10022. sensor_kind=kind,
  10023. value=value,
  10024. target=target_val,
  10025. )
  10026. )
  10027. recorded_count += 1
  10028. await db.commit()
  10029. if recorded_count > 0:
  10030. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  10031. # Periodic cleanup — once every ~24h at this interval.
  10032. global _printer_sensor_cleanup_counter
  10033. _printer_sensor_cleanup_counter += 1
  10034. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  10035. if _printer_sensor_cleanup_counter >= cleanup_every:
  10036. _printer_sensor_cleanup_counter = 0
  10037. result = await db.execute(
  10038. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  10039. )
  10040. setting = result.scalar_one_or_none()
  10041. retention_days = _retention_days(
  10042. setting.value if setting else None, PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  10043. )
  10044. cutoff = utcnow_naive() - timedelta(days=retention_days)
  10045. cleanup = await db.execute(
  10046. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  10047. )
  10048. await db.commit()
  10049. if cleanup.rowcount > 0:
  10050. logger.info(
  10051. "Cleaned up %s old printer sensor history entries (older than %s days)",
  10052. cleanup.rowcount,
  10053. retention_days,
  10054. )
  10055. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  10056. except asyncio.CancelledError:
  10057. break
  10058. except Exception as e:
  10059. logger.warning("Printer sensor history recording failed: %s", e)
  10060. await asyncio.sleep(60)
  10061. def start_printer_sensor_history_recording():
  10062. global _printer_sensor_history_task
  10063. if _printer_sensor_history_task is None:
  10064. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  10065. logging.getLogger(__name__).info("Printer sensor history recording started")
  10066. def stop_printer_sensor_history_recording():
  10067. global _printer_sensor_history_task
  10068. if _printer_sensor_history_task:
  10069. _printer_sensor_history_task.cancel()
  10070. _printer_sensor_history_task = None
  10071. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  10072. # Printer runtime tracking
  10073. _runtime_tracking_task: asyncio.Task | None = None
  10074. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  10075. # Printers the runtime tracker has seen connected since startup. One of them
  10076. # going offline clears its timestamp, so the time it was away is not counted
  10077. # when it comes back printing (DB-C5). A printer not yet seen -- still
  10078. # connecting after a restart -- keeps it for a grace period: a print that ran
  10079. # on through a Bambuddy restart is counted from the stored timestamp, as before.
  10080. _runtime_seen_connected: set[int] = set()
  10081. # A printer never seen connected this long after the tracker started is
  10082. # offline, not still connecting: its stored timestamp predates a gap too.
  10083. RUNTIME_STARTUP_GRACE_SECONDS = 120
  10084. async def track_printer_runtime():
  10085. """Background task to track printer active runtime (RUNNING state only).
  10086. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  10087. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  10088. which track mechanical wear. Pause time has no motion and no wear, so
  10089. counting it inflates maintenance warnings (#1521).
  10090. """
  10091. logger = logging.getLogger(__name__)
  10092. # Wait for MQTT connections to establish on startup
  10093. await asyncio.sleep(15)
  10094. started = time.monotonic()
  10095. while True:
  10096. try:
  10097. from backend.app.models.printer import Printer
  10098. # Fetch printer IDs in a short-lived read-only session
  10099. async with async_session() as db:
  10100. result = await db.execute(
  10101. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  10102. Printer.is_active.is_(True)
  10103. )
  10104. )
  10105. printer_rows = result.all()
  10106. now = datetime.now(timezone.utc)
  10107. updated_count = 0
  10108. # Update each printer in its own short session to minimise write-lock
  10109. # hold time and avoid blocking critical commits like queue status
  10110. # updates (#897).
  10111. for pid, pname, runtime_secs, last_update in printer_rows:
  10112. state = printer_manager.get_status(pid)
  10113. if not state:
  10114. logger.debug("[%s] Runtime tracking: no state available", pname)
  10115. continue
  10116. if not state.connected:
  10117. logger.debug("[%s] Runtime tracking: not connected", pname)
  10118. offline = pid in _runtime_seen_connected or (
  10119. time.monotonic() - started > RUNTIME_STARTUP_GRACE_SECONDS
  10120. )
  10121. if offline and last_update is not None:
  10122. try:
  10123. async with async_session() as db:
  10124. printer = await db.get(Printer, pid)
  10125. if printer:
  10126. printer.last_runtime_update = None
  10127. await db.commit()
  10128. except Exception as e:
  10129. # Still marked: the next offline tick tries again.
  10130. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  10131. continue
  10132. _runtime_seen_connected.discard(pid)
  10133. continue
  10134. _runtime_seen_connected.add(pid)
  10135. needs_commit = False
  10136. new_runtime = runtime_secs
  10137. new_last_update = last_update
  10138. if state.state == "RUNNING":
  10139. if last_update:
  10140. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  10141. elapsed = (now - lu).total_seconds()
  10142. if elapsed > 0:
  10143. new_runtime = runtime_secs + int(elapsed)
  10144. updated_count += 1
  10145. needs_commit = True
  10146. logger.debug(
  10147. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  10148. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  10149. )
  10150. else:
  10151. needs_commit = True
  10152. logger.debug("[%s] Runtime tracking: first active detection", pname)
  10153. new_last_update = now
  10154. else:
  10155. if last_update is not None:
  10156. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  10157. new_last_update = None
  10158. needs_commit = True
  10159. if needs_commit:
  10160. try:
  10161. async with async_session() as db:
  10162. result = await db.execute(select(Printer).where(Printer.id == pid))
  10163. printer = result.scalar_one_or_none()
  10164. if printer:
  10165. printer.runtime_seconds = new_runtime
  10166. printer.last_runtime_update = new_last_update
  10167. await db.commit()
  10168. except Exception as e:
  10169. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  10170. if updated_count > 0:
  10171. logger.debug("Updated runtime for %s printer(s)", updated_count)
  10172. except asyncio.CancelledError:
  10173. logger.info("Runtime tracking cancelled")
  10174. break
  10175. except Exception as e:
  10176. logger.warning("Runtime tracking failed: %s", e)
  10177. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  10178. def start_runtime_tracking():
  10179. """Start the printer runtime tracking background task."""
  10180. global _runtime_tracking_task
  10181. if _runtime_tracking_task is None:
  10182. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  10183. logging.getLogger(__name__).info("Printer runtime tracking started")
  10184. def stop_runtime_tracking():
  10185. """Stop the printer runtime tracking background task."""
  10186. global _runtime_tracking_task
  10187. if _runtime_tracking_task:
  10188. _runtime_tracking_task.cancel()
  10189. _runtime_tracking_task = None
  10190. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  10191. # SpoolBuddy device watchdog
  10192. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  10193. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  10194. async def _spoolbuddy_watchdog_loop():
  10195. """Periodic check for SpoolBuddy devices that have gone offline."""
  10196. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  10197. while True:
  10198. try:
  10199. await spoolbuddy_watchdog()
  10200. except asyncio.CancelledError:
  10201. break
  10202. except Exception as e:
  10203. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  10204. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  10205. def start_spoolbuddy_watchdog():
  10206. global _spoolbuddy_watchdog_task
  10207. if _spoolbuddy_watchdog_task is None:
  10208. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  10209. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  10210. def stop_spoolbuddy_watchdog():
  10211. global _spoolbuddy_watchdog_task
  10212. if _spoolbuddy_watchdog_task:
  10213. _spoolbuddy_watchdog_task.cancel()
  10214. _spoolbuddy_watchdog_task = None
  10215. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  10216. # Dead-MQTT-session recovery
  10217. #
  10218. # check_staleness() covers the "connected but silent" half-broken session. It
  10219. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  10220. # is the only thing left watching at that point. When paho stops making
  10221. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  10222. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  10223. # offline with the UI open the whole time, recovered only when something
  10224. # happened to nudge it.
  10225. #
  10226. # This loop is that backstop. It only touches printers that had a working
  10227. # session and lost it, and only when the MQTT port still answers — a printer
  10228. # that is simply switched off is left to paho, since rebuilding a client
  10229. # against an unreachable host achieves nothing and would fill the log every
  10230. # night.
  10231. _connection_watchdog_task: asyncio.Task | None = None
  10232. CONNECTION_WATCHDOG_INTERVAL = 60
  10233. # How long a printer must have been silent before we stop trusting paho.
  10234. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  10235. # so a session that is recovering on its own is never interrupted.
  10236. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  10237. # Per-printer floor between rebuild attempts.
  10238. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  10239. _connection_watchdog_last_attempt: dict[int, float] = {}
  10240. async def _recover_dead_printer_sessions() -> int:
  10241. """Rebuild MQTT clients that have been offline too long to still be trying.
  10242. Returns the number of printers a rebuild was attempted for (for tests and
  10243. for the caller's logging). Never raises: one unreachable printer must not
  10244. stop the sweep for the rest of the farm.
  10245. """
  10246. logger = logging.getLogger(__name__)
  10247. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  10248. now = time.monotonic()
  10249. recovered = 0
  10250. for printer_id, client in list(printer_manager._clients.items()):
  10251. try:
  10252. if client.state.connected:
  10253. _connection_watchdog_last_attempt.pop(printer_id, None)
  10254. continue
  10255. # Time since the last inbound message is the age of the last known
  10256. # good session — no extra bookkeeping needed, and it is the same
  10257. # clock is_stale() reads. 0 means this client has never had one:
  10258. # that is the initial-connect path, where paho retrying is the
  10259. # correct and only behaviour, so leave it be.
  10260. last_msg = client._last_message_time
  10261. if not last_msg:
  10262. continue
  10263. offline_for = time.time() - last_msg
  10264. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  10265. continue
  10266. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  10267. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  10268. continue
  10269. if not await check_port(client.ip_address, PORT_MQTT):
  10270. # Switched off, unplugged, or off the network. Paho's retry is
  10271. # the right handler; say so at debug level and move on.
  10272. logger.debug(
  10273. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  10274. "— leaving the reconnect to paho",
  10275. printer_id,
  10276. offline_for,
  10277. )
  10278. _connection_watchdog_last_attempt[printer_id] = now
  10279. continue
  10280. _connection_watchdog_last_attempt[printer_id] = now
  10281. recovered += 1
  10282. logger.warning(
  10283. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  10284. "rebuilding the client with a fresh session (last connect error: %s)",
  10285. printer_id,
  10286. offline_for,
  10287. PORT_MQTT,
  10288. client.last_connect_error or "none recorded",
  10289. )
  10290. # Async context, so this takes the hard-reset path: fresh client_id,
  10291. # paho's QoS 1 queue dropped. That matters — a project_file left
  10292. # unacked on the dead session would otherwise replay into the new
  10293. # one and trip 0500_4003 on the printer (#1136).
  10294. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  10295. except Exception as e:
  10296. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  10297. return recovered
  10298. async def _connection_watchdog_loop():
  10299. logger = logging.getLogger(__name__)
  10300. # Let the initial connects settle before judging anyone offline.
  10301. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  10302. while True:
  10303. try:
  10304. await _recover_dead_printer_sessions()
  10305. except asyncio.CancelledError:
  10306. break
  10307. except Exception as e:
  10308. logger.warning("Connection watchdog sweep failed: %s", e)
  10309. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  10310. def start_connection_watchdog():
  10311. global _connection_watchdog_task
  10312. if _connection_watchdog_task is None:
  10313. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  10314. logging.getLogger(__name__).info("Printer connection watchdog started")
  10315. def stop_connection_watchdog():
  10316. global _connection_watchdog_task
  10317. if _connection_watchdog_task:
  10318. _connection_watchdog_task.cancel()
  10319. _connection_watchdog_task = None
  10320. _connection_watchdog_last_attempt.clear()
  10321. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  10322. # Camera stream orphan cleanup
  10323. _camera_cleanup_task: asyncio.Task | None = None
  10324. CAMERA_CLEANUP_INTERVAL = 60
  10325. # Every this many camera cleanups (about an hour), the timelapse janitor too:
  10326. # kept frames of a failed stitch go after a day, not at the next restart.
  10327. TIMELAPSE_CLEANUP_EVERY = 60
  10328. async def _camera_cleanup_loop():
  10329. """Periodically clean up orphaned ffmpeg processes and timelapse leftovers."""
  10330. from backend.app.api.routes.camera import cleanup_orphaned_streams
  10331. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10332. rounds = 0
  10333. while True:
  10334. try:
  10335. rounds += 1
  10336. await cleanup_orphaned_streams()
  10337. except asyncio.CancelledError:
  10338. break
  10339. except Exception as e:
  10340. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  10341. try:
  10342. if rounds % TIMELAPSE_CLEANUP_EVERY == 0:
  10343. await asyncio.to_thread(cleanup_orphaned_timelapse_sessions)
  10344. except asyncio.CancelledError:
  10345. break
  10346. except Exception as e:
  10347. logging.getLogger(__name__).warning("Timelapse frames cleanup failed: %s", e)
  10348. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  10349. def start_camera_cleanup():
  10350. global _camera_cleanup_task
  10351. if _camera_cleanup_task is None:
  10352. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  10353. logging.getLogger(__name__).info("Camera stream cleanup started")
  10354. def stop_camera_cleanup():
  10355. global _camera_cleanup_task
  10356. if _camera_cleanup_task:
  10357. _camera_cleanup_task.cancel()
  10358. _camera_cleanup_task = None
  10359. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  10360. # ---------------------------------------------------------------------------
  10361. # Expected-print TTL eviction
  10362. # ---------------------------------------------------------------------------
  10363. def _evict_stale_expected_prints() -> None:
  10364. """Remove entries from _expected_prints / _expected_print_creators that are
  10365. older than _EXPECTED_PRINT_TTL_SECONDS.
  10366. This prevents unbounded growth when a print is registered (via
  10367. register_expected_print) but on_print_start never fires — e.g. because the
  10368. printer disconnects, the app restarts, or the print is started directly from
  10369. the printer panel without going through the queue.
  10370. """
  10371. # Use monotonic time so the TTL is unaffected by system clock adjustments
  10372. # (e.g. NTP sync, DST changes).
  10373. # A print that ended without its archive being found at completion leaves
  10374. # its id here; only running prints are owned.
  10375. _owned_print_archive_ids.intersection_update(_active_prints.values())
  10376. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  10377. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  10378. if not stale_keys:
  10379. return
  10380. evicted: set[tuple[int, int]] = set()
  10381. for key in stale_keys:
  10382. archive_id = _expected_prints.pop(key, None)
  10383. if archive_id is not None:
  10384. evicted.add((key[0], archive_id))
  10385. _expected_print_creators.pop(key, None)
  10386. _expected_print_registered_at.pop(key, None)
  10387. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  10388. # that have no remaining live keys in _expected_prints (all variants
  10389. # were just evicted) and are not printing right now. Print start pops
  10390. # only the names the printer reported, so the "<base>.gcode" variant
  10391. # outlives it; without the printing check its eviction two hours after
  10392. # dispatch threw away a running print's plate, AMS mapping and cost
  10393. # centre, which completion still reads (#3275).
  10394. for printer_id, archive_id in evicted:
  10395. if not _expected_or_printing_here(printer_id, archive_id):
  10396. _drop_dispatch(printer_id, archive_id)
  10397. logging.getLogger(__name__).info(
  10398. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  10399. )
  10400. async def _expected_prints_cleanup_loop() -> None:
  10401. """Background task: periodically evict stale expected-print entries."""
  10402. while True:
  10403. try:
  10404. _evict_stale_expected_prints()
  10405. except asyncio.CancelledError:
  10406. raise
  10407. except Exception as e:
  10408. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  10409. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  10410. def start_expected_prints_cleanup() -> None:
  10411. global _expected_prints_cleanup_task
  10412. if _expected_prints_cleanup_task is None:
  10413. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  10414. logging.getLogger(__name__).info("Expected prints cleanup started")
  10415. def stop_expected_prints_cleanup() -> None:
  10416. global _expected_prints_cleanup_task
  10417. if _expected_prints_cleanup_task:
  10418. _expected_prints_cleanup_task.cancel()
  10419. _expected_prints_cleanup_task = None
  10420. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  10421. # ---------------------------------------------------------------------------
  10422. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  10423. # ---------------------------------------------------------------------------
  10424. _auth_cleanup_task: asyncio.Task | None = None
  10425. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  10426. async def _run_auth_cleanup() -> None:
  10427. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  10428. from backend.app.core.database import async_session
  10429. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  10430. from backend.app.models.user_totp import UserTOTP
  10431. now = datetime.now(timezone.utc)
  10432. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  10433. try:
  10434. async with async_session() as db:
  10435. stale_cutoff = now - timedelta(hours=1)
  10436. result = await db.execute(
  10437. select(UserTOTP).where(
  10438. UserTOTP.is_enabled.is_(False),
  10439. UserTOTP.created_at < stale_cutoff,
  10440. )
  10441. )
  10442. stale_records = result.scalars().all()
  10443. if stale_records:
  10444. for rec in stale_records:
  10445. await db.delete(rec)
  10446. await db.commit()
  10447. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  10448. except Exception as e:
  10449. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  10450. # Remove expired revoked-JTI entries (they are no longer needed once the
  10451. # original token's exp has passed — the token would be rejected by JWT
  10452. # signature verification regardless).
  10453. try:
  10454. async with async_session() as db:
  10455. await db.execute(
  10456. delete(AuthEphemeralToken).where(
  10457. AuthEphemeralToken.token_type == "revoked_jti",
  10458. AuthEphemeralToken.expires_at < now,
  10459. )
  10460. )
  10461. await db.commit()
  10462. except Exception as e:
  10463. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  10464. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  10465. # Events outside this window can never affect rate-limit decisions — they only
  10466. # consume DB space. Use the same window constant as the rate limiter so the
  10467. # two are always in sync.
  10468. try:
  10469. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  10470. async with async_session() as db:
  10471. await db.execute(
  10472. delete(AuthRateLimitEvent).where(
  10473. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  10474. )
  10475. )
  10476. await db.commit()
  10477. except Exception as e:
  10478. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  10479. async def _auth_cleanup_loop() -> None:
  10480. """Periodic background task: run auth cleanup every hour."""
  10481. while True:
  10482. try:
  10483. await _run_auth_cleanup()
  10484. except asyncio.CancelledError:
  10485. break
  10486. except Exception as e:
  10487. logging.warning("Auth cleanup loop error: %s", e)
  10488. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  10489. def start_auth_cleanup() -> None:
  10490. global _auth_cleanup_task
  10491. if _auth_cleanup_task is None:
  10492. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  10493. logging.getLogger(__name__).info("Auth periodic cleanup started")
  10494. def stop_auth_cleanup() -> None:
  10495. global _auth_cleanup_task
  10496. if _auth_cleanup_task:
  10497. _auth_cleanup_task.cancel()
  10498. _auth_cleanup_task = None
  10499. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  10500. @asynccontextmanager
  10501. async def lifespan(app: FastAPI):
  10502. # Startup
  10503. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  10504. # anything else can spawn tasks that might trip it.
  10505. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  10506. install_proactor_reset_filter()
  10507. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  10508. # what turned descriptor exhaustion into a corrupted database (#2883).
  10509. from backend.app.core.fd_limit import raise_open_file_limit
  10510. raise_open_file_limit()
  10511. # Before init_db, so the warning is near the top of the log rather than
  10512. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  10513. warn_if_running_on_uvloop()
  10514. await init_db()
  10515. # Browser download tokens expire after five minutes. Remove abandoned
  10516. # prepared ZIPs at startup as well as before each new preparation so a
  10517. # quiet appliance cannot retain an unusable bundle indefinitely.
  10518. try:
  10519. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  10520. await prune_stale_printer_file_bundles()
  10521. except Exception as exc:
  10522. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  10523. # After migrations, so the is_env_managed column exists. Never raises --
  10524. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  10525. # startup (see apply_env_oidc_provider).
  10526. from backend.app.core.oidc_env import apply_env_oidc_provider
  10527. async with async_session() as oidc_db:
  10528. await apply_env_oidc_provider(oidc_db)
  10529. # Close out batches that finished before `completed` was a reachable status
  10530. # (#342). Without this the Batches tab opens on every batch created since
  10531. # the feature shipped, all still marked active. Never blocks startup.
  10532. try:
  10533. from backend.app.services.print_batch import backfill_batch_statuses
  10534. async with async_session() as batch_db:
  10535. await backfill_batch_statuses(batch_db)
  10536. except Exception as exc:
  10537. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  10538. # Each plate's estimate of archives made before they were kept (#3375),
  10539. # read from their 3MFs in the background: the readers use the whole
  10540. # file's figures until then.
  10541. global _plate_estimates_task
  10542. _plate_estimates_task = asyncio.create_task(_fill_plate_estimates())
  10543. # Register an app-scoped httpx client for Bambu Cloud services so
  10544. # per-request BambuCloudService instances reuse the same connection pool
  10545. # (important for routes like /cloud/filament-info that chain many
  10546. # get_setting_detail calls). The shared client stores no region/token
  10547. # state, so the per-request ownership pattern that fixed the region-bleed
  10548. # bug is preserved.
  10549. import httpx as _httpx
  10550. from backend.app.services.bambu_cloud import set_shared_http_client
  10551. from backend.app.services.model_providers.makerworld.service import (
  10552. set_shared_http_client as set_shared_makerworld_http_client,
  10553. )
  10554. from backend.app.services.orca_cloud import (
  10555. set_shared_http_client as set_shared_orca_http_client,
  10556. )
  10557. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  10558. set_shared_http_client(_shared_cloud_http_client)
  10559. # Reuse the same connection pool for MakerWorld — different host, same
  10560. # keep-alive pool saves a TLS handshake per request.
  10561. set_shared_makerworld_http_client(_shared_cloud_http_client)
  10562. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  10563. # each spun up (and never closed) its own client, leaking sockets.
  10564. set_shared_orca_http_client(_shared_cloud_http_client)
  10565. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  10566. # This can happen when a print was cancelled mid-print on versions before this fix.
  10567. try:
  10568. async with async_session() as db:
  10569. from backend.app.models.print_queue import PrintQueueItem
  10570. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  10571. aborted_items = result.scalars().all()
  10572. if aborted_items:
  10573. for item in aborted_items:
  10574. item.status = "cancelled"
  10575. await db.commit()
  10576. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  10577. except Exception as e:
  10578. logging.warning("Failed to fix aborted queue items: %s", e)
  10579. # Restore debug logging state from previous session
  10580. await init_debug_logging()
  10581. # Set up printer manager callbacks
  10582. loop = asyncio.get_event_loop()
  10583. printer_manager.set_event_loop(loop)
  10584. printer_manager.set_status_change_callback(on_printer_status_change)
  10585. printer_manager.set_print_start_callback(on_print_start)
  10586. printer_manager.set_print_complete_callback(on_print_complete)
  10587. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  10588. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  10589. printer_manager.set_ams_change_callback(on_ams_change)
  10590. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  10591. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  10592. await printer_manager.load_awaiting_plate_clear_from_db()
  10593. # Layer change callback for external camera timelapse
  10594. async def on_layer_change(printer_id: int, layer_num: int):
  10595. """Capture timelapse frame on layer change + first layer notification."""
  10596. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  10597. await tl_layer_change(printer_id, layer_num)
  10598. # #1867: bank a recent in-print frame so the finish-photo path has a
  10599. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  10600. # #2547 added `on_print_progress` as a second driver — this one alone
  10601. # stops firing once the final layer begins.
  10602. await _maybe_bank_inprint_frame(printer_id, layer_num)
  10603. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  10604. # Gate on actual printing state — Bambu firmware ticks layer_num during
  10605. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  10606. # nozzle clean), so a bare layer_num check can fire minutes before the
  10607. # first real extrusion. We require gcode_state == RUNNING and
  10608. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  10609. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  10610. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  10611. # edge fires later; _first_layer_notified stays clear until we actually send
  10612. # so a deferred re-evaluation can win. See issue #1837.
  10613. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  10614. client = printer_manager.get_client(printer_id)
  10615. state = client.state if client else None
  10616. if not state or state.state != "RUNNING":
  10617. return
  10618. if state.mc_print_sub_stage not in (None, 0):
  10619. return
  10620. _first_layer_notified[printer_id] = True
  10621. try:
  10622. async with async_session() as db:
  10623. from backend.app.models.printer import Printer
  10624. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  10625. printer = result.scalar_one_or_none()
  10626. if not printer:
  10627. return
  10628. printer_name = printer.name
  10629. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  10630. total_layers = state.total_layers if state else 0
  10631. image_data = await _capture_snapshot_for_notification(
  10632. printer_id, printer, logging.getLogger(__name__)
  10633. )
  10634. await notification_service.on_first_layer_complete(
  10635. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  10636. )
  10637. except Exception as e:
  10638. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  10639. printer_manager.set_layer_change_callback(on_layer_change)
  10640. async def on_print_progress(printer_id: int, percent: int):
  10641. """#2547: keep the in-print frame bank fresh through the final layer.
  10642. `on_layer_change` stops the moment the last layer starts, which on the
  10643. H2C capture that closed #2547 left the bank stale for the three minutes
  10644. that layer took. Progress is the only field that keeps advancing there,
  10645. and it freezes before the End G-code runs — so banking on it stays
  10646. inside the print and never sees a swapped plate.
  10647. """
  10648. client = printer_manager.get_client(printer_id)
  10649. state = client.state if client else None
  10650. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  10651. printer_manager.set_print_progress_callback(on_print_progress)
  10652. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  10653. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  10654. waiter = _bed_cool_waiters.get(printer_id)
  10655. if not waiter:
  10656. return
  10657. threshold = waiter["threshold"]
  10658. if bed_temp > threshold:
  10659. return
  10660. # Bed is at or below threshold — fire notification and remove waiter
  10661. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  10662. if not waiter_info:
  10663. return # Another callback already handled it
  10664. bed_cool_logger = logging.getLogger(__name__)
  10665. bed_cool_logger.info(
  10666. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  10667. bed_temp,
  10668. printer_id,
  10669. threshold,
  10670. )
  10671. try:
  10672. printer_info = printer_manager.get_printer(printer_id)
  10673. p_name = printer_info.name if printer_info else "Unknown"
  10674. async with async_session() as db:
  10675. await notification_service.on_bed_cooled(
  10676. printer_id=printer_id,
  10677. printer_name=p_name,
  10678. bed_temp=bed_temp,
  10679. threshold=threshold,
  10680. filename=waiter_info["filename"],
  10681. db=db,
  10682. )
  10683. except Exception as e:
  10684. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  10685. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  10686. async def on_drying_complete(printer_id: int, ams_id: int):
  10687. """Smart-plug auto-off-after-drying trigger (#1349).
  10688. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  10689. manager walks all plugs linked to this printer and turns off only
  10690. the ones with ``auto_off_after_drying`` enabled, after their
  10691. per-plug delay. Multiple AMS units finishing close together (e.g. a
  10692. dual-AMS dry that ends within the same MQTT push) call this once
  10693. per unit — the manager's ``_cancel_pending_off`` collapses
  10694. repeated scheduling on the same plug to one timer, so duplicate
  10695. fires are safe.
  10696. """
  10697. try:
  10698. async with async_session() as db:
  10699. await smart_plug_manager.on_drying_complete(printer_id, db)
  10700. except Exception as e:
  10701. logging.getLogger(__name__).warning(
  10702. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  10703. printer_id,
  10704. ams_id,
  10705. e,
  10706. )
  10707. printer_manager.set_drying_complete_callback(on_drying_complete)
  10708. async def on_drying_cycle_end(printer_id: int, cycle):
  10709. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  10710. from backend.app.services.spool_drying import record_drying_cycle
  10711. try:
  10712. async with async_session() as db:
  10713. await record_drying_cycle(db, printer_id, cycle)
  10714. except Exception as e:
  10715. logging.getLogger(__name__).warning(
  10716. "Failed to record drying for printer %d (AMS %d): %s",
  10717. printer_id,
  10718. cycle.ams_id,
  10719. e,
  10720. )
  10721. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  10722. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  10723. """Surface the read-back result of a spool assignment to the UI (#2582).
  10724. The MQTT client confirms (or fails to confirm) that the tray telemetry
  10725. echoed back the filament id we pushed. We relay that as a websocket
  10726. event so the frontend can toast "loaded" / "assignment didn't take"
  10727. instead of the historic silent fire-and-forget, which made the
  10728. AMS→Studio hand-off feel random to users.
  10729. """
  10730. try:
  10731. from backend.app.services.spool_assignment_notifications import (
  10732. _slot_label_from_global_tray,
  10733. )
  10734. if ams_id == 255:
  10735. global_id = 254 + tray_id
  10736. elif ams_id >= 128:
  10737. global_id = ams_id
  10738. else:
  10739. global_id = ams_id * 4 + tray_id
  10740. slot_label = _slot_label_from_global_tray(global_id)
  10741. printer_info = printer_manager.get_printer(printer_id)
  10742. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  10743. await ws_manager.broadcast(
  10744. {
  10745. "type": "spool_assignment_verified",
  10746. "printer_id": printer_id,
  10747. "printer_name": printer_name,
  10748. "ams_id": ams_id,
  10749. "tray_id": tray_id,
  10750. "slot": slot_label,
  10751. "verified": verified,
  10752. # Present on success: False means the filament setting landed
  10753. # but the K-profile (cali_idx) did not — the reporter's exact
  10754. # "loaded but no flow profile" symptom.
  10755. "kprofile_applied": detail.get("kprofile_applied", True),
  10756. }
  10757. )
  10758. except Exception as e:
  10759. logging.getLogger(__name__).warning(
  10760. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  10761. printer_id,
  10762. ams_id,
  10763. tray_id,
  10764. e,
  10765. )
  10766. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  10767. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  10768. """Persist a mid-print tray change for completion-time attribution.
  10769. AMS filament backup switches trays without telling the slicer, so the
  10770. tray-change log is the only record of which spool fed which layers.
  10771. Keeping it only in memory meant a restart mid-print charged everything
  10772. to the tray that finished the job.
  10773. """
  10774. try:
  10775. from backend.app.services.usage_tracker import record_tray_change
  10776. async with async_session() as db:
  10777. await record_tray_change(db, printer_id, tray_global, layer_num)
  10778. except Exception as e:
  10779. logging.getLogger(__name__).warning(
  10780. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  10781. printer_id,
  10782. tray_global,
  10783. layer_num,
  10784. e,
  10785. )
  10786. printer_manager.set_tray_change_callback(on_tray_change)
  10787. # Initialize MQTT relay from settings
  10788. async with async_session() as db:
  10789. from backend.app.api.routes.settings import get_setting
  10790. mqtt_settings = {
  10791. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  10792. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  10793. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  10794. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  10795. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  10796. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  10797. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  10798. }
  10799. await mqtt_relay.configure(mqtt_settings)
  10800. # Restore MQTT smart plug subscriptions
  10801. if mqtt_settings.get("mqtt_enabled"):
  10802. from backend.app.models.smart_plug import SmartPlug
  10803. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  10804. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  10805. mqtt_plugs = result.scalars().all()
  10806. restored = 0
  10807. for plug in mqtt_plugs:
  10808. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  10809. restored += 1
  10810. if restored:
  10811. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  10812. # Connect to all active printers
  10813. async with async_session() as db:
  10814. await init_printer_connections(db)
  10815. # Auto-connect to Spoolman if enabled
  10816. async with async_session() as db:
  10817. from backend.app.api.routes.settings import get_setting
  10818. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  10819. spoolman_url = await get_setting(db, "spoolman_url")
  10820. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  10821. try:
  10822. client = await init_spoolman_client(spoolman_url)
  10823. if await client.health_check():
  10824. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  10825. # Ensure the 'tag' extra field exists for RFID/UUID storage
  10826. field_ok = await client.ensure_tag_extra_field()
  10827. if not field_ok:
  10828. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  10829. # Register the BambuStudio slicer-preset fields used by the
  10830. # spool-edit / assign flow. Spoolman rejects PATCHes with
  10831. # unknown extra keys, so these must exist before any update
  10832. # that touches them.
  10833. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  10834. if not await client.ensure_extra_field(field_name):
  10835. logging.warning(
  10836. "Spoolman extra field %r registration failed — "
  10837. "spool slicer-preset edits will return 502",
  10838. field_name,
  10839. )
  10840. else:
  10841. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  10842. except Exception as e:
  10843. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  10844. # Start the print scheduler
  10845. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  10846. # Start the smart plug scheduler for time-based on/off
  10847. smart_plug_manager.start_scheduler()
  10848. # Start the Home Assistant sensor poller (#1148)
  10849. ha_sensor_manager.start()
  10850. location_ha_sensor_manager.start()
  10851. # Resume any pending auto-offs that were interrupted by restart
  10852. await smart_plug_manager.resume_pending_auto_offs()
  10853. # Start the notification digest scheduler
  10854. notification_service.start_digest_scheduler()
  10855. notify_live_activities.start()
  10856. notify_widgets.start()
  10857. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  10858. # provider in reactions/both mode; the notification routes resync them.
  10859. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  10860. # until the next provider save, not the whole startup.
  10861. try:
  10862. await telegram_reaction_poller.start()
  10863. except Exception as e:
  10864. logging.warning("Telegram reaction poller did not start: %s", e)
  10865. # Start the GitHub backup scheduler
  10866. await github_backup_service.start_scheduler()
  10867. # Start the local backup scheduler
  10868. await local_backup_service.start_scheduler()
  10869. await obico_detection_service.start()
  10870. # Start the library trash sweeper (#1008)
  10871. await library_trash_service.start_scheduler()
  10872. # Start the archive auto-purge sweeper (#1008 follow-up)
  10873. await archive_purge_service.start_scheduler()
  10874. # Start AMS history recording
  10875. start_ams_history_recording()
  10876. # Start printer sensor (nozzle / bed / chamber) history recording
  10877. start_printer_sensor_history_recording()
  10878. # Start printer runtime tracking
  10879. start_runtime_tracking()
  10880. # Start SpoolBuddy device watchdog
  10881. start_spoolbuddy_watchdog()
  10882. # Start camera stream orphan cleanup
  10883. start_camera_cleanup()
  10884. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  10885. start_connection_watchdog()
  10886. # One-shot sweep for timelapse session directories orphaned by a crash
  10887. # or restart that happened mid-print (in-memory session tracking can't
  10888. # survive that, and nothing else reaps the leftover frames/output file)
  10889. try:
  10890. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10891. removed = cleanup_orphaned_timelapse_sessions()
  10892. if removed:
  10893. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  10894. except Exception as e:
  10895. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  10896. # Start expected-print TTL eviction (prevents memory leak when prints are
  10897. # registered but on_print_start never fires)
  10898. start_expected_prints_cleanup()
  10899. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  10900. start_auth_cleanup()
  10901. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  10902. from backend.app.services import announcements as announcements_service
  10903. announcements_service.start()
  10904. from backend.app.services.printer_media import start_printer_download_cleanup
  10905. start_printer_download_cleanup()
  10906. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  10907. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  10908. from backend.app.services.loop_watchdog import start_loop_watchdog
  10909. start_loop_watchdog()
  10910. # Initialize virtual printer manager and sync from DB
  10911. from backend.app.services.virtual_printer import virtual_printer_manager
  10912. virtual_printer_manager.set_session_factory(async_session)
  10913. virtual_printer_manager.set_printer_manager(printer_manager)
  10914. try:
  10915. await virtual_printer_manager.sync_from_db()
  10916. logging.info("Virtual printer manager synced from database")
  10917. except Exception as e:
  10918. logging.warning("Failed to sync virtual printers: %s", e)
  10919. yield
  10920. # Shutdown
  10921. print_scheduler.stop()
  10922. smart_plug_manager.stop_scheduler()
  10923. ha_sensor_manager.stop()
  10924. location_ha_sensor_manager.stop()
  10925. notification_service.stop_digest_scheduler()
  10926. await notify_live_activities.close()
  10927. await notify_widgets.close()
  10928. await telegram_reaction_poller.aclose()
  10929. github_backup_service.stop_scheduler()
  10930. local_backup_service.stop_scheduler()
  10931. library_trash_service.stop_scheduler()
  10932. archive_purge_service.stop_scheduler()
  10933. obico_detection_service.stop()
  10934. stop_ams_history_recording()
  10935. stop_printer_sensor_history_recording()
  10936. stop_runtime_tracking()
  10937. stop_spoolbuddy_watchdog()
  10938. stop_camera_cleanup()
  10939. stop_connection_watchdog()
  10940. from backend.app.services.loop_watchdog import stop_loop_watchdog
  10941. stop_loop_watchdog()
  10942. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  10943. # cleanly rather than waiting on a queue that nothing will ever fill.
  10944. try:
  10945. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  10946. await shutdown_all_broadcasters()
  10947. except Exception as e:
  10948. logging.warning("Failed to shut down camera broadcasters: %s", e)
  10949. stop_expected_prints_cleanup()
  10950. stop_auth_cleanup()
  10951. if _plate_estimates_task is not None and not _plate_estimates_task.done():
  10952. _plate_estimates_task.cancel()
  10953. from backend.app.services import announcements as announcements_service
  10954. announcements_service.stop()
  10955. from backend.app.services.printer_media import stop_printer_download_cleanup
  10956. await stop_printer_download_cleanup()
  10957. # Stops a timelapse editor's ffmpeg rather than leaving it to the OS.
  10958. from backend.app.services import timelapse_jobs
  10959. await timelapse_jobs.cancel_all()
  10960. printer_manager.disconnect_all()
  10961. slot_unlink_grace.reset()
  10962. await close_spoolman_client()
  10963. # Stop all virtual printer services
  10964. await virtual_printer_manager.stop_all()
  10965. await mqtt_smart_plug_service.disconnect(timeout=2)
  10966. await mqtt_relay.disconnect(timeout=2)
  10967. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  10968. set_shared_http_client(None)
  10969. set_shared_makerworld_http_client(None)
  10970. set_shared_orca_http_client(None)
  10971. await _shared_cloud_http_client.aclose()
  10972. # Checkpoint WAL (SQLite only) and close all database connections
  10973. from backend.app.core.db_dialect import is_sqlite
  10974. if is_sqlite():
  10975. try:
  10976. async with engine.begin() as conn:
  10977. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  10978. logging.info("WAL checkpoint completed")
  10979. except Exception as e:
  10980. logging.warning("WAL checkpoint failed: %s", e)
  10981. await engine.dispose()
  10982. app = FastAPI(
  10983. title=app_settings.app_name,
  10984. description="Archive and manage Bambu Lab 3MF files",
  10985. version=APP_VERSION,
  10986. lifespan=lifespan,
  10987. )
  10988. # Added first so it sits innermost, next to the routes: a refused header's value
  10989. # (often a stored token) masked in every JSON body. See core.response_redaction.
  10990. app.add_middleware(RefusedHeaderResponseMask)
  10991. def _json_safe(value):
  10992. """The validation errors with every non-finite number written as text."""
  10993. if isinstance(value, float) and not math.isfinite(value):
  10994. return str(value)
  10995. if isinstance(value, dict):
  10996. return {key: _json_safe(item) for key, item in value.items()}
  10997. if isinstance(value, list | tuple):
  10998. return [_json_safe(item) for item in value]
  10999. return value
  11000. @app.exception_handler(RequestValidationError)
  11001. async def _validation_error(_request, exc: RequestValidationError) -> JSONResponse:
  11002. """FastAPI's own 422, except that it survives a non-finite number.
  11003. A body may carry ``Infinity`` or ``NaN`` (Python's JSON reader accepts
  11004. them), and the default handler echoes the input back in its errors,
  11005. which JSON cannot hold: the request ended in an error instead of a 422.
  11006. """
  11007. return JSONResponse(status_code=422, content={"detail": _json_safe(jsonable_encoder(exc.errors()))})
  11008. # =============================================================================
  11009. # Authentication Middleware - Secures ALL API routes by default
  11010. # =============================================================================
  11011. # Public routes that don't require authentication even when auth is enabled
  11012. PUBLIC_API_ROUTES = {
  11013. # Auth routes needed before/during login
  11014. "/api/v1/auth/status",
  11015. "/api/v1/auth/login",
  11016. "/api/v1/auth/setup", # Needed for initial setup and recovery
  11017. # Advanced auth status needed for login page
  11018. "/api/v1/auth/advanced-auth/status",
  11019. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  11020. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  11021. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  11022. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  11023. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  11024. # OIDC routes that must be reachable without a JWT
  11025. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  11026. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  11027. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  11028. # Connected apps: the app's server swaps a code for the user's identity,
  11029. # authenticated by its client secret rather than a login token.
  11030. "/api/v1/connect/token",
  11031. # Version check for updates (no sensitive data)
  11032. "/api/v1/updates/version",
  11033. # Metrics endpoint handles its own prometheus_token authentication
  11034. "/api/v1/metrics",
  11035. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  11036. # this BEFORE a JWT is available to pick up the firstboot wizard's
  11037. # hostname / timezone / locale and the chrony NTP-gate state. The
  11038. # response contains user-set defaults and a public sync flag — no
  11039. # secrets. Without this entry the global auth middleware returns 401
  11040. # before the route handler runs, regardless of the route's own
  11041. # "no auth required" intent.
  11042. "/api/v1/system/appliance",
  11043. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  11044. # authenticates with a long-lived ``camwall``-scoped token in the query
  11045. # string — exactly like the camera streams two lists below, and for the same
  11046. # reason (no header to put a JWT in). "Public" here only means the middleware
  11047. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  11048. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  11049. # plain ``camera_stream`` token does NOT open this door.
  11050. "/api/v1/camwall/printers",
  11051. # Overlay branding: the route enforces overlay-scoped token authentication.
  11052. "/api/v1/overlay-branding/logo",
  11053. }
  11054. # Route prefixes that are public (for routes with dynamic segments)
  11055. PUBLIC_API_PREFIXES = [
  11056. # WebSocket connections handle their own auth
  11057. "/api/v1/ws",
  11058. # OIDC authorize redirects — include provider_id in path
  11059. "/api/v1/auth/oidc/authorize/",
  11060. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  11061. # a phone with no session, so no header can carry a JWT — the single-use
  11062. # capability token in the path IS the credential (same reasoning as the
  11063. # /dl/ slicer downloads below). The route grants nothing beyond writing
  11064. # good/reject on the one archive the token was minted for.
  11065. "/api/v1/archives/confirm/",
  11066. ]
  11067. # Route patterns that are public (read-only display data)
  11068. # These are checked with "in path" - needed because browsers load images/videos
  11069. # via <img src> and <video src> which don't include Authorization headers
  11070. PUBLIC_API_PATTERNS = [
  11071. # Thumbnails
  11072. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  11073. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  11074. # Images and media
  11075. "/photos/", # /archives/{id}/photos/{filename}
  11076. "/project-image/", # /archives/{id}/project-image/{path}
  11077. "/qrcode", # /archives/{id}/qrcode
  11078. "/timelapse", # /archives/{id}/timelapse (video)
  11079. "/cover", # /printers/{id}/cover
  11080. "/icon", # /external-links/{id}/icon
  11081. # Camera (streams loaded via <img> tag)
  11082. "/camera/stream", # /printers/{id}/camera/stream
  11083. "/camera/snapshot", # /printers/{id}/camera/snapshot
  11084. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  11085. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  11086. # string (same reasoning as the camera streams above — no header to carry a
  11087. # JWT). "Public" only means the middleware steps aside; the route still runs
  11088. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  11089. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  11090. "/overlay-status", # /printers/{id}/overlay-status
  11091. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  11092. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  11093. # download token in the URL path instead.
  11094. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  11095. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  11096. # and these patterns match by substring. Without its own entry the middleware
  11097. # 401s the slicer's header-less request before the route's token check runs,
  11098. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  11099. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  11100. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  11101. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  11102. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  11103. ]
  11104. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  11105. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  11106. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  11107. Format: comma-separated list of ``scheme://host[:port]`` origins.
  11108. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  11109. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  11110. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  11111. Invalid entries are dropped with a warning rather than failing startup, so
  11112. a typo in one origin doesn't take the whole deployment down.
  11113. """
  11114. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  11115. if not raw:
  11116. return ()
  11117. valid: list[str] = []
  11118. for item in raw.split(","):
  11119. candidate = item.strip()
  11120. if not candidate:
  11121. continue
  11122. try:
  11123. parsed = urlparse(candidate)
  11124. except ValueError as e:
  11125. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  11126. continue
  11127. if parsed.scheme not in ("http", "https"):
  11128. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  11129. continue
  11130. if not parsed.netloc:
  11131. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  11132. continue
  11133. if parsed.path and parsed.path != "/":
  11134. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  11135. continue
  11136. if parsed.query or parsed.fragment:
  11137. _security_headers_logger.warning(
  11138. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  11139. )
  11140. continue
  11141. if "*" in parsed.netloc:
  11142. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  11143. continue
  11144. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  11145. if valid:
  11146. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  11147. return tuple(valid)
  11148. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  11149. def _frame_ancestors(default_value: str) -> str:
  11150. """Compose the ``frame-ancestors`` CSP directive (#1191).
  11151. ``default_value`` is the strict directive used when the operator has not
  11152. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  11153. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  11154. Settings URL builder's preview). When trusted origins
  11155. are configured, ``'self'`` is always included so same-origin embedding never
  11156. breaks even if an operator forgets to add their own origin to the list.
  11157. """
  11158. if _TRUSTED_FRAME_ORIGINS:
  11159. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  11160. return f"frame-ancestors {default_value};"
  11161. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  11162. # patterns are anchored on the exact emitted name so the relaxed policies
  11163. # below can never apply to any other asset.
  11164. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  11165. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  11166. # -> /assets/pdf.worker.min-<hash>.js
  11167. # Vite also emits a one-line chunk under the second name that only exports the
  11168. # worker's URL. The page imports it as a module, and a module script is run
  11169. # under the importing document's policy, never its own response's, so it
  11170. # matching as well changes nothing.
  11171. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  11172. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  11173. @app.middleware("http")
  11174. async def security_headers_middleware(request, call_next):
  11175. """Add standard HTTP security headers to every response."""
  11176. # Per-request nonce stamped into `script-src` (#1460). On its own this
  11177. # changes nothing for Bambuddy's own pages — index.html has no inline
  11178. # scripts since the SW registration moved to /sw-register.js. The reason
  11179. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  11180. # script injected into the HTML on the edge, with a fresh hash on every
  11181. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  11182. # it clones the same nonce onto its injected <script>, and the inline
  11183. # script passes the policy without us needing 'unsafe-inline'. See
  11184. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  11185. csp_nonce = secrets.token_urlsafe(16)
  11186. # Routes that render their own HTML need it too, or their inline script is
  11187. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  11188. # one that does: it submits its own form so a verdict still costs one tap.
  11189. request.state.csp_nonce = csp_nonce
  11190. response = await call_next(request)
  11191. response.headers["X-Content-Type-Options"] = "nosniff"
  11192. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  11193. # browsers honour CSP frame-ancestors instead, and the legacy
  11194. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  11195. # When operators have explicitly allowlisted trusted frame origins (#1191
  11196. # — typically Home Assistant on a different port), drop X-Frame-Options
  11197. # and let the CSP-side frame-ancestors directive govern embedding.
  11198. if not _TRUSTED_FRAME_ORIGINS:
  11199. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  11200. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  11201. # Content-Security-Policy for the React SPA.
  11202. # Notes:
  11203. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  11204. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  11205. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  11206. # - media-src blob:: timelapse video player uses Blob URLs.
  11207. # - font-src data:: some icon fonts are embedded as data URIs.
  11208. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  11209. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  11210. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  11211. # default CSP would render a blank page.
  11212. response.headers["Content-Security-Policy"] = (
  11213. "default-src 'self'; "
  11214. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  11215. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  11216. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  11217. "connect-src 'self'; "
  11218. "font-src 'self' data: https://fonts.gstatic.com; "
  11219. "worker-src 'self' blob:; "
  11220. "object-src 'none'; "
  11221. "base-uri 'self'; " + _frame_ancestors("'none'")
  11222. )
  11223. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  11224. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  11225. # its emscripten/embind glue generates invoker functions with `new
  11226. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  11227. # worker is governed by the policy delivered with the WORKER SCRIPT's
  11228. # own response — not the document's — so relaxing it here confines
  11229. # eval to that DOM-less worker context. The document policy below
  11230. # stays nonce-strict, and this response header has no effect when the
  11231. # file is merely fetched (a fetch's CSP is enforced against the
  11232. # requesting document, not the resource's own headers).
  11233. response.headers["Content-Security-Policy"] = (
  11234. "default-src 'self'; "
  11235. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  11236. "connect-src 'self'; "
  11237. "object-src 'none'; "
  11238. "base-uri 'self'; " + _frame_ancestors("'none'")
  11239. )
  11240. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  11241. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  11242. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  11243. # rule as the STEP worker above: the policy that governs a dedicated
  11244. # worker is the one delivered with its own script, so the wasm compile
  11245. # has to be permitted here rather than on the document. Unlike the STEP
  11246. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  11247. response.headers["Content-Security-Policy"] = (
  11248. "default-src 'self'; "
  11249. "script-src 'self' 'wasm-unsafe-eval'; "
  11250. "connect-src 'self'; "
  11251. "object-src 'none'; "
  11252. "base-uri 'self'; " + _frame_ancestors("'none'")
  11253. )
  11254. else:
  11255. # The streaming overlay is embedded same-origin by the URL builder's
  11256. # preview in Settings (#1422), so this branch allows 'self'.
  11257. # Embedding from anywhere else is still refused: 'self'
  11258. # only permits a framer on this origin, which is Bambuddy's own UI, so
  11259. # a clickjacking page on another host is blocked exactly as before.
  11260. # (The overlay draws status over a camera feed and its only interactive
  11261. # element is the logo link, so there is nothing to bait a click into
  11262. # even from a same-origin framer.) Cross-origin embedding of the
  11263. # overlay — Home Assistant on another port — remains what
  11264. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  11265. # allowlist in.
  11266. #
  11267. # The connected-app consent page (/connect/authorize) gets the same
  11268. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  11269. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  11270. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  11271. # requires every ancestor to be this origin, so a foreign page -- a
  11272. # sidebar link's site included -- still cannot frame the consent
  11273. # screen to bait a click.
  11274. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  11275. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  11276. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  11277. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  11278. # the policy served with their own script, so each gets it in its own
  11279. # branch above and the document policy stays as strict as it was.
  11280. response.headers["Content-Security-Policy"] = (
  11281. "default-src 'self'; "
  11282. f"script-src 'self' 'nonce-{csp_nonce}'; "
  11283. "style-src 'self' 'unsafe-inline'; "
  11284. "img-src 'self' data: blob:; "
  11285. "media-src 'self' blob:; "
  11286. "connect-src 'self' ws: wss:; "
  11287. "font-src 'self' data:; "
  11288. "object-src 'none'; "
  11289. "base-uri 'self'; "
  11290. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  11291. )
  11292. if request.url.scheme == "https":
  11293. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  11294. return response
  11295. @app.middleware("http")
  11296. async def auth_middleware(request, call_next):
  11297. """Enforce authentication on all API routes when auth is enabled.
  11298. This middleware provides defense-in-depth by checking auth at the API gateway level,
  11299. regardless of whether individual routes have auth dependencies.
  11300. """
  11301. from starlette.responses import JSONResponse
  11302. path = request.url.path
  11303. # Only apply to API routes
  11304. if not path.startswith("/api/"):
  11305. return await call_next(request)
  11306. # Allow public routes
  11307. if path in PUBLIC_API_ROUTES:
  11308. return await call_next(request)
  11309. # Allow public prefixes
  11310. for prefix in PUBLIC_API_PREFIXES:
  11311. if path.startswith(prefix):
  11312. return await call_next(request)
  11313. # Allow public patterns (read-only display data like thumbnails)
  11314. for pattern in PUBLIC_API_PATTERNS:
  11315. if pattern in path:
  11316. return await call_next(request)
  11317. # Check if auth is enabled. Fail CLOSED on any exception during the
  11318. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  11319. # an attacker who could force a DB exception (e.g. file-descriptor
  11320. # exhaustion via login flood) bypass auth on every protected endpoint.
  11321. # Only the probe is guarded: the request itself runs outside the try, so an
  11322. # error in a route surfaces as the 500 it is rather than as an auth outage.
  11323. try:
  11324. async with async_session() as db:
  11325. from backend.app.core.auth import is_auth_enabled
  11326. auth_enabled = await is_auth_enabled(db)
  11327. except Exception:
  11328. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  11329. return JSONResponse(
  11330. status_code=503,
  11331. content={"detail": "Authentication service temporarily unavailable"},
  11332. )
  11333. if not auth_enabled:
  11334. # Auth disabled, allow all requests
  11335. return await call_next(request)
  11336. # Auth is enabled - require valid token
  11337. auth_header = request.headers.get("Authorization")
  11338. x_api_key = request.headers.get("X-API-Key")
  11339. # Check for API key auth first
  11340. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  11341. # API key authentication - let the request through to be validated by route handler
  11342. # API keys are validated per-route since they have different permission levels
  11343. return await call_next(request)
  11344. # Check for JWT auth
  11345. if not auth_header or not auth_header.startswith("Bearer "):
  11346. return JSONResponse(
  11347. status_code=401,
  11348. content={"detail": "Authentication required"},
  11349. headers={"WWW-Authenticate": "Bearer"},
  11350. )
  11351. # Validate JWT token
  11352. import jwt
  11353. try:
  11354. from backend.app.core.auth import (
  11355. ALGORITHM,
  11356. SECRET_KEY,
  11357. _is_token_fresh,
  11358. get_user_by_username,
  11359. is_jti_revoked,
  11360. )
  11361. token = auth_header.replace("Bearer ", "")
  11362. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  11363. username = payload.get("sub")
  11364. if not username:
  11365. raise ValueError("No username in token")
  11366. jti = payload.get("jti")
  11367. if not jti:
  11368. raise ValueError("No jti in token")
  11369. iat = payload.get("iat")
  11370. # Verify user exists, is active, and token is still fresh (L-R8-A).
  11371. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  11372. # this session so the gateway adds a single pooled checkout, not two (#2572).
  11373. async with async_session() as db:
  11374. if await is_jti_revoked(jti, db):
  11375. return JSONResponse(
  11376. status_code=401,
  11377. content={"detail": "Token has been revoked"},
  11378. headers={"WWW-Authenticate": "Bearer"},
  11379. )
  11380. user = await get_user_by_username(db, username)
  11381. if not user or not user.is_active:
  11382. return JSONResponse(
  11383. status_code=401,
  11384. content={"detail": "User not found or inactive"},
  11385. headers={"WWW-Authenticate": "Bearer"},
  11386. )
  11387. if not _is_token_fresh(iat, user):
  11388. return JSONResponse(
  11389. status_code=401,
  11390. content={"detail": "Token no longer valid"},
  11391. headers={"WWW-Authenticate": "Bearer"},
  11392. )
  11393. except jwt.ExpiredSignatureError:
  11394. return JSONResponse(
  11395. status_code=401,
  11396. content={"detail": "Token has expired"},
  11397. headers={"WWW-Authenticate": "Bearer"},
  11398. )
  11399. except (jwt.InvalidTokenError, ValueError):
  11400. return JSONResponse(
  11401. status_code=401,
  11402. content={"detail": "Invalid token"},
  11403. headers={"WWW-Authenticate": "Bearer"},
  11404. )
  11405. except Exception:
  11406. # Not a bad token but a failure checking it (database, pool): refuse,
  11407. # as for the probe above, rather than answer 401 -- the frontend reads
  11408. # a 401 from /auth/me as final and signs the user out.
  11409. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  11410. return JSONResponse(
  11411. status_code=503,
  11412. content={"detail": "Authentication service temporarily unavailable"},
  11413. )
  11414. return await call_next(request)
  11415. @app.middleware("http")
  11416. async def trace_id_middleware(request, call_next):
  11417. """Stamp every HTTP request with a trace ID and echo it back.
  11418. Decorated AFTER auth_middleware on purpose: Starlette stacks
  11419. @app.middleware decorators LIFO, so the last-decorated runs first
  11420. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  11421. which means auth-middleware log lines (and every line emitted on the
  11422. way down to and back from the route handler) all carry the same
  11423. trace ID. If we put it before auth, auth's logs would be stamped
  11424. with the *previous* request's ID — useless for correlation.
  11425. Honours an inbound ``X-Trace-Id`` header so callers running their
  11426. own tracing can correlate their span IDs with our log lines, but
  11427. only if the value passes the whitelist gate in
  11428. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  11429. rejected (too long, contains control chars, etc.) silently triggers
  11430. a freshly minted server-side ID rather than failing the request.
  11431. The minted (or echoed) ID is set on a ContextVar so that every log
  11432. record emitted during the request — application logs *and* uvicorn's
  11433. access log — carries it via TraceIDFilter, and is also written to
  11434. the ``X-Trace-Id`` response header so clients can pin a server-side
  11435. log search to the exact request they made.
  11436. """
  11437. from backend.app.core.trace import (
  11438. generate_trace_id,
  11439. normalise_inbound_trace_id,
  11440. trace_id_var,
  11441. )
  11442. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  11443. trace_id = inbound if inbound is not None else generate_trace_id()
  11444. token = trace_id_var.set(trace_id)
  11445. try:
  11446. response = await call_next(request)
  11447. finally:
  11448. # Reset the ContextVar so a record emitted in a totally
  11449. # unrelated background task that just happens to inherit this
  11450. # context doesn't keep referencing this request's ID forever.
  11451. # In practice ContextVar.reset is best-effort under asyncio
  11452. # task-spawn semantics, but the cost is one attribute write so
  11453. # we may as well do it.
  11454. trace_id_var.reset(token)
  11455. response.headers["X-Trace-Id"] = trace_id
  11456. return response
  11457. # API routes
  11458. app.include_router(auth.router, prefix=app_settings.api_prefix)
  11459. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  11460. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  11461. app.include_router(users.router, prefix=app_settings.api_prefix)
  11462. app.include_router(groups.router, prefix=app_settings.api_prefix)
  11463. app.include_router(printers.router, prefix=app_settings.api_prefix)
  11464. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  11465. app.include_router(archives.router, prefix=app_settings.api_prefix)
  11466. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  11467. app.include_router(finance.router, prefix=app_settings.api_prefix)
  11468. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  11469. app.include_router(labels.router, prefix=app_settings.api_prefix)
  11470. app.include_router(label_templates.router, prefix=app_settings.api_prefix)
  11471. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  11472. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  11473. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  11474. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  11475. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  11476. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  11477. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  11478. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  11479. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  11480. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  11481. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  11482. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  11483. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  11484. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  11485. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  11486. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  11487. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  11488. app.include_router(updates.router, prefix=app_settings.api_prefix)
  11489. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  11490. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  11491. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  11492. app.include_router(camera.router, prefix=app_settings.api_prefix)
  11493. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  11494. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  11495. app.include_router(projects.router, prefix=app_settings.api_prefix)
  11496. app.include_router(library.router, prefix=app_settings.api_prefix)
  11497. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  11498. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  11499. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  11500. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  11501. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  11502. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  11503. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  11504. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  11505. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  11506. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  11507. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  11508. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  11509. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  11510. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  11511. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  11512. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  11513. app.include_router(system.router, prefix=app_settings.api_prefix)
  11514. app.include_router(support.router, prefix=app_settings.api_prefix)
  11515. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  11516. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  11517. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  11518. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  11519. app.include_router(bulk.router, prefix=app_settings.api_prefix)
  11520. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  11521. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  11522. app.include_router(obico.router, prefix=app_settings.api_prefix)
  11523. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  11524. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  11525. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  11526. # Serve static files (React build)
  11527. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  11528. # Compressed, and cached for good where Vite hashed the name (#3175).
  11529. app.mount(
  11530. "/assets",
  11531. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  11532. name="assets",
  11533. )
  11534. if (app_settings.static_dir / "img").exists():
  11535. app.mount(
  11536. "/img",
  11537. StaticFiles(directory=app_settings.static_dir / "img"),
  11538. name="img",
  11539. )
  11540. if (app_settings.static_dir / "icons").exists():
  11541. app.mount(
  11542. "/icons",
  11543. StaticFiles(directory=app_settings.static_dir / "icons"),
  11544. name="icons",
  11545. )
  11546. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  11547. # falls through to the SPA catch-all and returns index.html, which the
  11548. # browser's font sanitizer rejects ("downloadable font: rejected by
  11549. # sanitizer").
  11550. if (app_settings.static_dir / "fonts").exists():
  11551. app.mount(
  11552. "/fonts",
  11553. StaticFiles(directory=app_settings.static_dir / "fonts"),
  11554. name="fonts",
  11555. )
  11556. @app.get("/")
  11557. async def serve_frontend():
  11558. """Serve the React frontend."""
  11559. index_file = app_settings.static_dir / "index.html"
  11560. if index_file.exists():
  11561. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11562. return {
  11563. "message": "Bambuddy API",
  11564. "docs": "/docs",
  11565. "frontend": "Build and place React app in /static directory",
  11566. }
  11567. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  11568. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  11569. # forever, but the HTML wrapping it is the only file that knows which hash
  11570. # is current. Without explicit cache-control headers Chromium decides
  11571. # heuristically (typically 10% of the time since Last-Modified) and on
  11572. # long-running kiosks happily serves stale HTML across browser restarts.
  11573. # That stale HTML references an old bundle hash, the old bundle is also
  11574. # in the disk cache, and the user ends up running pre-update JS forever
  11575. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  11576. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  11577. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  11578. @app.get("/health")
  11579. async def health_check():
  11580. """Health check endpoint."""
  11581. return {"status": "healthy"}
  11582. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  11583. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  11584. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  11585. # in deployment debugging. One decorator per method, not api_route(methods=
  11586. # [...]): api_route gives both methods the same OpenAPI operation id.
  11587. @app.get("/manifest.json")
  11588. @app.head("/manifest.json")
  11589. async def serve_manifest():
  11590. """Serve PWA manifest."""
  11591. manifest_file = app_settings.static_dir / "manifest.json"
  11592. if manifest_file.exists():
  11593. return FileResponse(manifest_file, media_type="application/manifest+json")
  11594. return {"error": "Manifest not found"}
  11595. @app.get("/sw.js")
  11596. @app.head("/sw.js")
  11597. async def serve_service_worker():
  11598. """Serve service worker."""
  11599. sw_file = app_settings.static_dir / "sw.js"
  11600. if sw_file.exists():
  11601. return FileResponse(
  11602. sw_file,
  11603. media_type="application/javascript",
  11604. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  11605. )
  11606. return {"error": "Service worker not found"}
  11607. @app.get("/sw-register.js")
  11608. @app.head("/sw-register.js")
  11609. async def serve_sw_register():
  11610. """Serve the service-worker registration bootstrap script.
  11611. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  11612. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  11613. """
  11614. reg_file = app_settings.static_dir / "sw-register.js"
  11615. if reg_file.exists():
  11616. return FileResponse(reg_file, media_type="application/javascript")
  11617. return {"error": "sw-register.js not found"}
  11618. # ── GCode viewer static files ────────────────────────────────────────────────
  11619. # Catch-all route for React Router (must be last)
  11620. @app.get("/{full_path:path}")
  11621. async def serve_spa(full_path: str):
  11622. """Serve React app for client-side routing."""
  11623. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  11624. if full_path.startswith("api/"):
  11625. from fastapi import HTTPException
  11626. raise HTTPException(status_code=404, detail="Not found")
  11627. index_file = app_settings.static_dir / "index.html"
  11628. if index_file.exists():
  11629. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11630. return {"error": "Frontend not built"}