main.py 457 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557
  1. import asyncio
  2. import json
  3. import logging
  4. import os
  5. import posixpath
  6. import secrets
  7. import time
  8. from contextlib import asynccontextmanager
  9. from datetime import datetime, timedelta, timezone
  10. from logging.handlers import RotatingFileHandler
  11. from pathlib import Path, PurePosixPath
  12. from urllib.parse import urlparse
  13. from fastapi import FastAPI
  14. from fastapi.responses import FileResponse
  15. from fastapi.staticfiles import StaticFiles
  16. from sqlalchemy import delete, or_, select, text
  17. from backend.app.api.routes import (
  18. ams_history,
  19. api_keys,
  20. archive_purge,
  21. archives,
  22. auth,
  23. bug_report,
  24. camera,
  25. camwall,
  26. cloud,
  27. discovery,
  28. external_links,
  29. filaments,
  30. finance,
  31. firmware,
  32. github_backup,
  33. groups,
  34. ha_sensors,
  35. inventory,
  36. kprofiles,
  37. labels,
  38. library,
  39. library_tags,
  40. library_trash,
  41. library_variants,
  42. local_backup,
  43. local_presets,
  44. location_ha_sensors,
  45. maintenance,
  46. makerworld,
  47. metrics,
  48. mfa,
  49. notification_templates,
  50. notifications,
  51. obico,
  52. orca_cloud,
  53. pending_uploads,
  54. pipeline_runs,
  55. print_log,
  56. print_queue,
  57. printer_sensor_history,
  58. printers,
  59. projects,
  60. scheduled_dryings,
  61. settings as settings_routes,
  62. slice_jobs,
  63. slicer_pipelines,
  64. slicer_presets,
  65. smart_plugs,
  66. sponsor_prompt,
  67. spoolbuddy,
  68. spoolman,
  69. spoolman_inventory,
  70. support,
  71. system,
  72. updates,
  73. user_notifications,
  74. users,
  75. virtual_printers,
  76. webhook,
  77. websocket,
  78. )
  79. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  80. from backend.app.api.routes.support import init_debug_logging
  81. from backend.app.core.config import APP_VERSION, settings as app_settings
  82. from backend.app.core.database import async_session, engine, init_db
  83. from backend.app.core.tasks import spawn_background_task
  84. from backend.app.core.websocket import ws_manager
  85. from backend.app.services import print_dispatch_context
  86. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  87. from backend.app.services.archive_purge import archive_purge_service
  88. from backend.app.services.bambu_ftp import (
  89. FileNotOnPrinterError,
  90. cache_3mf_download,
  91. clear_3mf_cache,
  92. download_file_async,
  93. download_file_try_paths_async,
  94. ftps_handshake_blocked,
  95. get_cached_3mf,
  96. get_ftp_retry_settings,
  97. normalize_3mf_name,
  98. with_ftp_retry,
  99. )
  100. from backend.app.services.bambu_mqtt import PrinterState
  101. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  102. from backend.app.services.github_backup import github_backup_service
  103. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  104. from backend.app.services.homeassistant import homeassistant_service
  105. from backend.app.services.library_trash import library_trash_service
  106. from backend.app.services.local_backup import local_backup_service
  107. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  108. from backend.app.services.mqtt_relay import mqtt_relay
  109. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  110. from backend.app.services.notification_service import notification_service
  111. from backend.app.services.obico_detection import obico_detection_service
  112. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  113. from backend.app.services.print_scheduler import scheduler as print_scheduler
  114. from backend.app.services.print_storage import (
  115. REASON_FTPS_COOLOFF,
  116. external_storage_present,
  117. ftp_probe_paths,
  118. print_file_reachable_over_ftp,
  119. )
  120. from backend.app.services.printer_manager import (
  121. init_printer_connections,
  122. parse_plate_id,
  123. printer_manager,
  124. printer_state_to_dict,
  125. resolve_plate_id,
  126. )
  127. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  128. from backend.app.services.smart_plug_manager import smart_plug_manager
  129. from backend.app.services.spool_assignment_notifications import (
  130. notify_missing_spool_assignments_on_print_start,
  131. )
  132. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  133. from backend.app.services.spoolman_tracking import (
  134. cleanup_tracking as _cleanup_spoolman_tracking,
  135. report_usage as _report_spoolman_usage,
  136. store_print_data as _store_spoolman_print_data,
  137. )
  138. from backend.app.services.tasmota import tasmota_service
  139. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  140. from backend.app.utils.filament_types import printer_filament_type
  141. from backend.app.utils.fts_routing import extruder_for_inlet, slot_extruder as resolve_slot_extruder
  142. from backend.app.utils.local_time import utcnow_naive
  143. from backend.app.utils.print_jobs import is_internal_printer_job
  144. # =============================================================================
  145. # Dependency Check - runs before other imports to give helpful error messages
  146. # =============================================================================
  147. def _start_error_server(missing_packages: list):
  148. """Start a minimal HTTP server to display dependency errors in browser."""
  149. import os
  150. import signal
  151. from http.server import BaseHTTPRequestHandler, HTTPServer
  152. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  153. html = f"""<!DOCTYPE html>
  154. <html>
  155. <head>
  156. <title>Bambuddy - Setup Required</title>
  157. <style>
  158. body {{
  159. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  160. background: #0f172a; color: #e2e8f0;
  161. display: flex; justify-content: center; align-items: center;
  162. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  163. }}
  164. .container {{
  165. background: #1e293b; border-radius: 12px; padding: 40px;
  166. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  167. }}
  168. h1 {{ color: #f87171; margin-bottom: 10px; }}
  169. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  170. .packages {{
  171. background: #0f172a; border-radius: 8px; padding: 20px;
  172. margin: 20px 0; text-align: left;
  173. }}
  174. .packages ul {{ margin: 0; padding-left: 20px; }}
  175. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  176. .command {{
  177. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  178. margin: 15px 0; font-family: monospace; color: #4ade80;
  179. text-align: left; overflow-x: auto;
  180. }}
  181. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  182. </style>
  183. </head>
  184. <body>
  185. <div class="container">
  186. <h1>Setup Required</h1>
  187. <h2>Missing Python packages</h2>
  188. <div class="packages"><ul>{packages_html}</ul></div>
  189. <p>To fix, run this command on your server:</p>
  190. <div class="command">pip install -r requirements.txt</div>
  191. <p>Or if using a virtual environment:</p>
  192. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  193. <p class="note">After installing, restart Bambuddy:<br>
  194. <code>sudo systemctl restart bambuddy</code></p>
  195. </div>
  196. </body>
  197. </html>"""
  198. class ErrorHandler(BaseHTTPRequestHandler):
  199. def do_GET(self):
  200. self.send_response(503)
  201. self.send_header("Content-type", "text/html")
  202. self.end_headers()
  203. self.wfile.write(html.encode())
  204. def log_message(self, format, *args):
  205. print(f"[Error Server] {args[0]}")
  206. port = int(os.environ.get("PORT", 8000))
  207. print(f"\nStarting error server on http://0.0.0.0:{port}")
  208. print("Visit this URL in your browser to see the error details.\n")
  209. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  210. def shutdown(signum, frame):
  211. print("\nShutting down error server...")
  212. raise SystemExit(0)
  213. signal.signal(signal.SIGTERM, shutdown)
  214. signal.signal(signal.SIGINT, shutdown)
  215. server.serve_forever()
  216. def check_dependencies():
  217. """Check that all required packages are installed."""
  218. missing = []
  219. # Map of import name -> package name (for pip install)
  220. required = {
  221. "jwt": "PyJWT",
  222. "fastapi": "fastapi",
  223. "uvicorn": "uvicorn",
  224. "sqlalchemy": "sqlalchemy",
  225. "aiosqlite": "aiosqlite",
  226. "pydantic": "pydantic",
  227. "paho.mqtt": "paho-mqtt",
  228. }
  229. for module, package in required.items():
  230. try:
  231. __import__(module)
  232. except ImportError:
  233. missing.append(package)
  234. if missing:
  235. print("\n" + "=" * 60)
  236. print("ERROR: Missing required Python packages!")
  237. print("=" * 60)
  238. print(f"\nMissing packages: {', '.join(missing)}")
  239. print("\nTo fix, run:")
  240. print(" pip install -r requirements.txt")
  241. print("\nOr if using a virtual environment:")
  242. print(" ./venv/bin/pip install -r requirements.txt")
  243. print("=" * 60 + "\n")
  244. _start_error_server(missing)
  245. check_dependencies()
  246. # =============================================================================
  247. # Import settings first for logging configuration
  248. # Configure logging based on settings
  249. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  250. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  251. log_level = getattr(logging, log_level_str, logging.INFO)
  252. # Trace ID column ([-] when no request scope is active — startup, MQTT
  253. # callbacks, scheduled tasks not chained from a request — so the column
  254. # stays visually aligned and missing values are obvious in grep). See
  255. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  256. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  257. # Create root logger
  258. root_logger = logging.getLogger()
  259. root_logger.setLevel(log_level)
  260. # Trace-ID injection: this filter populates record.trace_id from the
  261. # per-request ContextVar so the format string above can reference it.
  262. # Attached to each HANDLER (not the root logger) because Python's
  263. # logging semantics only invoke a logger's filters on records that
  264. # *originated* at that logger — records propagated up from child
  265. # loggers (every named logger in the app) never trigger root's filter.
  266. # Putting it on the handlers means every record any handler emits gets
  267. # trace_id injected just before the formatter runs, regardless of which
  268. # logger created the record. Without this, the formatter raises
  269. # KeyError on every child-logger record and the record is silently
  270. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  271. # partially" bug we hit. See backend/app/core/trace.py for the
  272. # ContextVar the filter reads.
  273. from backend.app.core.trace import TraceIDFilter
  274. _trace_id_filter = TraceIDFilter()
  275. # Console handler - always enabled
  276. console_handler = logging.StreamHandler()
  277. console_handler.setLevel(log_level)
  278. console_handler.setFormatter(logging.Formatter(log_format))
  279. console_handler.addFilter(_trace_id_filter)
  280. root_logger.addHandler(console_handler)
  281. # File handler - only in production or if explicitly enabled
  282. if app_settings.log_to_file:
  283. log_file = app_settings.log_dir / "bambuddy.log"
  284. file_handler = RotatingFileHandler(
  285. log_file,
  286. maxBytes=app_settings.log_max_bytes,
  287. backupCount=app_settings.log_backup_count,
  288. encoding="utf-8",
  289. )
  290. file_handler.setLevel(log_level)
  291. file_handler.setFormatter(logging.Formatter(log_format))
  292. file_handler.addFilter(_trace_id_filter)
  293. root_logger.addHandler(file_handler)
  294. logging.info("Logging to file: %s", log_file)
  295. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  296. # access logger with propagate=False by default, so without this attach
  297. # there is no on-disk record of which endpoint triggered a server-state
  298. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  299. # for exactly this reason. Filtered to write methods only
  300. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  301. # frontend don't churn the rotation window faster than it's useful.
  302. from backend.app.core.logging_filters import (
  303. CancelledPoolNoiseFilter,
  304. WriteRequestsOnlyFilter,
  305. )
  306. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  307. uvicorn_access_logger.addHandler(file_handler)
  308. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  309. # Uvicorn's access logger has propagate=False (its own default), so the
  310. # root-attached TraceIDFilter never sees these records. Attach a
  311. # second instance directly so HTTP access lines carry the same trace
  312. # ID column as the application logs they correlate with.
  313. uvicorn_access_logger.addFilter(TraceIDFilter())
  314. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  315. # BaseHTTPMiddleware cancelling the inner task scope on client
  316. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  317. # underlying transaction leak; this filter only suppresses the residual
  318. # log records that pre-existing pools still emit during their cleanup.
  319. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  320. # Reduce noise from third-party libraries in production
  321. if not app_settings.debug:
  322. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  323. logging.getLogger("httpcore").setLevel(logging.WARNING)
  324. logging.getLogger("httpx").setLevel(logging.WARNING)
  325. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  326. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  327. # Track active prints: {(printer_id, filename): archive_id}
  328. _active_prints: dict[tuple[int, str], int] = {}
  329. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  330. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  331. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  332. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  333. # instead of running its own grab-now chain when present, so the finish photo
  334. # captures the better-framed pre-bed-drop moment without us having to force
  335. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  336. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  337. #
  338. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  339. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  340. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  341. # bank and the others are not — so the consumer can't tell them apart and
  342. # must not rotate again.
  343. _stage22_finish_frames: dict[int, bytes] = {}
  344. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  345. # `finally` block (whether it captured a frame or not). The consumer in
  346. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  347. # so the FINISH-state fallback path — where moment and completion are dispatched
  348. # back-to-back — doesn't race past the producer with an empty pop, and the
  349. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  350. # grab (Bambu printers allow only one RTSP client at a time).
  351. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  352. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  353. # layer-change and on print-progress advances (#2547) while the model is still
  354. # printing, then consumed by the FINISH-state finish-photo path when the
  355. # dispatcher recorded that it injected End G-code into this print. Bambu
  356. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  357. # plate-swap) has run, so a live grab there would capture the swapped/empty
  358. # plate.
  359. #
  360. # The load-bearing property: both drivers are print telemetry that stops before
  361. # the End G-code executes — no further layer_num increases, and mc_percent
  362. # freezes — so the last banked frame is always the finished print before the
  363. # swap. Anything added as a third driver must hold that same property.
  364. _inprint_frame_bank: dict[int, bytes] = {}
  365. # Monotonic timestamp of the last banked frame per printer — throttles banking
  366. # so tall prints don't add a camera grab on every layer.
  367. _inprint_frame_bank_ts: dict[int, float] = {}
  368. # Minimum seconds between banked frames, except the final object layer which
  369. # always refreshes for the best framing.
  370. _INPRINT_BANK_MIN_INTERVAL = 25.0
  371. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  372. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  373. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  374. # the first connected status update for that connection; transitions back
  375. # to False whenever we observe `state.connected = False` so the next
  376. # reconnect re-arms reconciliation. Keyed by printer_id.
  377. _printer_reconciled_since_connect: dict[int, bool] = {}
  378. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  379. # {(printer_id, filename): archive_id}
  380. _expected_prints: dict[tuple[int, str], int] = {}
  381. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  382. # Used by usage tracker to map 3MF slots to physical AMS trays
  383. _print_ams_mappings: dict[int, list[int]] = {}
  384. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  385. _print_cost_center_ids: dict[int, int] = {}
  386. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  387. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  388. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  389. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  390. # for the queue path. Cleared on print completion or TTL eviction.
  391. _print_plate_ids: dict[int, int] = {}
  392. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  393. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  394. _last_progress_milestone: dict[int, int] = {}
  395. # Track whether first layer complete notification has been sent for current print
  396. _first_layer_notified: dict[int, bool] = {}
  397. # Track whether we already sent a kill-switch stop for the current unauthorized print
  398. _unauthorized_print_kill_sent: set[int] = set()
  399. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  400. # lookup briefly so an unknown active print does not query the database on
  401. # every status frame. A short TTL keeps settings changes responsive.
  402. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  403. _kill_switch_setting_cache: tuple[bool, float] | None = None
  404. # Provider notification started when the kill switch stops a print. The later
  405. # MQTT print-complete callback awaits this task and only sends its regular
  406. # provider notification when the immediate attempt failed.
  407. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  408. # Track HMS errors that have been notified: {printer_id: set of error codes}
  409. # This prevents sending duplicate notifications for the same error
  410. _notified_hms_errors: dict[int, set[str]] = {}
  411. # Track when HMS errors were last seen: {printer_id: timestamp}
  412. # Used to debounce clearing — prevents flapping errors from re-triggering notifications
  413. _hms_last_seen: dict[int, float] = {}
  414. _HMS_CLEAR_GRACE_SECONDS = 30.0
  415. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  416. # Used for snapshot-diff detection at print completion
  417. _timelapse_baselines: dict[int, set[str]] = {}
  418. # Track printers waiting for bed to cool after print completion.
  419. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  420. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  421. _bed_cool_waiters: dict[int, dict] = {}
  422. # Track printers where the user explicitly stopped the print from the queue UI.
  423. # When on_print_complete fires with status "failed" for these printers we treat it
  424. # as "cancelled" (stopped by user) so the correct notification email is sent.
  425. _user_stopped_printers: set[int] = set()
  426. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  427. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  428. # holds the previous observation so we only fire on the True → False edge (a
  429. # False → False repeat doesn't notify; an initial False at startup doesn't
  430. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  431. # holds the per-printer pending asyncio task that fires the notification
  432. # after a debounce window — cancelled if the printer reconnects before the
  433. # window elapses, so transient MQTT blips don't flood the user.
  434. _printer_last_connected: dict[int, bool] = {}
  435. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  436. # Debounce: a printer must stay offline this long before we notify. Sized
  437. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  438. # so a single stale-trigger cooldown isn't enough to fire — only a real
  439. # offline that survives one reconnect attempt notifies.
  440. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  441. # HMS short-code → human-readable failure reason. Used by _dispatch_archive_update
  442. # when status="failed" to label the print's failure_reason in archives.
  443. #
  444. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  445. # which is wrong on two counts:
  446. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  447. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  448. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  449. # the public wiki) as part of its user-cancel sequence. Matching on the module
  450. # alone caused user-cancellations to be archived as "Layer shift" failures.
  451. # We now match by full short code only — anything not in this map leaves
  452. # failure_reason=None rather than guessing.
  453. _HMS_FAILURE_REASONS: dict[str, str] = {
  454. # Layer shift / step loss
  455. "0300_4057": "Layer shift",
  456. "0300_4068": "Layer shift",
  457. "0300_800C": "Layer shift",
  458. # Filament runout (printer-side & per-AMS-slot)
  459. "0300_8004": "Filament runout",
  460. "0700_8011": "Filament runout",
  461. "0701_8011": "Filament runout",
  462. "0702_8011": "Filament runout",
  463. "0703_8011": "Filament runout",
  464. "0704_8011": "Filament runout",
  465. "0705_8011": "Filament runout",
  466. "0706_8011": "Filament runout",
  467. "0707_8011": "Filament runout",
  468. "07FF_8011": "Filament runout",
  469. # Clogged nozzle / extruder
  470. "0300_4006": "Clogged nozzle",
  471. "0300_8016": "Clogged nozzle",
  472. "0300_801C": "Clogged nozzle",
  473. "0700_8003": "Clogged nozzle",
  474. "0700_8007": "Clogged nozzle",
  475. "0700_8013": "Clogged nozzle",
  476. "0701_8003": "Clogged nozzle",
  477. "0701_8007": "Clogged nozzle",
  478. "0701_8013": "Clogged nozzle",
  479. "0702_8003": "Clogged nozzle",
  480. }
  481. def _hms_short_code(attr: int, code: int | str) -> str:
  482. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  483. if isinstance(code, str):
  484. code_int = int(code.replace("0x", ""), 16) if code else 0
  485. else:
  486. code_int = int(code or 0)
  487. attr_int = int(attr or 0)
  488. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  489. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  490. """Derive a human-readable failure_reason for an archived print.
  491. Returns "User cancelled" for cancelled/aborted prints; for failed prints,
  492. returns the first matching reason from _HMS_FAILURE_REASONS, or None when
  493. no HMS code matches (don't guess — null is honest).
  494. """
  495. if status in ("aborted", "cancelled"):
  496. return "User cancelled"
  497. if status != "failed":
  498. return None
  499. for err in hms_errors or []:
  500. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  501. if short_code in _HMS_FAILURE_REASONS:
  502. return _HMS_FAILURE_REASONS[short_code]
  503. return None
  504. # Track created_by_id for expected prints so the user email can be sent even when
  505. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  506. # {(printer_id, filename): created_by_id}
  507. _expected_print_creators: dict[tuple[int, str], int] = {}
  508. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  509. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  510. # updates for the same printer in quick succession (~30 ms apart, observed in
  511. # the wild on H2D + dual AMS).
  512. #
  513. # Without this serialisation, two concurrent on_ams_change callbacks each read
  514. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  515. # the second commit hits
  516. # IntegrityError: duplicate key value violates unique constraint
  517. # "spool_assignment_printer_id_ams_id_tray_id_key"
  518. # SQLite's WAL serial-write semantics had been silently swallowing the race
  519. # until optional Postgres support landed (asyncpg allows true concurrent
  520. # transactions and surfaces the constraint violation).
  521. #
  522. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  523. # assign) are inside the lock. The Spoolman sync block further down stays
  524. # concurrent because it's network-bound and idempotent.
  525. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  526. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  527. """Return the per-printer assignment lock, creating it on first use."""
  528. lock = _ams_assignment_locks.get(printer_id)
  529. if lock is None:
  530. lock = asyncio.Lock()
  531. _ams_assignment_locks[printer_id] = lock
  532. return lock
  533. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  534. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  535. # tag tuple changes for the slot. Cleared when the slot is reported empty
  536. # so remove + reinsert reliably re-prompts the UI.
  537. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  538. async def _broadcast_unknown_tag(
  539. *,
  540. printer_id: int,
  541. ams_id: int,
  542. tray_id: int,
  543. tag_uid: str,
  544. tray_uuid: str,
  545. tray_type: str | None = None,
  546. tray_color: str | None = None,
  547. tray_sub_brands: str | None = None,
  548. tray_count: int | None = None,
  549. ) -> None:
  550. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  551. _logger = logging.getLogger(__name__)
  552. slot_key = (ams_id, tray_id)
  553. tag_key = (tag_uid or "", tray_uuid or "")
  554. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  555. if per_printer.get(slot_key) == tag_key:
  556. _logger.debug(
  557. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  558. printer_id,
  559. ams_id,
  560. tray_id,
  561. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  562. )
  563. return
  564. _logger.info(
  565. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  566. printer_id,
  567. ams_id,
  568. tray_id,
  569. tray_type,
  570. tray_color,
  571. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  572. )
  573. # Broadcast first; only commit the dedup if the WS write succeeds.
  574. # If broadcast raises, the next MQTT push retries instead of being
  575. # permanently silenced by a poisoned dedup entry.
  576. await ws_manager.broadcast(
  577. {
  578. "type": "unknown_tag",
  579. "printer_id": printer_id,
  580. "ams_id": ams_id,
  581. "tray_id": tray_id,
  582. "tag_uid": tag_uid,
  583. "tray_uuid": tray_uuid,
  584. "tray_type": tray_type,
  585. "tray_color": tray_color,
  586. "tray_sub_brands": tray_sub_brands,
  587. "tray_count": tray_count,
  588. }
  589. )
  590. per_printer[slot_key] = tag_key
  591. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  592. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  593. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  594. if per_printer is None:
  595. return
  596. per_printer.pop((ams_id, tray_id), None)
  597. # TTL for expected-print entries: evict registrations older than this to prevent
  598. # unbounded growth when a print is registered but never starts (e.g. printer
  599. # disconnect, app restart, print started from the printer panel).
  600. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  601. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  602. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  603. # Cleanup loop interval
  604. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  605. _expected_prints_cleanup_task: asyncio.Task | None = None
  606. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  607. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  608. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  609. possible_keys: list[tuple[int, str]] = []
  610. filename = (state.gcode_file or state.current_print or "").strip()
  611. subtask_name = (state.subtask_name or "").strip()
  612. if subtask_name:
  613. possible_keys.append((printer_id, subtask_name))
  614. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  615. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  616. if filename:
  617. base_name = filename.rsplit("/", 1)[-1]
  618. if base_name.endswith(".gcode.3mf"):
  619. root_name = base_name[: -len(".gcode.3mf")]
  620. possible_keys.append((printer_id, root_name))
  621. possible_keys.append((printer_id, base_name))
  622. possible_keys.append((printer_id, f"{root_name}.gcode"))
  623. possible_keys.append((printer_id, f"{root_name}.3mf"))
  624. elif base_name.endswith(".3mf"):
  625. root_name = base_name[: -len(".3mf")]
  626. possible_keys.append((printer_id, root_name))
  627. possible_keys.append((printer_id, base_name))
  628. elif base_name.endswith(".gcode"):
  629. root_name = base_name[: -len(".gcode")]
  630. possible_keys.append((printer_id, root_name))
  631. possible_keys.append((printer_id, f"{root_name}.3mf"))
  632. possible_keys.append((printer_id, base_name))
  633. else:
  634. possible_keys.append((printer_id, base_name))
  635. possible_keys.append((printer_id, f"{base_name}.3mf"))
  636. return possible_keys
  637. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  638. """Check the cheap, process-local print ownership signals."""
  639. if printer_manager.get_current_print_user(printer_id):
  640. return True
  641. return any(key in _expected_prints or key in _active_prints for key in _build_status_print_keys(printer_id, state))
  642. async def _is_printer_kill_switch_enabled_cached() -> bool:
  643. """Return the kill-switch setting without querying on every MQTT frame."""
  644. global _kill_switch_setting_cache
  645. now = time.monotonic()
  646. if _kill_switch_setting_cache is not None:
  647. enabled, expires_at = _kill_switch_setting_cache
  648. if now < expires_at:
  649. return enabled
  650. async with async_session() as db:
  651. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  652. enabled = await is_printer_kill_switch_enabled(db)
  653. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  654. return enabled
  655. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  656. """Resolve whether the current print was started by Bambuddy.
  657. ``None`` means identity is not yet safe to decide. The kill switch must
  658. defer in that case: stopping a print is irreversible, and the first status
  659. frames after a restart may arrive before all subtask fields are populated.
  660. """
  661. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  662. return True
  663. possible_keys = _build_status_print_keys(printer_id, state)
  664. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  665. # is on disk. subtask_id is minted per print and pins the answer to the job
  666. # actually running, rather than to an unrelated one that reuses a filename.
  667. raw_subtask_id = getattr(state, "subtask_id", None)
  668. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  669. if subtask_id in ("", "0"):
  670. return None
  671. from backend.app.models.archive import PrintArchive
  672. result = await db.execute(
  673. select(PrintArchive)
  674. .where(
  675. PrintArchive.printer_id == printer_id,
  676. PrintArchive.status == "printing",
  677. PrintArchive.subtask_id == subtask_id,
  678. )
  679. .order_by(PrintArchive.created_at.desc())
  680. .limit(1)
  681. )
  682. archive = result.scalar_one_or_none()
  683. # An archive row on its own proves nothing: `on_print_start` archives every
  684. # print it observes, including ones started from Bambu Studio or Handy, and
  685. # stamps them with the same status and subtask_id. Authorizing on its mere
  686. # existence would disable the kill switch the moment the 3MF finishes
  687. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  688. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  689. # (carried over from the queue item that started it).
  690. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  691. # Rehydrate the fast in-memory path for subsequent status frames. Include
  692. # both the archive filename and every normalized key reported by MQTT.
  693. _active_prints[(printer_id, archive.filename)] = archive.id
  694. for key in possible_keys:
  695. _active_prints[key] = archive.id
  696. return True
  697. # No dispatch marker. Before calling this someone else's print, check whether
  698. # Bambuddy has a job of its own running on this printer: a library-file
  699. # dispatch has no archive at send time, and an archive created seconds later
  700. # by `on_print_start` carries neither marker. The queue row, which the
  701. # scheduler commits to status="printing" before the MQTT send, is the one
  702. # durable record every Bambuddy print has. It cannot be tied to this
  703. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  704. # print is irreversible, and refusing to act costs nothing but a log line.
  705. from backend.app.models.print_queue import PrintQueueItem
  706. dispatched_here = await db.scalar(
  707. select(PrintQueueItem.id)
  708. .where(
  709. PrintQueueItem.printer_id == printer_id,
  710. PrintQueueItem.status == "printing",
  711. )
  712. .limit(1)
  713. )
  714. if dispatched_here is not None:
  715. return None
  716. return False
  717. async def _send_kill_switch_provider_notification(
  718. printer_id: int,
  719. printer_name: str,
  720. data: dict,
  721. ) -> bool:
  722. """Send the immediate print-stopped provider notification.
  723. Returning a success flag lets the normal MQTT completion path retry when
  724. this early notification could not be delivered.
  725. """
  726. logger = logging.getLogger(__name__)
  727. try:
  728. async with async_session() as db:
  729. await notification_service.on_print_complete(
  730. printer_id,
  731. printer_name,
  732. "stopped",
  733. data,
  734. db,
  735. )
  736. return True
  737. except Exception as e:
  738. logger.warning(
  739. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  740. printer_id,
  741. e,
  742. )
  743. return False
  744. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  745. """Wait for an immediate kill-switch notification, if one was scheduled."""
  746. if task is None:
  747. return False
  748. try:
  749. return await task
  750. except Exception as e:
  751. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  752. return False
  753. async def _get_plug_energy(plug, db) -> dict | None:
  754. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  755. For HA plugs, configures the service with current settings from DB.
  756. For MQTT plugs, returns data from the subscription service.
  757. For REST plugs, polls the status URL with JSON path extraction.
  758. """
  759. if plug.plug_type == "homeassistant":
  760. from backend.app.api.routes.settings import get_homeassistant_settings
  761. ha_settings = await get_homeassistant_settings(db)
  762. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  763. return await homeassistant_service.get_energy(plug)
  764. elif plug.plug_type == "mqtt":
  765. # MQTT plugs report "today" energy, not lifetime total
  766. # For per-print tracking, we use "today" as the counter (resets at midnight)
  767. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  768. if mqtt_data:
  769. return {
  770. "power": mqtt_data.power,
  771. "today": mqtt_data.energy,
  772. "total": mqtt_data.energy, # Use today as total for per-print calculations
  773. }
  774. return None
  775. elif plug.plug_type == "rest":
  776. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  777. return await rest_smart_plug_service.get_energy(plug)
  778. else:
  779. return await tasmota_service.get_energy(plug)
  780. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  781. """Capture the smart plug lifetime counter on the archive at print start.
  782. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  783. tracking survives a backend restart mid-print. The print-end handler reads
  784. this value back from the DB and computes the delta against the current
  785. plug counter.
  786. """
  787. _logger = logging.getLogger(__name__)
  788. try:
  789. candidates = await energy_plug_candidates(db, printer_id)
  790. if not candidates:
  791. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  792. return False
  793. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  794. if selected is None:
  795. # Naming the plugs matters here: with several linked to one printer
  796. # this is the difference between "the meter is offline" and "you
  797. # linked only accessories" (#2859).
  798. _logger.warning(
  799. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  800. printer_id,
  801. archive.id,
  802. ", ".join(plug.name for plug in candidates),
  803. )
  804. return False
  805. plug, energy = selected
  806. archive.energy_start_kwh = float(energy["total"])
  807. await db.commit()
  808. _logger.info(
  809. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  810. f" ({context})" if context else "",
  811. archive.id,
  812. plug.name,
  813. energy["total"],
  814. )
  815. return True
  816. except Exception as e:
  817. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  818. return False
  819. def register_expected_print(
  820. printer_id: int,
  821. filename: str,
  822. archive_id: int,
  823. ams_mapping: list[int] | None = None,
  824. created_by_id: int | None = None,
  825. cost_center_id: int | None = None,
  826. plate_id: int | None = None,
  827. ):
  828. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  829. # Store with multiple filename variations to catch different naming patterns
  830. _expected_prints[(printer_id, filename)] = archive_id
  831. # Also store without .3mf extension if present
  832. if filename.endswith(".3mf"):
  833. base = filename[:-4]
  834. _expected_prints[(printer_id, base)] = archive_id
  835. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  836. # Store AMS mapping for usage tracking at print completion
  837. if ams_mapping is not None:
  838. _print_ams_mappings[archive_id] = ams_mapping
  839. if cost_center_id is not None:
  840. _print_cost_center_ids[archive_id] = cost_center_id
  841. # Store plate_id for usage tracking when this is a single-plate dispatch from
  842. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  843. # file's filament total to the spool instead of just the printed plate (#1697).
  844. if plate_id is not None:
  845. _print_plate_ids[archive_id] = plate_id
  846. # Store created_by_id so the user start email can be sent even when the archive
  847. # itself has no created_by_id (e.g. library-file-based queue prints)
  848. if created_by_id is not None:
  849. _expected_print_creators[(printer_id, filename)] = created_by_id
  850. if filename.endswith(".3mf"):
  851. base = filename[:-4]
  852. _expected_print_creators[(printer_id, base)] = created_by_id
  853. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  854. # Record registration time for TTL-based eviction
  855. _registered_at = time.monotonic()
  856. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  857. if filename.endswith(".3mf"):
  858. base = filename[:-4]
  859. _expected_print_registered_at[(printer_id, base)] = _registered_at
  860. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  861. logging.getLogger(__name__).info(
  862. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  863. )
  864. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  865. """Undo :func:`register_expected_print` when the print never went out.
  866. Registration has to happen *before* the MQTT print command, because the
  867. printer can report the print before the line after the send executes. So
  868. every path that registers and then fails to send — a cancel winning the
  869. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  870. between — leaves an expectation for a print that will never arrive.
  871. The TTL sweep evicts those after two hours, which is far longer than it
  872. takes a user to react to a failed dispatch by pressing print again: that
  873. reprint would be folded into the *old* archive and take the stale
  874. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  875. Mirrors the sweep's rules, including the one that is easy to get wrong:
  876. ``_print_ams_mappings`` / ``_print_plate_ids`` are keyed by archive, not by
  877. file, so they may only be dropped once no live key still points at that
  878. archive.
  879. """
  880. keys = [(printer_id, filename)]
  881. if filename.endswith(".3mf"):
  882. base = filename[:-4]
  883. keys.append((printer_id, base))
  884. keys.append((printer_id, f"{base}.gcode"))
  885. removed = False
  886. for key in keys:
  887. if _expected_prints.pop(key, None) is not None:
  888. removed = True
  889. _expected_print_creators.pop(key, None)
  890. _expected_print_registered_at.pop(key, None)
  891. if archive_id not in set(_expected_prints.values()):
  892. _print_ams_mappings.pop(archive_id, None)
  893. _print_plate_ids.pop(archive_id, None)
  894. if removed:
  895. logging.getLogger(__name__).info(
  896. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  897. printer_id,
  898. filename,
  899. archive_id,
  900. )
  901. def _compute_run_filament_grams(
  902. status: str,
  903. archive_filament_used_grams: float | None,
  904. progress: float | int | None,
  905. usage_results: list[dict] | None,
  906. ) -> float | None:
  907. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  908. Priority for every status:
  909. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  910. weight delta — same source that drives "Total Consumed" on the
  911. Inventory page, so Stats and Inventory totals stay aligned).
  912. 2. For ``completed``: the slicer estimate (no tracker available, fall
  913. back to the canonical "this print used X" value).
  914. 3. For partial statuses: ``estimate * progress%``.
  915. 4. ``None`` if nothing is known.
  916. """
  917. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  918. if tracked_grams > 0:
  919. return round(tracked_grams, 1)
  920. if status == "completed":
  921. return archive_filament_used_grams
  922. if archive_filament_used_grams:
  923. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  924. if scale > 0:
  925. return round(archive_filament_used_grams * scale, 1)
  926. return None
  927. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  928. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  929. stored_ams_mapping = data.get("ams_mapping")
  930. if not stored_ams_mapping and archive_id:
  931. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  932. return stored_ams_mapping
  933. def _get_start_plate_id(archive_id: int | None) -> int | None:
  934. """Resolve plate_id for print start without consuming stored direct-Print state.
  935. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  936. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  937. read it back at print-start without popping (the entry is popped on print
  938. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  939. """
  940. if archive_id is None:
  941. return None
  942. return _print_plate_ids.get(archive_id)
  943. def _partial_progress_scale(progress: int | float | None) -> float:
  944. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  945. Used by every site that multiplies a "would-have-used" slicer estimate
  946. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  947. so the three sites in ``_background_notifications`` (and the per-plate
  948. override helper) can't drift apart on the coercion shape.
  949. """
  950. return max(0.0, min((progress or 0) / 100.0, 1.0))
  951. def _scope_notification_archive_data_to_plate(
  952. archive_data: dict,
  953. archive_file_path: str | None,
  954. plate_id: int | None,
  955. print_status: str,
  956. progress: int | float | None,
  957. base_dir: Path,
  958. ) -> dict:
  959. """Override summed-across-plates totals in ``archive_data`` with the values
  960. for ``plate_id`` so the completion notification reports what was actually
  961. printed, not the whole project (#1785).
  962. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  963. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  964. the archive card's "whole project" headline, wrong for the completion
  965. notification of a single-plate print. The queue UI already re-reads the
  966. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  967. notification payload (filament grams, time estimate, per-slot breakdown).
  968. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  969. no per-plate values — in every fail case the original ``archive_data`` is
  970. returned unchanged so the notification still sends.
  971. """
  972. if plate_id is None or not archive_file_path:
  973. return archive_data
  974. from backend.app.utils.threemf_tools import (
  975. extract_filament_usage_from_3mf,
  976. extract_print_time_from_3mf,
  977. )
  978. archive_path = base_dir / archive_file_path
  979. if not archive_path.exists():
  980. return archive_data
  981. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  982. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  983. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  984. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  985. if plate_time:
  986. archive_data["print_time_seconds"] = plate_time
  987. # Gate both the grams headline AND the per-slot breakdown on the same
  988. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  989. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  990. # to the project-level grams the archive columns already provide rather
  991. # than ship a project-level headline next to an all-zero per-plate
  992. # breakdown.
  993. if plate_grams > 0:
  994. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  995. archive_data["filament_slots"] = [
  996. {
  997. "slot_id": s.get("slot_id"),
  998. "used_g": round((s.get("used_g") or 0) * scale, 1),
  999. "type": s.get("type", ""),
  1000. "color": s.get("color", ""),
  1001. }
  1002. for s in plate_slots
  1003. ]
  1004. return archive_data
  1005. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1006. """Best-effort filament metadata from the MQTT print-start snapshot.
  1007. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1008. file during print, see #1533) so the fallback PrintArchive still has
  1009. enough filament info to support the inventory views and AMS-expansion
  1010. planning the operator opens it for. Returns a dict with optional
  1011. ``filament_type`` and ``filament_color`` keys in the same
  1012. comma-separated format the 3MF extractor produces, so the rest of the
  1013. codebase treats the fallback archive identically to a normal one.
  1014. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1015. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1016. entries). When supplied, only the slots actually consumed by this
  1017. print contribute. Without it the function falls back to every loaded
  1018. AMS slot — less accurate but still useful.
  1019. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1020. that the unit tests pass directly, AND the on_print_start callback
  1021. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1022. bambu_mqtt service hands to main.py at runtime. The original
  1023. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1024. handled the inner shape and silently returned ``{}`` for every real
  1025. print start, leaving fallback archives' filament fields NULL — the
  1026. exact regression the fix was meant to close. Reported with a log
  1027. proving the AMS state was right there at
  1028. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1029. """
  1030. result: dict[str, str] = {}
  1031. # Look at the on_print_start wrapper first, then the inner shape.
  1032. raw_data = (data or {}).get("raw_data")
  1033. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1034. if not isinstance(ams_root, dict):
  1035. ams_root = (data or {}).get("ams") or {}
  1036. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1037. if not isinstance(ams_units, list) or not ams_units:
  1038. return result
  1039. # Map global tray id (unit * 4 + tray) → (type, color).
  1040. loaded: dict[int, tuple[str, str]] = {}
  1041. for unit in ams_units:
  1042. if not isinstance(unit, dict):
  1043. continue
  1044. try:
  1045. unit_id = int(unit.get("id", 0))
  1046. except (TypeError, ValueError):
  1047. continue
  1048. for tray in unit.get("tray") or []:
  1049. if not isinstance(tray, dict):
  1050. continue
  1051. try:
  1052. tray_id = int(tray.get("id", 0))
  1053. except (TypeError, ValueError):
  1054. continue
  1055. ttype = (tray.get("tray_type") or "").strip()
  1056. tcolor = (tray.get("tray_color") or "").strip().upper()
  1057. if not ttype:
  1058. continue # Empty / unloaded slot.
  1059. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  1060. if not loaded:
  1061. return result
  1062. if ams_mapping:
  1063. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1064. filaments = [loaded[g] for g in used_ids if g in loaded]
  1065. if not filaments:
  1066. return result # Mapping points entirely at slots we have no data for.
  1067. else:
  1068. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1069. types_joined = ",".join(f[0] for f in filaments)
  1070. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1071. # Column limits per backend/app/models/archive.py: filament_type=50,
  1072. # filament_color=200.
  1073. if types_joined:
  1074. result["filament_type"] = types_joined[:50]
  1075. if colors_joined:
  1076. result["filament_color"] = colors_joined[:200]
  1077. return result
  1078. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1079. """Start a layer-timelapse session for *archive_id* when the printer has
  1080. an external camera configured. Returns True if a session was started.
  1081. Three call sites in on_print_start (expected-archive promotion, fallback
  1082. archive creation, fresh-archive creation) used to inline this same
  1083. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1084. on the first pass). Centralising the conditional + call here makes the
  1085. contract testable in isolation and keeps the three sites locked in step.
  1086. """
  1087. if not (printer.external_camera_enabled and printer.external_camera_url):
  1088. return False
  1089. from backend.app.services.layer_timelapse import start_session
  1090. start_session(
  1091. printer_id,
  1092. archive_id,
  1093. printer.external_camera_url,
  1094. printer.external_camera_type or "mjpeg",
  1095. snapshot_url=printer.external_camera_snapshot_url,
  1096. rotation=getattr(printer, "camera_rotation", 0),
  1097. )
  1098. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1099. return True
  1100. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1101. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1102. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1103. — since #2926 — the description the parser already resolved, which is preferred
  1104. when present so the queue's failure reason reads the same as the status
  1105. response. The short code still produces the bracketed label, and still
  1106. resolves the sentence for a caller whose entries predate the field. Falls back
  1107. to the bare short code when no description is on file. Returns None for an
  1108. empty list so callers can leave error_message unset.
  1109. """
  1110. if not hms_errors:
  1111. return None
  1112. from backend.app.services.hms_errors import get_error_description
  1113. parts: list[str] = []
  1114. for err in hms_errors:
  1115. try:
  1116. # `_hms_short_code` rather than a local derivation: this one used to
  1117. # format the error without masking it to 16 bits, so an `hms[]` entry
  1118. # whose code carries an alert-level group produced a five-digit label
  1119. # like "0500_3000A" — not a code the user can look up, and never a
  1120. # catalogue key, so the sentence was lost with it.
  1121. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1122. except (TypeError, ValueError):
  1123. continue
  1124. description = err.get("description") or get_error_description(short_code)
  1125. parts.append(f"[{short_code}] {description}" if description else f"[{short_code}]")
  1126. return "; ".join(parts) if parts else None
  1127. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1128. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1129. print completes successfully. Gated to status=='completed': failed, cancelled
  1130. and aborted prints do not count as usage. Caller is responsible for committing
  1131. the session. No-op when the queue item has no linked library file (e.g. reprints
  1132. from an archive). See #1008."""
  1133. if queue_status != "completed" or item.library_file_id is None:
  1134. return
  1135. from backend.app.models.library import LibraryFile
  1136. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1137. if lib_file is None:
  1138. return
  1139. lib_file.print_count = (lib_file.print_count or 0) + 1
  1140. lib_file.last_printed_at = datetime.now(timezone.utc)
  1141. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1142. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1143. When on_print_complete fires with status 'failed' for a printer in this set we
  1144. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1145. rather than a 'print failed' notification.
  1146. """
  1147. _user_stopped_printers.add(printer_id)
  1148. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1149. _last_status_broadcast: dict[int, str] = {}
  1150. # Track printers where we've updated nozzle_count
  1151. _nozzle_count_updated: set[int] = set()
  1152. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1153. """Wait the debounce window then fire `on_printer_offline` if the printer
  1154. is still offline.
  1155. Scheduled by `on_printer_status_change` on the connected → disconnected
  1156. edge (#1752). Cancelled by the same handler if the printer reconnects
  1157. before the window elapses, so a single MQTT blip + recovery doesn't
  1158. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1159. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1160. route through the same status-change callback, so this covers both.
  1161. """
  1162. logger = logging.getLogger(__name__)
  1163. try:
  1164. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1165. still_offline = not printer_manager.is_connected(printer_id)
  1166. logger.info(
  1167. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1168. printer_id,
  1169. still_offline,
  1170. )
  1171. if not still_offline:
  1172. return
  1173. async with async_session() as db:
  1174. from backend.app.models.printer import Printer
  1175. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1176. printer = result.scalar_one_or_none()
  1177. if not printer:
  1178. logger.warning(
  1179. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1180. printer_id,
  1181. )
  1182. return
  1183. logger.info(
  1184. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1185. printer_id,
  1186. printer.name,
  1187. )
  1188. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1189. except asyncio.CancelledError:
  1190. raise
  1191. except Exception as e:
  1192. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1193. finally:
  1194. _printer_offline_notify_tasks.pop(printer_id, None)
  1195. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1196. """Handle printer status changes - broadcast via WebSocket."""
  1197. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1198. # transitions disconnected → connected — which covers both Bambuddy
  1199. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1200. # `reconcile_stale_active_prints` exactly once for this connection so
  1201. # any archive still in `status="printing"` that can't actually be
  1202. # running anymore (printer IDLE / different subtask / empty subtask)
  1203. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1204. # finished during a disconnect window + a smart-plug power cycle
  1205. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1206. # next boot. Reconciliation runs concurrently — it must not block the
  1207. # WebSocket dedup / broadcast logic below, and the connected edge is
  1208. # marked True BEFORE the await so concurrent status updates inside
  1209. # the same connection don't re-trigger reconciliation.
  1210. #
  1211. # Wait for a real push_status before reconciling (#1679): MQTT
  1212. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1213. # the connection, BEFORE `_request_push_all` round-trips. At that
  1214. # instant the `PrinterState` is still on construction defaults — most
  1215. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1216. # If reconcile spawns here, every in-flight archive falls through to
  1217. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1218. # creates a duplicate archive on the real PRINT COMPLETE and
  1219. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1220. # keeps the #1542 mechanism intact: once the first real push_status
  1221. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1222. # fires again with the flag still False — reconcile then runs against
  1223. # actual evidence.
  1224. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1225. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1226. _printer_reconciled_since_connect[printer_id] = True
  1227. spawn_background_task(
  1228. reconcile_stale_active_prints(printer_id),
  1229. name=f"reconcile-stale-prints-{printer_id}",
  1230. )
  1231. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1232. # Re-arm so the next reconnect triggers reconciliation again.
  1233. _printer_reconciled_since_connect[printer_id] = False
  1234. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1235. # connected → disconnected. The "back online" channel is already covered
  1236. # by the print-failure notification (firmware reports gcode_state=FAILED
  1237. # on reconnect of an interrupted print), so we don't add a symmetric
  1238. # online event here.
  1239. prev_connected = _printer_last_connected.get(printer_id)
  1240. _printer_last_connected[printer_id] = state.connected
  1241. if prev_connected is True and not state.connected:
  1242. existing = _printer_offline_notify_tasks.get(printer_id)
  1243. if existing is None or existing.done():
  1244. logging.getLogger(__name__).info(
  1245. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1246. printer_id,
  1247. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1248. )
  1249. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1250. _maybe_notify_printer_offline(printer_id),
  1251. name=f"printer-offline-notify-{printer_id}",
  1252. )
  1253. elif state.connected:
  1254. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1255. if pending is not None and not pending.done():
  1256. logging.getLogger(__name__).info(
  1257. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1258. printer_id,
  1259. )
  1260. pending.cancel()
  1261. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1262. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1263. temps = state.temperatures or {}
  1264. nozzle_temp = round(temps.get("nozzle", 0))
  1265. bed_temp = round(temps.get("bed", 0))
  1266. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1267. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1268. # Auto-detect dual-nozzle printers from MQTT temperature data
  1269. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1270. _nozzle_count_updated.add(printer_id)
  1271. # Update nozzle_count in database
  1272. async with async_session() as db:
  1273. from backend.app.models.printer import Printer
  1274. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1275. printer = result.scalar_one_or_none()
  1276. if printer and printer.nozzle_count != 2:
  1277. printer.nozzle_count = 2
  1278. await db.commit()
  1279. logging.getLogger(__name__).info(
  1280. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1281. )
  1282. # Include target temps for heating phase detection
  1283. bed_target = round(temps.get("bed_target", 0))
  1284. nozzle_target = round(temps.get("nozzle_target", 0))
  1285. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1286. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1287. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts
  1288. ams_dry_key = tuple(a.get("dry_time", 0) for a in (state.raw_data.get("ams") or [])) if state.raw_data else ()
  1289. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1290. #
  1291. # The filament identity fields are here because Configure Slot writes
  1292. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1293. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1294. # matched, this function returned before broadcasting, and the card kept
  1295. # showing the old filament until the 30s fallback poll or a page reload —
  1296. # even though the configure route asks the printer for a fresh pushall and
  1297. # that push does carry the new values. Reset always worked, because it
  1298. # clears tray_type.
  1299. #
  1300. # These fields only change when someone configures a slot or swaps a spool,
  1301. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1302. ams_tray_key = (
  1303. tuple(
  1304. (
  1305. t.get("id"),
  1306. t.get("tray_type", ""),
  1307. t.get("state"),
  1308. t.get("tray_color", ""),
  1309. t.get("tray_info_idx", ""),
  1310. t.get("tray_sub_brands", ""),
  1311. t.get("cali_idx"),
  1312. )
  1313. for a in (state.raw_data.get("ams") or [])
  1314. for t in a.get("tray", [])
  1315. )
  1316. if state.raw_data
  1317. else ()
  1318. )
  1319. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1320. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1321. # in the AMS change-hash (tray fields only, and widening that would fire
  1322. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1323. # screen changed no key at all and the card's inlet badges sat stale until a
  1324. # reload. Like the filament-backup flag, these only move when someone
  1325. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1326. fts_key = (
  1327. state.fila_switch.installed if state.fila_switch else False,
  1328. tuple(sorted(state.ams_switch_inlet.items())),
  1329. )
  1330. status_key = (
  1331. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1332. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1333. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1334. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1335. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1336. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1337. )
  1338. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1339. if not is_active_print:
  1340. _unauthorized_print_kill_sent.discard(printer_id)
  1341. elif printer_id in _unauthorized_print_kill_sent:
  1342. # stop_print() was already sent for this print; avoid all further
  1343. # ownership and settings work until the printer leaves an active state.
  1344. pass
  1345. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1346. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1347. _unauthorized_print_kill_sent.discard(printer_id)
  1348. else:
  1349. kill_switch_enabled = False
  1350. authorization: bool | None = None
  1351. status_logger = logging.getLogger(__name__)
  1352. try:
  1353. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1354. if kill_switch_enabled:
  1355. async with async_session() as db:
  1356. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1357. except Exception as e:
  1358. # Fail safe: a database/reconciliation error must never turn into an
  1359. # irreversible stop of a print whose ownership is still unknown.
  1360. authorization = None
  1361. status_logger.warning(
  1362. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1363. )
  1364. if not kill_switch_enabled or authorization is True:
  1365. _unauthorized_print_kill_sent.discard(printer_id)
  1366. elif authorization is None:
  1367. _unauthorized_print_kill_sent.discard(printer_id)
  1368. status_logger.debug(
  1369. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1370. printer_id,
  1371. )
  1372. else:
  1373. try:
  1374. stopped = printer_manager.stop_print(printer_id)
  1375. if stopped:
  1376. _unauthorized_print_kill_sent.add(printer_id)
  1377. printer_info = printer_manager.get_printer(printer_id)
  1378. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1379. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1380. notification_data = {
  1381. "status": "stopped",
  1382. "filename": state.gcode_file or state.current_print or "",
  1383. "subtask_name": state.subtask_name or "",
  1384. "progress": state.progress,
  1385. "reason": "unauthorized_print",
  1386. }
  1387. status_logger.warning(
  1388. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1389. printer_id,
  1390. state.state,
  1391. )
  1392. try:
  1393. await ws_manager.broadcast(
  1394. {
  1395. "type": "kill_switch_triggered",
  1396. "printer_id": printer_id,
  1397. "printer_name": printer_name,
  1398. "filename": filename,
  1399. "reason": "unauthorized_print",
  1400. }
  1401. )
  1402. except Exception as e:
  1403. status_logger.warning(
  1404. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1405. )
  1406. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1407. if previous_task is not None and not previous_task.done():
  1408. previous_task.cancel()
  1409. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1410. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1411. name=f"kill-switch-notification-{printer_id}",
  1412. )
  1413. else:
  1414. status_logger.warning(
  1415. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1416. printer_id,
  1417. state.state,
  1418. )
  1419. except Exception as e:
  1420. status_logger.warning(
  1421. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1422. )
  1423. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1424. try:
  1425. printer_info = printer_manager.get_printer(printer_id)
  1426. if printer_info:
  1427. await mqtt_relay.on_printer_status(
  1428. printer_id,
  1429. state,
  1430. printer_info.name,
  1431. printer_info.serial_number,
  1432. printer_manager.is_awaiting_plate_clear(printer_id),
  1433. )
  1434. except Exception:
  1435. pass # Don't fail status callback if MQTT fails
  1436. if _last_status_broadcast.get(printer_id) == status_key:
  1437. return # No change, skip WebSocket broadcast
  1438. _last_status_broadcast[printer_id] = status_key
  1439. # Check for progress milestone notifications (25%, 50%, 75%)
  1440. progress = state.progress or 0
  1441. is_printing = state.state in ("RUNNING", "PRINTING")
  1442. if is_printing and progress > 0:
  1443. # Determine which milestone we've reached
  1444. current_milestone = 0
  1445. if progress >= 75:
  1446. current_milestone = 75
  1447. elif progress >= 50:
  1448. current_milestone = 50
  1449. elif progress >= 25:
  1450. current_milestone = 25
  1451. last_milestone = _last_progress_milestone.get(printer_id, 0)
  1452. # If we've crossed a new milestone, send notification
  1453. if current_milestone > last_milestone:
  1454. _last_progress_milestone[printer_id] = current_milestone
  1455. try:
  1456. from backend.app.models.printer import Printer
  1457. # Read the printer in a short session and release the connection
  1458. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1459. # pinned a pooled connection per milestone, per printer (issue #2572).
  1460. async with async_session() as db:
  1461. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1462. printer = result.scalar_one_or_none()
  1463. printer_name = printer.name if printer else f"Printer {printer_id}"
  1464. filename = state.subtask_name or state.gcode_file or "Unknown"
  1465. # remaining_time is in minutes, convert to seconds for notification
  1466. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1467. # Capture camera snapshot for notification image attachment (no DB held).
  1468. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1469. # Notification send needs a session (provider/template lookups).
  1470. async with async_session() as db:
  1471. await notification_service.on_print_progress(
  1472. printer_id,
  1473. printer_name,
  1474. filename,
  1475. current_milestone,
  1476. db,
  1477. remaining_time_seconds,
  1478. image_data=image_data,
  1479. )
  1480. except Exception as e:
  1481. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1482. elif progress < 5:
  1483. # Reset milestone tracking when print restarts or new print begins
  1484. _last_progress_milestone[printer_id] = 0
  1485. _first_layer_notified[printer_id] = False
  1486. # HMS error codes that should not trigger notifications even though they
  1487. # have known descriptions (e.g. user-initiated actions, not real errors).
  1488. _HMS_NOTIFICATION_SUPPRESS = {
  1489. "0500_400E", # Printing was cancelled (user action, not an error)
  1490. }
  1491. # Check for new HMS errors and send notifications
  1492. current_hms_errors = getattr(state, "hms_errors", []) or []
  1493. if current_hms_errors:
  1494. # Build set of current error codes (using attr for uniqueness)
  1495. current_error_codes = {f"{e.attr:08x}" for e in current_hms_errors}
  1496. previously_notified = _notified_hms_errors.get(printer_id, set())
  1497. # Find new errors that haven't been notified yet
  1498. new_error_codes = current_error_codes - previously_notified
  1499. # Update tracking immediately to prevent duplicate notifications from concurrent callbacks
  1500. _notified_hms_errors[printer_id] = current_error_codes
  1501. _hms_last_seen[printer_id] = time.time()
  1502. if new_error_codes:
  1503. # Get the actual new errors for the notification
  1504. # Filter to severity >= 2 (skip informational/status messages like H2D sends)
  1505. new_errors = [e for e in current_hms_errors if f"{e.attr:08x}" in new_error_codes and e.severity >= 2]
  1506. try:
  1507. from backend.app.models.printer import Printer
  1508. # Read the printer in a short session and release the connection
  1509. # BEFORE the ~15s camera snapshot below (issue #2572).
  1510. async with async_session() as db:
  1511. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1512. printer = result.scalar_one_or_none()
  1513. printer_name = printer.name if printer else f"Printer {printer_id}"
  1514. # Format error details for notification
  1515. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1516. module_names = {
  1517. 0x03: "Print/Task",
  1518. 0x05: "Nozzle/Extruder",
  1519. 0x07: "AMS/Filament",
  1520. 0x0C: "Motion Controller",
  1521. 0x12: "Chamber",
  1522. }
  1523. # Capture camera snapshot once for all error notifications (no DB held).
  1524. error_image_data = await _capture_snapshot_for_notification(
  1525. printer_id, printer, logging.getLogger(__name__)
  1526. )
  1527. # Notification sends need a session (provider/template lookups).
  1528. async with async_session() as db:
  1529. sent_count = 0
  1530. for error in new_errors:
  1531. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1532. # Build short code like "0700_8010"
  1533. # Mask to 16 bits to handle printers that send larger values
  1534. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1535. error_code_masked = error_code_int & 0xFFFF
  1536. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1537. # Only notify for errors with known descriptions — printers
  1538. # send many undocumented/phantom codes that aren't real errors.
  1539. # Resolved at parse time (#2926); short_code is still needed
  1540. # for the suppression set below.
  1541. description = error.description
  1542. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1543. continue
  1544. error_type = f"{module_name} Error"
  1545. error_detail = description
  1546. await notification_service.on_printer_error(
  1547. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1548. )
  1549. sent_count += 1
  1550. if sent_count:
  1551. logging.getLogger(__name__).info(
  1552. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1553. )
  1554. # Also publish to MQTT relay (no DB).
  1555. printer_info = printer_manager.get_printer(printer_id)
  1556. if printer_info:
  1557. errors_data = [
  1558. {
  1559. "code": e.code,
  1560. "attr": e.attr,
  1561. "module": e.module,
  1562. "severity": e.severity,
  1563. }
  1564. for e in new_errors
  1565. ]
  1566. await mqtt_relay.on_printer_error(
  1567. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1568. )
  1569. except Exception as e:
  1570. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1571. else:
  1572. # No HMS errors — only clear tracking after a grace period to prevent
  1573. # flapping errors (brief hms:[] gaps) from re-triggering notifications.
  1574. # Some HMS codes (e.g. chamber temp regulation during PETG prints) toggle
  1575. # on/off every few seconds as conditions fluctuate around thresholds.
  1576. if printer_id in _notified_hms_errors:
  1577. last_seen = _hms_last_seen.get(printer_id, 0)
  1578. if time.time() - last_seen >= _HMS_CLEAR_GRACE_SECONDS:
  1579. _notified_hms_errors.pop(printer_id, None)
  1580. _hms_last_seen.pop(printer_id, None)
  1581. await ws_manager.send_printer_status(
  1582. printer_id,
  1583. printer_state_to_dict(
  1584. state,
  1585. printer_id,
  1586. printer_manager.get_model(printer_id),
  1587. printer_manager.get_drying_targets(printer_id),
  1588. ),
  1589. )
  1590. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1591. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1592. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1593. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  1594. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  1595. K-profiles are per-nozzle and the printer's calibration table is numbered
  1596. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  1597. switch's other inlet therefore silently invalidates every configured slot in
  1598. it: the index stays put and now resolves against the other nozzle's table.
  1599. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  1600. and 0.020 on the right kept the left profile after the move, and a manual
  1601. RFID re-read only re-asserted the same wrong one.
  1602. Configuring a slot is a deliberate preparation step, so this re-selects
  1603. rather than re-configures: only the calibration binding moves, and only for
  1604. slots whose spool already has a stored profile for the new nozzle. A slot
  1605. Bambuddy knows nothing about is left exactly as the operator left it.
  1606. """
  1607. logger = logging.getLogger(__name__)
  1608. target_extruder = extruder_for_inlet(inlet)
  1609. if target_extruder is None:
  1610. return
  1611. client = printer_manager.get_client(printer_id)
  1612. state = printer_manager.get_status(printer_id)
  1613. if not client or not state or not state.raw_data:
  1614. return
  1615. nozzle_diameter = "0.4"
  1616. if state.nozzles and state.nozzles[0].nozzle_diameter:
  1617. nozzle_diameter = state.nozzles[0].nozzle_diameter
  1618. ams_raw = state.raw_data.get("ams")
  1619. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  1620. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  1621. if not unit:
  1622. return
  1623. try:
  1624. async with async_session() as db:
  1625. for tray in unit.get("tray", []):
  1626. tray_id = int(tray.get("id", -1))
  1627. if tray_id < 0 or not tray.get("tray_type"):
  1628. continue
  1629. current_idx = tray.get("cali_idx")
  1630. profile = await find_slot_kprofile_for_extruder(
  1631. db, printer_id, ams_id, tray_id, target_extruder, nozzle_diameter
  1632. )
  1633. if profile is None or profile.cali_idx is None:
  1634. continue
  1635. if current_idx == profile.cali_idx:
  1636. continue # Already on the right one.
  1637. logger.info(
  1638. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  1639. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  1640. printer_id,
  1641. ams_id,
  1642. tray_id,
  1643. inlet,
  1644. target_extruder,
  1645. profile.name,
  1646. current_idx,
  1647. profile.cali_idx,
  1648. profile.k_value,
  1649. )
  1650. client.extrusion_cali_sel(
  1651. ams_id=ams_id,
  1652. tray_id=tray_id,
  1653. cali_idx=profile.cali_idx,
  1654. filament_id=profile.filament_id or tray.get("tray_info_idx", "") or "",
  1655. nozzle_diameter=nozzle_diameter,
  1656. )
  1657. except Exception as e:
  1658. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  1659. async def on_ams_change(printer_id: int, ams_data: list):
  1660. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  1661. logger = logging.getLogger(__name__)
  1662. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  1663. # on_print_complete may pop _active_sessions during our awaits (#880).
  1664. from backend.app.services.usage_tracker import _active_sessions
  1665. _print_active = printer_id in _active_sessions
  1666. # A slot that reports empty while a print is running is a filament runout,
  1667. # not a spool swap: the spool is still physically in the AMS, just
  1668. # consumed. Dropping either inventory backend's slot link there loses the
  1669. # only record of which spool fed the print, so the completion path can't
  1670. # charge the runout segment to anything. Both cleanup passes below consult
  1671. # this; computed once, up front, so neither depends on the other having run.
  1672. _unlink_state = printer_manager.get_status(printer_id)
  1673. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  1674. # MQTT relay - publish AMS change
  1675. try:
  1676. printer_info = printer_manager.get_printer(printer_id)
  1677. if printer_info:
  1678. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  1679. except Exception:
  1680. pass # Don't fail AMS callback if MQTT fails
  1681. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  1682. # This ensures frontend gets immediate updates when AMS slots are configured
  1683. try:
  1684. state = printer_manager.get_status(printer_id)
  1685. if state:
  1686. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  1687. await ws_manager.send_printer_status(
  1688. printer_id,
  1689. printer_state_to_dict(
  1690. state,
  1691. printer_id,
  1692. printer_manager.get_model(printer_id),
  1693. printer_manager.get_drying_targets(printer_id),
  1694. ),
  1695. )
  1696. except Exception as e:
  1697. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  1698. from backend.app.utils.color_utils import colors_similar as _colors_similar
  1699. # Auto-unlink spool assignments with stale fingerprints
  1700. try:
  1701. async with async_session() as db:
  1702. from sqlalchemy.orm import selectinload
  1703. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  1704. from backend.app.models.spool import Spool as _Spool
  1705. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1706. result = await db.execute(
  1707. select(SA)
  1708. .where(SA.printer_id == printer_id)
  1709. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  1710. )
  1711. # ``printing_now`` (top of this function) keeps a runout from
  1712. # unlinking the spool that fed the print — the next idle-time pass
  1713. # unlinks it if the user really did take it out.
  1714. stale = []
  1715. for assignment in result.scalars().all():
  1716. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  1717. if assignment.ams_id == 255:
  1718. ps = printer_manager.get_status(printer_id)
  1719. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  1720. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  1721. current_tray = None
  1722. for vt in vt_tray_raw:
  1723. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1724. current_tray = vt
  1725. break
  1726. if not current_tray:
  1727. # vt_tray data may not have arrived yet — keep assignment
  1728. continue
  1729. else:
  1730. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  1731. if not current_tray:
  1732. if printing_now:
  1733. logger.info(
  1734. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  1735. assignment.spool_id,
  1736. assignment.ams_id,
  1737. assignment.tray_id,
  1738. )
  1739. continue
  1740. logger.info(
  1741. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  1742. assignment.spool_id,
  1743. assignment.ams_id,
  1744. assignment.tray_id,
  1745. )
  1746. stale.append(assignment) # Slot empty
  1747. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  1748. # A Bambu Lab spool is in this slot — check if it's the same spool
  1749. # that's currently assigned. If yes, keep the assignment (avoids
  1750. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  1751. # the printer's filament preset on every startup).
  1752. tray_uuid = current_tray.get("tray_uuid", "")
  1753. tag_uid = current_tray.get("tag_uid", "")
  1754. spool = assignment.spool
  1755. spool_matches = False
  1756. if spool:
  1757. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  1758. spool.tag_uid
  1759. and tag_uid
  1760. and tag_uid != "0000000000000000"
  1761. and spool.tag_uid.upper() == tag_uid.upper()
  1762. ):
  1763. spool_matches = True
  1764. if spool_matches:
  1765. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  1766. cur_color = current_tray.get("tray_color", "")
  1767. cur_type = current_tray.get("tray_type", "")
  1768. fp_color = assignment.fingerprint_color or ""
  1769. fp_type = assignment.fingerprint_type or ""
  1770. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  1771. assignment.fingerprint_color = cur_color
  1772. assignment.fingerprint_type = cur_type
  1773. logger.debug(
  1774. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  1775. assignment.spool_id,
  1776. assignment.ams_id,
  1777. assignment.tray_id,
  1778. )
  1779. continue
  1780. # Different BL spool or unrecognized — unlink so auto-assign can match
  1781. logger.info(
  1782. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  1783. assignment.spool_id,
  1784. assignment.ams_id,
  1785. assignment.tray_id,
  1786. tray_uuid,
  1787. )
  1788. stale.append(assignment)
  1789. else:
  1790. cur_color = current_tray.get("tray_color", "")
  1791. cur_type = current_tray.get("tray_type", "")
  1792. cur_state = current_tray.get("state")
  1793. fp_color = assignment.fingerprint_color or ""
  1794. fp_type = assignment.fingerprint_type or ""
  1795. # SpoolBuddy pre-config replay: fingerprint_type empty means
  1796. # the slot was empty when the user pre-assigned via SpoolBuddy
  1797. # (the firmware drops ams_filament_setting on empty slots, so
  1798. # MQTT was deferred). The moment any filament gets inserted
  1799. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  1800. # reconfigured spool — fire the deferred configuration.
  1801. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  1802. # extruder" code) OR, on firmwares that don't use the state
  1803. # enum meaningfully, a non-empty tray_type when state is
  1804. # NOT one of the firmware's explicit empty signals (9, 10).
  1805. # state-only was wrong for firmwares that never set 11 — A1
  1806. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  1807. # always report state=3 — so the replay never fired for them
  1808. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  1809. # explicit "empty" signals authoritative over any stale
  1810. # tray_type that might survive the relay's auto-clearing.
  1811. loaded = cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  1812. if not fp_type.strip() and loaded and assignment.spool:
  1813. try:
  1814. from backend.app.api.routes.inventory import (
  1815. apply_spool_to_slot_via_mqtt,
  1816. )
  1817. await apply_spool_to_slot_via_mqtt(
  1818. db=db,
  1819. current_user=None,
  1820. spool=assignment.spool,
  1821. printer_id=printer_id,
  1822. ams_id=assignment.ams_id,
  1823. tray_id=assignment.tray_id,
  1824. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  1825. current_tray_type=cur_type,
  1826. )
  1827. logger.info(
  1828. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  1829. assignment.spool_id,
  1830. printer_id,
  1831. assignment.ams_id,
  1832. assignment.tray_id,
  1833. )
  1834. except Exception:
  1835. logger.exception(
  1836. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  1837. assignment.spool_id,
  1838. printer_id,
  1839. assignment.ams_id,
  1840. assignment.tray_id,
  1841. )
  1842. assignment.fingerprint_color = cur_color
  1843. assignment.fingerprint_type = cur_type
  1844. continue
  1845. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  1846. # Blank tray data mid-print is a runout, not a swap: the
  1847. # firmware clears colour and type when it unloads a spool
  1848. # it just emptied. Unlinking here would erase the record
  1849. # of which spool fed the print so far.
  1850. if printing_now and not cur_color.strip() and not cur_type.strip():
  1851. logger.info(
  1852. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  1853. "(runout?)",
  1854. assignment.spool_id,
  1855. assignment.ams_id,
  1856. assignment.tray_id,
  1857. )
  1858. continue
  1859. # Fingerprint mismatch — but check if tray now matches the
  1860. # assigned spool (e.g. auto-configure changed the tray).
  1861. # Both sides are reduced to the type the slot can carry
  1862. # before comparing: the assign path writes that rather
  1863. # than the spool's raw material (#2902), so a spool whose
  1864. # material is a product line — "PLA+", "HTPLA" — reports
  1865. # back as "PLA" and would otherwise fail this check and
  1866. # be auto-unlinked from the slot it was just assigned to.
  1867. # Reducing the printer's side too keeps slots configured
  1868. # by an older Bambuddy, still reporting "PLA+", matching.
  1869. spool = assignment.spool
  1870. if spool:
  1871. spool_color = (spool.rgba or "FFFFFFFF").upper()
  1872. # Two ways the assign path can have arrived at the
  1873. # slot's type, so both count as "we wrote this".
  1874. # The material column is one; the spool's preset is
  1875. # the other, and it outranks the material when the
  1876. # spool has one -- a spool whose material says PLA
  1877. # and whose preset is "Bambu PLA Aero" puts
  1878. # PLA-AERO in the slot (#2902). Read from the stored
  1879. # preset name rather than resolving the preset,
  1880. # because this runs on every AMS push and a cloud
  1881. # lookup here would be both slow and unavailable on
  1882. # the unauthenticated replay path.
  1883. spool_types = {printer_filament_type(spool.material).upper()}
  1884. if spool.slicer_filament_name:
  1885. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  1886. # An imported local preset stores its type outright,
  1887. # which is what the assign path used -- and the name
  1888. # above may be unset. One keyed read, and only on a
  1889. # mismatch, which is rare.
  1890. #
  1891. # slicer_filament is free text up to fifty characters,
  1892. # so the digits have to be checked against the range
  1893. # of the integer primary key they are about to be
  1894. # compared with. Postgres raises on an out-of-range
  1895. # integer rather than simply not matching, and that
  1896. # would poison this session and abandon the rest of
  1897. # the cleanup pass.
  1898. lp_ref = (spool.slicer_filament or "").strip()
  1899. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  1900. from backend.app.models.local_preset import LocalPreset as _LP
  1901. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  1902. if lp_type:
  1903. spool_types.add(printer_filament_type(lp_type).upper())
  1904. if (
  1905. _colors_similar(cur_color, spool_color)
  1906. and printer_filament_type(cur_type).upper() in spool_types
  1907. ):
  1908. logger.info(
  1909. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  1910. assignment.spool_id,
  1911. assignment.ams_id,
  1912. assignment.tray_id,
  1913. )
  1914. assignment.fingerprint_color = cur_color
  1915. assignment.fingerprint_type = cur_type
  1916. continue
  1917. logger.info(
  1918. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  1919. assignment.spool_id,
  1920. assignment.ams_id,
  1921. assignment.tray_id,
  1922. cur_color,
  1923. cur_type,
  1924. fp_color,
  1925. fp_type,
  1926. spool.rgba if spool else "?",
  1927. spool.material if spool else "?",
  1928. )
  1929. stale.append(assignment) # Spool changed
  1930. # Snapshot slots before delete — ORM attribute access after the
  1931. # commit would refresh against a deleted row.
  1932. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  1933. for a in stale:
  1934. await db.delete(a)
  1935. if stale:
  1936. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  1937. # Commit any changes (stale deletions and/or fingerprint updates)
  1938. await db.commit()
  1939. # Tell open browsers the assignment is gone (#2575). Only the manual
  1940. # REST assign/unassign endpoints broadcast this event; without it the
  1941. # frontend's spool-assignments cache keeps rendering the unlinked
  1942. # spool on the slot until an unrelated refetch — which reads exactly
  1943. # like "the fix didn't work" (reporter verified: a browser refresh
  1944. # after the swap showed the correct state all along).
  1945. for ams_id, tray_id in unlinked_slots:
  1946. await ws_manager.broadcast(
  1947. {
  1948. "type": "spool_assignment_changed",
  1949. "printer_id": printer_id,
  1950. "ams_id": ams_id,
  1951. "tray_id": tray_id,
  1952. }
  1953. )
  1954. except Exception as e:
  1955. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  1956. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  1957. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  1958. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  1959. # "no existing assignment" for the same (printer, ams, tray) and race to
  1960. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  1961. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  1962. # bug stayed latent there. See _ams_assignment_locks comment for details.
  1963. try:
  1964. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  1965. from backend.app.api.routes.settings import get_setting
  1966. from backend.app.models.spool import Spool
  1967. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1968. from backend.app.services.spool_tag_matcher import (
  1969. auto_assign_spool,
  1970. create_spool_from_tray,
  1971. find_matching_untagged_spool,
  1972. get_spool_by_tag,
  1973. is_bambu_tag,
  1974. is_valid_tag,
  1975. link_tag_to_inventory_spool,
  1976. )
  1977. _spoolman_on = await get_setting(db, "spoolman_enabled")
  1978. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  1979. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  1980. if not _spoolman_on or _spoolman_on.lower() != "true":
  1981. for ams_unit in ams_data:
  1982. if not isinstance(ams_unit, dict):
  1983. continue
  1984. ams_id = int(ams_unit.get("id", 0))
  1985. for tray in ams_unit.get("tray", []):
  1986. if not isinstance(tray, dict):
  1987. continue
  1988. tray_id = int(tray.get("id", 0))
  1989. tag_uid = tray.get("tag_uid", "")
  1990. tray_uuid = tray.get("tray_uuid", "")
  1991. tray_info_idx = tray.get("tray_info_idx", "")
  1992. if not tray.get("tray_type"):
  1993. # Slot reported empty — drop any cached unknown-tag
  1994. # broadcast so reinserting the same spool re-prompts.
  1995. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  1996. continue # Empty slot
  1997. # Check if assignment already exists for this slot
  1998. existing = await db.execute(
  1999. select(SA)
  2000. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2001. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2002. )
  2003. existing_assignment = existing.scalar_one_or_none()
  2004. if existing_assignment:
  2005. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2006. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2007. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2008. # Skip during active prints: the usage tracker handles deduction
  2009. # precisely via 3MF data on print completion. Without this guard the
  2010. # AMS remain% SET and the usage tracker ADD both fire from the same
  2011. # MQTT message, doubling the deduction (#880).
  2012. if _print_active:
  2013. continue
  2014. remain_raw = tray.get("remain")
  2015. if (
  2016. remain_raw is not None
  2017. and existing_assignment.spool
  2018. and not existing_assignment.spool.weight_locked
  2019. ):
  2020. try:
  2021. remain_val = int(remain_raw)
  2022. except (TypeError, ValueError):
  2023. remain_val = -1
  2024. if 1 <= remain_val <= 100:
  2025. lw = existing_assignment.spool.label_weight or 1000
  2026. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2027. current_used = existing_assignment.spool.weight_used or 0
  2028. if new_used > current_used + 1:
  2029. logger.info(
  2030. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2031. existing_assignment.spool_id,
  2032. current_used,
  2033. new_used,
  2034. remain_val,
  2035. )
  2036. existing_assignment.spool.weight_used = new_used
  2037. await db.commit()
  2038. # Re-apply stored K-profile when the live tray's
  2039. # cali_idx drifted from the spool's stored profile.
  2040. # This catches "reset slot → re-read" and any other
  2041. # path where the firmware loses the user's K-profile
  2042. # selection while the SpoolAssignment row persists.
  2043. # Per the maintainer's rule: any time a spool tag is
  2044. # identified and matches inventory, the slot must be
  2045. # configured with the spool's stored settings. Without
  2046. # this block the existing-assignment branch only ran
  2047. # weight-sync and let the firmware-default cali_idx win.
  2048. try:
  2049. spool = existing_assignment.spool
  2050. if (
  2051. spool is not None
  2052. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  2053. and spool.k_profiles
  2054. ):
  2055. state = printer_manager.get_status(printer_id)
  2056. nozzle_diameter = "0.4"
  2057. if state and state.nozzles:
  2058. nd = state.nozzles[0].nozzle_diameter
  2059. if nd:
  2060. nozzle_diameter = nd
  2061. slot_extruder = resolve_slot_extruder(
  2062. ams_id,
  2063. tray_id,
  2064. state.ams_extruder_map if state else None,
  2065. state.ams_switch_inlet if state else None,
  2066. )
  2067. # Prefer exact extruder match, fall back to
  2068. # extruder-agnostic kp for the same printer +
  2069. # nozzle. Avoids hard-skipping when the AMS is
  2070. # mapped differently than at calibration time.
  2071. matching_kp = None
  2072. fallback_kp = None
  2073. for kp in spool.k_profiles:
  2074. if (
  2075. kp.printer_id != printer_id
  2076. or kp.nozzle_diameter != nozzle_diameter
  2077. or kp.cali_idx is None
  2078. ):
  2079. continue
  2080. if (
  2081. slot_extruder is not None
  2082. and kp.extruder is not None
  2083. and kp.extruder == slot_extruder
  2084. ):
  2085. matching_kp = kp
  2086. break
  2087. if fallback_kp is None:
  2088. fallback_kp = kp
  2089. chosen_kp = matching_kp or fallback_kp
  2090. if chosen_kp is not None:
  2091. live_cali_idx = tray.get("cali_idx")
  2092. # Only fire MQTT when the printer's live
  2093. # cali_idx differs from the stored value.
  2094. # Avoids spamming the broker on every
  2095. # MQTT push during steady-state operation.
  2096. if live_cali_idx != chosen_kp.cali_idx:
  2097. client = printer_manager.get_client(printer_id)
  2098. if client:
  2099. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  2100. client.extrusion_cali_sel(
  2101. ams_id=ams_id,
  2102. tray_id=tray_id,
  2103. cali_idx=chosen_kp.cali_idx,
  2104. filament_id=cali_filament_id,
  2105. nozzle_diameter=nozzle_diameter,
  2106. )
  2107. logger.info(
  2108. "Re-applied K-profile cali_idx=%d for spool %d "
  2109. "on printer %d AMS%d-T%d (live=%s drift detected)",
  2110. chosen_kp.cali_idx,
  2111. spool.id,
  2112. printer_id,
  2113. ams_id,
  2114. tray_id,
  2115. live_cali_idx,
  2116. )
  2117. except Exception:
  2118. logger.exception(
  2119. "K-profile re-apply failed for printer %d AMS%d-T%d",
  2120. printer_id,
  2121. ams_id,
  2122. tray_id,
  2123. )
  2124. continue
  2125. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2126. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2127. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2128. if not spool:
  2129. # Try matching an untagged inventory spool (same material/color)
  2130. spool = await find_matching_untagged_spool(db, tray)
  2131. if spool:
  2132. await link_tag_to_inventory_spool(db, spool, tray)
  2133. elif _auto_add_unknown:
  2134. spool = await create_spool_from_tray(db, tray)
  2135. else:
  2136. # Auto-add disabled: surface the slot so the
  2137. # user can add it manually via the UI.
  2138. await _broadcast_unknown_tag(
  2139. printer_id=printer_id,
  2140. ams_id=ams_id,
  2141. tray_id=tray_id,
  2142. tag_uid=tag_uid,
  2143. tray_uuid=tray_uuid,
  2144. tray_type=tray.get("tray_type"),
  2145. tray_color=tray.get("tray_color"),
  2146. tray_sub_brands=tray.get("tray_sub_brands"),
  2147. tray_count=len(ams_unit.get("tray", [])),
  2148. )
  2149. continue
  2150. # Slot matched (existing tag, untagged inventory
  2151. # match, or freshly auto-created spool) — drop any
  2152. # stale dedup so a future tag swap re-prompts.
  2153. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2154. await auto_assign_spool(
  2155. printer_id,
  2156. ams_id,
  2157. tray_id,
  2158. spool,
  2159. printer_manager,
  2160. db,
  2161. tray_info_idx=tray_info_idx,
  2162. )
  2163. await db.commit()
  2164. await ws_manager.broadcast(
  2165. {
  2166. "type": "spool_auto_assigned",
  2167. "printer_id": printer_id,
  2168. "ams_id": ams_id,
  2169. "tray_id": tray_id,
  2170. "spool_id": spool.id,
  2171. }
  2172. )
  2173. logger.info(
  2174. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2175. spool.id,
  2176. printer_id,
  2177. ams_id,
  2178. tray_id,
  2179. )
  2180. elif is_valid_tag(tag_uid, tray_uuid):
  2181. # Non-BL spool with some tag — let user choose
  2182. await _broadcast_unknown_tag(
  2183. printer_id=printer_id,
  2184. ams_id=ams_id,
  2185. tray_id=tray_id,
  2186. tag_uid=tag_uid,
  2187. tray_uuid=tray_uuid,
  2188. tray_type=tray.get("tray_type"),
  2189. tray_color=tray.get("tray_color"),
  2190. tray_sub_brands=tray.get("tray_sub_brands"),
  2191. tray_count=len(ams_unit.get("tray", [])),
  2192. )
  2193. # No-tag slots (generic non-RFID filament) are left alone:
  2194. # nothing to identify, prompting "+ Add" would just create
  2195. # ghost spools with empty tags on every confirm.
  2196. except Exception as e:
  2197. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2198. try:
  2199. async with async_session() as db:
  2200. from backend.app.api.routes.settings import get_setting
  2201. from backend.app.models.printer import Printer
  2202. # Check if Spoolman is enabled
  2203. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2204. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2205. return
  2206. # Check sync mode
  2207. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2208. if sync_mode and sync_mode != "auto":
  2209. return # Only sync on auto mode
  2210. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2211. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2212. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2213. # always owned by per-print tracking, never by AMS auto-sync. The
  2214. # setting is still read by the settings UI for backwards compat but
  2215. # has no effect on the sync path here.
  2216. # Get Spoolman URL
  2217. spoolman_url = await get_setting(db, "spoolman_url")
  2218. if not spoolman_url:
  2219. return
  2220. # Get or create Spoolman client
  2221. client = await get_spoolman_client()
  2222. if not client:
  2223. try:
  2224. client = await init_spoolman_client(spoolman_url)
  2225. except ValueError as exc:
  2226. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2227. return
  2228. # Check if Spoolman is reachable
  2229. if not await client.health_check():
  2230. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2231. return
  2232. # Get printer name for location
  2233. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2234. printer = result.scalar_one_or_none()
  2235. printer_name = printer.name if printer else f"Printer {printer_id}"
  2236. # OPTIMIZATION: Fetch all spools once before processing trays
  2237. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2238. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2239. try:
  2240. cached_spools = await client.get_spools()
  2241. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2242. except Exception as e:
  2243. logger.error(
  2244. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2245. printer_id,
  2246. e,
  2247. )
  2248. return
  2249. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2250. from sqlalchemy.orm import selectinload
  2251. from backend.app.models.spool_assignment import SpoolAssignment
  2252. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2253. inventory_weights: dict[tuple[int, int], float] = {}
  2254. try:
  2255. assign_result = await db.execute(
  2256. select(SpoolAssignment)
  2257. .options(selectinload(SpoolAssignment.spool))
  2258. .where(SpoolAssignment.printer_id == printer_id)
  2259. )
  2260. for assignment in assign_result.scalars().all():
  2261. spool = assignment.spool
  2262. if spool and spool.label_weight > 0:
  2263. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2264. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2265. except Exception as e:
  2266. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2267. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2268. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2269. try:
  2270. slot_result = await db.execute(
  2271. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2272. )
  2273. for slot in slot_result.scalars().all():
  2274. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2275. except Exception as e:
  2276. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2277. # Sync each AMS tray and collect slot changes for DB persistence
  2278. synced = 0
  2279. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2280. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2281. for ams_unit in ams_data:
  2282. if not isinstance(ams_unit, dict):
  2283. continue
  2284. ams_id = int(ams_unit.get("id", 0))
  2285. trays = ams_unit.get("tray", [])
  2286. for tray_data in trays:
  2287. if not isinstance(tray_data, dict):
  2288. continue
  2289. tray_id_raw = int(tray_data.get("id", 0))
  2290. tray = client.parse_ams_tray(ams_id, tray_data)
  2291. if not tray:
  2292. # Empty tray slot — record for local assignment cleanup
  2293. # and drop any cached unknown-tag broadcast so a
  2294. # reinserted spool re-prompts.
  2295. #
  2296. # Not during a running print: a slot that empties there
  2297. # is a filament runout, and the spool is still in the
  2298. # AMS. `spoolman_slot_assignments` is how a tag-less
  2299. # spool assigned through the Bambuddy UI is resolved at
  2300. # completion (#1459), so deleting the row mid-print
  2301. # loses the runout segment's usage — the same failure
  2302. # the internal inventory's auto-unlink had.
  2303. if not printing_now:
  2304. empty_slots.append((ams_id, tray_id_raw))
  2305. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2306. continue
  2307. spool_tag = (
  2308. tray.tray_uuid
  2309. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2310. else tray.tag_uid
  2311. )
  2312. # Provide the hint only when no RFID is available
  2313. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2314. try:
  2315. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2316. result = await client.sync_ams_tray(
  2317. tray,
  2318. printer_name,
  2319. # Per-print tracking is the only weight writer (#1119).
  2320. # AMS auto-sync still maintains spool metadata / slot
  2321. # assignments but no longer touches remaining_weight.
  2322. disable_weight_sync=True,
  2323. cached_spools=cached_spools,
  2324. inventory_remaining=inv_remaining,
  2325. spoolman_spool_id_hint=hint,
  2326. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2327. )
  2328. if result is None and spool_tag and not auto_add_unknown_rfid:
  2329. # Spoolman skipped auto-create per user setting — surface
  2330. # the slot so the UI can offer "+ Add to inventory".
  2331. await _broadcast_unknown_tag(
  2332. printer_id=printer_id,
  2333. ams_id=ams_id,
  2334. tray_id=tray.tray_id,
  2335. tag_uid=tray.tag_uid or "",
  2336. tray_uuid=tray.tray_uuid or "",
  2337. tray_type=tray.tray_type,
  2338. tray_color=tray.tray_color,
  2339. tray_sub_brands=tray.tray_sub_brands,
  2340. tray_count=len(trays),
  2341. )
  2342. elif result:
  2343. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2344. if result:
  2345. synced += 1
  2346. if result.get("id"):
  2347. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2348. # If a new spool was created, add it to the cache
  2349. # so subsequent trays can find it if they reference the same tag
  2350. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  2351. if not spool_exists:
  2352. cached_spools.append(result)
  2353. logger.debug(
  2354. "[Printer %s] Added newly created spool %s to cache",
  2355. printer_id,
  2356. result["id"],
  2357. )
  2358. # Reconcile slot_preset_mappings (the same row internal
  2359. # mode keeps in sync via inventory + spool_tag_matcher).
  2360. # Without this the slot card surfaces the previous spool's
  2361. # preset name — same bug shape, different inventory mode.
  2362. from backend.app.services.slot_preset_writer import (
  2363. upsert_slot_preset_for_spoolman_spool,
  2364. )
  2365. await upsert_slot_preset_for_spoolman_spool(
  2366. db=db,
  2367. spoolman_spool=result,
  2368. tray_info_idx=tray.tray_info_idx or "",
  2369. tray_sub_brands=tray.tray_sub_brands or "",
  2370. tray_type=tray.tray_type or "",
  2371. printer_id=printer_id,
  2372. ams_id=ams_id,
  2373. tray_id=tray.tray_id,
  2374. )
  2375. except Exception as e:
  2376. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  2377. if synced > 0:
  2378. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  2379. # Persist slot assignment changes to the local table
  2380. if slot_changes or empty_slots:
  2381. try:
  2382. for ams_id, tray_id, spool_id in slot_changes:
  2383. await db.execute(
  2384. text(
  2385. "INSERT INTO spoolman_slot_assignments"
  2386. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  2387. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  2388. " ON CONFLICT(printer_id, ams_id, tray_id)"
  2389. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  2390. ),
  2391. {
  2392. "printer_id": printer_id,
  2393. "ams_id": ams_id,
  2394. "tray_id": tray_id,
  2395. "spool_id": spool_id,
  2396. },
  2397. )
  2398. for ams_id, tray_id in empty_slots:
  2399. await db.execute(
  2400. delete(SpoolmanSlotAssignment).where(
  2401. SpoolmanSlotAssignment.printer_id == printer_id,
  2402. SpoolmanSlotAssignment.ams_id == ams_id,
  2403. SpoolmanSlotAssignment.tray_id == tray_id,
  2404. )
  2405. )
  2406. await db.commit()
  2407. except Exception as e:
  2408. await db.rollback()
  2409. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  2410. except Exception as e:
  2411. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  2412. async def _capture_snapshot_for_notification(printer_id: int, printer, logger) -> bytes | None:
  2413. """Capture a camera snapshot for notification image attachment.
  2414. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  2415. Uses: external camera > buffered frame > fresh capture.
  2416. """
  2417. if not printer:
  2418. return None
  2419. try:
  2420. from backend.app.api.routes.settings import get_setting
  2421. async with async_session() as db:
  2422. capture_enabled = await get_setting(db, "capture_finish_photo")
  2423. if capture_enabled is not None and capture_enabled.lower() != "true":
  2424. return None
  2425. # Try external camera first
  2426. if printer.external_camera_enabled and printer.external_camera_url:
  2427. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  2428. from backend.app.api.routes.camera import live_frame_for_capture
  2429. from backend.app.services.external_camera import capture_frame
  2430. # An external camera allows one reader, so capturing while a viewer
  2431. # is attached fails (#2707). A None here falls through to the paths
  2432. # below exactly as a failed capture did.
  2433. defer, buffered = live_frame_for_capture(printer_id)
  2434. if defer:
  2435. frame_data = buffered
  2436. else:
  2437. frame_data = await capture_frame(
  2438. printer.external_camera_url,
  2439. printer.external_camera_type or "mjpeg",
  2440. snapshot_url=printer.external_camera_snapshot_url,
  2441. )
  2442. if frame_data and len(frame_data) <= 2_500_000:
  2443. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  2444. return _apply_camera_rotation(frame_data, printer, logger)
  2445. # Try buffered frame from active stream
  2446. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  2447. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  2448. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  2449. buffered_frame = get_buffered_frame(printer_id)
  2450. if (active_for_printer or active_chamber) and buffered_frame:
  2451. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  2452. if len(buffered_frame) <= 2_500_000:
  2453. return _apply_camera_rotation(buffered_frame, printer, logger)
  2454. # Fresh capture from printer camera
  2455. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  2456. from backend.app.services.camera import capture_camera_frame_bytes
  2457. frame_data = await capture_camera_frame_bytes(
  2458. printer.ip_address, printer.access_code, printer.model, timeout=15
  2459. )
  2460. if frame_data and len(frame_data) <= 2_500_000:
  2461. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  2462. return _apply_camera_rotation(frame_data, printer, logger)
  2463. except Exception as e:
  2464. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  2465. return None
  2466. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  2467. """#1867: bank a recent in-print camera frame for the finish photo.
  2468. Called on every layer change and (#2547) on every print-progress advance.
  2469. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  2470. path has a pre-End-G-code image for prints that end with a plate swap.
  2471. Both drivers are print telemetry that stops the instant printing ends: no
  2472. further layers, and progress freezes before the End G-code (e.g. SwapMod
  2473. plate swap) executes. So the last banked frame is always the finished print,
  2474. never the swapped plate — that property is what the #1867 path relies on and
  2475. it must survive any change to the throttle below.
  2476. Layer changes alone were not enough: they stop when the *final* layer
  2477. begins, which on a three-minute last layer left the bank stale by the whole
  2478. length of that layer (#2547). Progress keeps ticking through it.
  2479. Best-effort: any failure just leaves the previous banked frame.
  2480. """
  2481. logger = logging.getLogger(__name__)
  2482. client = printer_manager.get_client(printer_id)
  2483. state = client.state if client else None
  2484. if not state or state.state != "RUNNING":
  2485. return
  2486. # Only during actual extrusion — firmware ticks layer_num during the
  2487. # pre-print calibration sequence, whose sub-stages are non-zero.
  2488. if state.mc_print_sub_stage not in (None, 0):
  2489. return
  2490. # #2547: throttled uniformly, with no last-layer exemption. The old code
  2491. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  2492. # now that progress advances also drive banking, that exemption would fire a
  2493. # camera grab on every percent tick of the last layer. Bambu printers accept
  2494. # one RTSP client at a time, so each grab contends with the live view.
  2495. now = time.monotonic()
  2496. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  2497. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  2498. return
  2499. total = state.total_layers or 0
  2500. try:
  2501. async with async_session() as db:
  2502. from backend.app.models.printer import Printer
  2503. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2504. printer = result.scalar_one_or_none()
  2505. if not printer:
  2506. return
  2507. # Reuses the notification snapshot path, which honours the
  2508. # `capture_finish_photo` setting (returns None when disabled) so we
  2509. # don't bank frames the user never asked for.
  2510. frame = await _capture_snapshot_for_notification(printer_id, printer, logger)
  2511. if frame:
  2512. _inprint_frame_bank[printer_id] = frame
  2513. _inprint_frame_bank_ts[printer_id] = now
  2514. logger.debug(
  2515. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  2516. printer_id,
  2517. layer_num,
  2518. total,
  2519. len(frame),
  2520. )
  2521. except Exception as e:
  2522. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  2523. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  2524. """Apply camera rotation to snapshot image if configured."""
  2525. from backend.app.services.camera import apply_camera_rotation
  2526. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  2527. async def _send_print_start_notification(
  2528. printer_id: int,
  2529. data: dict,
  2530. archive_data: dict | None = None,
  2531. logger=None,
  2532. ):
  2533. """Helper to send print start notification with optional archive data."""
  2534. if logger is None:
  2535. logger = logging.getLogger(__name__)
  2536. try:
  2537. async with async_session() as db:
  2538. from backend.app.models.printer import Printer
  2539. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2540. printer = result.scalar_one_or_none()
  2541. printer_name = printer.name if printer else f"Printer {printer_id}"
  2542. # Capture camera snapshot for notification image attachment
  2543. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  2544. if image_data:
  2545. if archive_data is None:
  2546. archive_data = {}
  2547. archive_data["image_data"] = image_data
  2548. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  2549. # Send user-specific email notification for print start
  2550. if archive_data and archive_data.get("created_by_id"):
  2551. await notification_service.send_user_print_email(
  2552. event_type="user_print_start",
  2553. created_by_id=archive_data["created_by_id"],
  2554. printer_name=printer_name,
  2555. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  2556. db=db,
  2557. )
  2558. except Exception as e:
  2559. logger.warning("Notification on_print_start failed: %s", e)
  2560. async def _dispatch_user_print_email(
  2561. status: str,
  2562. created_by_id: int | None,
  2563. printer_name: str,
  2564. filename: str,
  2565. db,
  2566. ) -> None:
  2567. """Send a user-specific print-completion email based on print status.
  2568. Maps the normalised print status to the correct event type and delegates
  2569. to :meth:`NotificationService.send_user_print_email`. A single helper
  2570. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  2571. "stopped"`` dispatch block at every call site.
  2572. Does nothing if *created_by_id* is ``None``.
  2573. """
  2574. if created_by_id is None:
  2575. return
  2576. if status == "completed":
  2577. event_type = "user_print_complete"
  2578. elif status == "failed":
  2579. event_type = "user_print_failed"
  2580. elif status in ("stopped", "aborted", "cancelled"):
  2581. event_type = "user_print_stopped"
  2582. else:
  2583. return
  2584. await notification_service.send_user_print_email(
  2585. event_type=event_type,
  2586. created_by_id=created_by_id,
  2587. printer_name=printer_name,
  2588. filename=filename,
  2589. db=db,
  2590. )
  2591. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  2592. """Extract printable objects from an archive's 3MF file and store in printer state."""
  2593. try:
  2594. from backend.app.services.archive import extract_printable_objects_from_archive
  2595. client = printer_manager.get_client(printer_id)
  2596. if not client:
  2597. return
  2598. # Extract with positions for UI overlay, scoped to the plate that
  2599. # is printing — resolve_plate_id is the same resolver /cover uses,
  2600. # so the object list can't disagree with the thumbnail it is drawn
  2601. # over (#2522).
  2602. printable_objects, bbox_all = extract_printable_objects_from_archive(
  2603. app_settings.base_dir / archive.file_path,
  2604. plate_number=resolve_plate_id(client.state),
  2605. )
  2606. if printable_objects:
  2607. client.state.printable_objects = printable_objects
  2608. client.state.printable_objects_bbox_all = bbox_all
  2609. client.state.skipped_objects = []
  2610. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  2611. except Exception as e:
  2612. logger.debug("Failed to extract printable objects from archive: %s", e)
  2613. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  2614. """Put the skip-objects list back after a restart mid-print.
  2615. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  2616. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  2617. which the #1304 guard suppresses on the first RUNNING push after startup.
  2618. Everything else this hook restores (the archive, the usage-tracking session,
  2619. the timelapse baseline) was already handled; the object list was not, so a
  2620. restart mid-print took skip-objects away for the rest of that print.
  2621. Nothing recovered it either: the printer card gates its Skip button on the
  2622. object count, and the one endpoint that can rebuild the list is reachable
  2623. only from the modal that button opens.
  2624. Anchored on ``subtask_id``, which the firmware mints per print, so a
  2625. leftover ``status="printing"`` row from a completion we never saw cannot
  2626. hand this print someone else's objects. Without one, nothing is loaded
  2627. rather than guessed — the reload path on ``GET /print/objects`` covers that
  2628. case on demand.
  2629. """
  2630. client = printer_manager.get_client(printer_id)
  2631. if client is None or client.state.printable_objects:
  2632. return
  2633. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  2634. if subtask_id in ("", "0"):
  2635. return
  2636. from backend.app.models.archive import PrintArchive
  2637. archive = await db.scalar(
  2638. select(PrintArchive)
  2639. .where(
  2640. PrintArchive.printer_id == printer_id,
  2641. PrintArchive.status == "printing",
  2642. PrintArchive.subtask_id == subtask_id,
  2643. )
  2644. .order_by(PrintArchive.created_at.desc())
  2645. .limit(1)
  2646. )
  2647. if archive is not None:
  2648. _load_objects_from_archive(archive, printer_id, logger)
  2649. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  2650. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  2651. # past it; the second covers a handshake that failed again on the way back and
  2652. # armed a fresh one. Module-level so tests can shrink them.
  2653. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  2654. # printer_id -> the in-flight retry task, so print completion can cancel it.
  2655. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  2656. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  2657. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  2658. # by view, so two views race), the cool-off retry task, and print completion.
  2659. # Without this they each read file_path == "" and each run a full copy, so the row
  2660. # ends up pointing at one timestamped directory while the others sit orphaned.
  2661. #
  2662. # Keyed by printer rather than archive because a printer runs one print at a time,
  2663. # which makes the two equally strong here — and it bounds the dict by printer
  2664. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  2665. # done safely: `Lock.locked()` reads False between release and the queued waiter
  2666. # resuming, so "no waiters" is not a question this API can answer.
  2667. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  2668. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  2669. """Fill in a no-3MF archive from a 3MF that turned up later.
  2670. Returns True when the row was upgraded. Safe to call speculatively: it
  2671. verifies the archive still exists, is still a fallback, and that the file
  2672. is a readable 3MF before touching anything.
  2673. Serialised per printer — see ``_fallback_recovery_locks``.
  2674. """
  2675. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  2676. async with lock:
  2677. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id)
  2678. async def _recover_fallback_archive_locked(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  2679. """The body of :func:`_recover_fallback_archive`, under its per-printer lock."""
  2680. import zipfile
  2681. from backend.app.models.archive import PrintArchive
  2682. from backend.app.services.archive import ArchiveService
  2683. logger = logging.getLogger(__name__)
  2684. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  2685. return False
  2686. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  2687. # A truncated or half-written download is worse than no download: it
  2688. # would replace an honest empty archive with wrong metadata.
  2689. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  2690. return False
  2691. async with async_session() as db:
  2692. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  2693. if archive is None or archive.deleted_at is not None:
  2694. return False
  2695. if archive.file_path:
  2696. # Already recovered, or never was a fallback. Either way there is a
  2697. # real 3MF attached and overwriting it is not this function's job.
  2698. return False
  2699. print_data = (archive.extra_data or {}).get("_print_data") or {}
  2700. service = ArchiveService(db)
  2701. recovered = await service.archive_print(
  2702. printer_id=printer_id,
  2703. source_file=source_3mf,
  2704. print_data={**print_data, "status": archive.status or "printing"},
  2705. subtask_id=archive.subtask_id,
  2706. update_archive_id=archive.id,
  2707. )
  2708. if recovered is None:
  2709. return False
  2710. logger.info(
  2711. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  2712. archive_id,
  2713. source_3mf,
  2714. recovered.file_size,
  2715. )
  2716. # `archive_updated`, not `archive_created` — the row was already on the
  2717. # Archives page as an empty card and is now filled in, not new.
  2718. await ws_manager.send_archive_updated(
  2719. {
  2720. "id": recovered.id,
  2721. "printer_id": recovered.printer_id,
  2722. "filename": recovered.filename,
  2723. "print_name": recovered.print_name,
  2724. "status": recovered.status,
  2725. }
  2726. )
  2727. return True
  2728. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path) -> bool:
  2729. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  2730. Called from the paths that pull a 3MF for a print that is already under way
  2731. — chiefly the cover endpoint, which downloads the very file the archive flow
  2732. could not get and, before #2957, used it for a thumbnail and nothing else.
  2733. The bytes are already local, so this costs a parse and a row update.
  2734. No-op when the running print has a real archive, which is the common case.
  2735. """
  2736. from backend.app.models.archive import PrintArchive
  2737. logger = logging.getLogger(__name__)
  2738. # `_active_prints` is keyed on the raw names seen at print start — the
  2739. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  2740. # Callers here arrive with whichever variant their own path produced, so
  2741. # match on the same normalization the download cache uses rather than on an
  2742. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  2743. # endpoint find an archive registered under "Desktop_Goose".
  2744. wanted = normalize_3mf_name(name)
  2745. archive_id = None
  2746. for (key_printer_id, key_name), value in list(_active_prints.items()):
  2747. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  2748. archive_id = value
  2749. break
  2750. if archive_id is None:
  2751. return False
  2752. async with async_session() as db:
  2753. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  2754. # Cheap pre-check so the common case (a normal archive) does no work.
  2755. if archive is None or archive.file_path or archive.deleted_at is not None:
  2756. return False
  2757. try:
  2758. return await _recover_fallback_archive(archive_id, path, printer_id)
  2759. except Exception as e:
  2760. # Recovery is opportunistic. A failure here must never take down the
  2761. # caller, which is usually just trying to render a thumbnail.
  2762. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  2763. return False
  2764. def _schedule_fallback_3mf_retry(printer_id: int, archive_id: int, filenames: list[str]) -> None:
  2765. """Re-attempt the 3MF download after the printer's FTPS cool-off clears."""
  2766. logger = logging.getLogger(__name__)
  2767. async def _retry() -> None:
  2768. from backend.app.models.archive import PrintArchive
  2769. from backend.app.models.printer import Printer
  2770. for delay in _FALLBACK_3MF_RETRY_DELAYS_SECONDS:
  2771. await asyncio.sleep(delay)
  2772. async with async_session() as db:
  2773. archive = (
  2774. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2775. ).scalar_one_or_none()
  2776. if archive is None or archive.deleted_at is not None or archive.file_path:
  2777. return
  2778. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  2779. if printer is None:
  2780. return
  2781. # Read the fields while the session is open rather than touching
  2782. # a detached instance minutes later, mid-download.
  2783. printer_ip = printer.ip_address
  2784. printer_code = printer.access_code
  2785. printer_model = printer.model
  2786. # Someone else may have fetched it in the meantime — the cover
  2787. # endpoint routinely does, and its copy is the same bytes.
  2788. for name in filenames:
  2789. cached = get_cached_3mf(printer_id, name)
  2790. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  2791. return
  2792. if ftps_handshake_blocked(printer_ip):
  2793. logger.info(
  2794. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  2795. printer_id,
  2796. archive_id,
  2797. )
  2798. continue
  2799. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  2800. for candidate in filenames:
  2801. # Bare name only. These come from the print-start flow, which
  2802. # already strips the path, but the local temp write must not
  2803. # depend on that holding for every future caller — a name that
  2804. # is absolute or contains ".." would otherwise escape the data
  2805. # volume via the `/` operator.
  2806. name = Path(candidate).name
  2807. if not name or name in (".", ".."):
  2808. continue
  2809. if not name.endswith(".3mf"):
  2810. name = f"{name}.3mf"
  2811. temp_path = app_settings.archive_dir / "temp" / name
  2812. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2813. try:
  2814. hit = await download_file_try_paths_async(
  2815. printer_ip,
  2816. printer_code,
  2817. ftp_probe_paths(name),
  2818. temp_path,
  2819. socket_timeout=ftp_timeout,
  2820. printer_model=printer_model,
  2821. )
  2822. except Exception as e:
  2823. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  2824. continue
  2825. if not hit:
  2826. continue
  2827. cache_3mf_download(printer_id, name, temp_path)
  2828. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  2829. return
  2830. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  2831. async def _guarded() -> None:
  2832. try:
  2833. await _retry()
  2834. except asyncio.CancelledError:
  2835. raise
  2836. except Exception as e:
  2837. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  2838. finally:
  2839. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  2840. _fallback_3mf_retry_tasks.pop(printer_id, None)
  2841. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  2842. if existing and not existing.done():
  2843. existing.cancel()
  2844. task = asyncio.create_task(_guarded())
  2845. _fallback_3mf_retry_tasks[printer_id] = task
  2846. logger.info(
  2847. "[RECOVER] Archive %s has no 3MF because printer %s was in its FTPS cool-off; will retry",
  2848. archive_id,
  2849. printer_id,
  2850. )
  2851. async def on_print_start(printer_id: int, data: dict):
  2852. """Handle print start - archive the 3MF file immediately."""
  2853. logger = logging.getLogger(__name__)
  2854. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  2855. # Clear any stale user-stopped flag from previous print cycles
  2856. _user_stopped_printers.discard(printer_id)
  2857. _kill_switch_notification_tasks.pop(printer_id, None)
  2858. # #1721: drop any leftover pre-captured finish frame from a prior print
  2859. # so a never-consumed cache entry can't bleed into the new print's photo.
  2860. _stage22_finish_frames.pop(printer_id, None)
  2861. # #1867: same for the in-print frame bank — a queued print must not reuse
  2862. # the previous job's banked frame.
  2863. _inprint_frame_bank.pop(printer_id, None)
  2864. _inprint_frame_bank_ts.pop(printer_id, None)
  2865. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  2866. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  2867. # print's flag instead of inheriting it.
  2868. print_dispatch_context.adopt(printer_id)
  2869. # Cancel any active bed cooldown waiter for this printer
  2870. if _bed_cool_waiters.pop(printer_id, None):
  2871. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  2872. # Clear cached cover images so the new print's thumbnail is fetched fresh
  2873. from backend.app.api.routes.printers import clear_cover_cache
  2874. clear_cover_cache(printer_id)
  2875. await ws_manager.send_print_start(printer_id, data)
  2876. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  2877. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  2878. # MQTT relay - publish print start
  2879. try:
  2880. printer_info = printer_manager.get_printer(printer_id)
  2881. if printer_info:
  2882. await mqtt_relay.on_print_start(
  2883. printer_id,
  2884. printer_info.name,
  2885. printer_info.serial_number,
  2886. data.get("filename", ""),
  2887. data.get("subtask_name", ""),
  2888. )
  2889. except Exception:
  2890. pass # Don't fail print start callback if MQTT fails
  2891. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  2892. # and mapping, and the seeded tray-change log.
  2893. #
  2894. # Unconditional, for both inventory backends. This only *captures* — the
  2895. # writing is still split, with the internal tracker skipped at completion
  2896. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  2897. # carries its plate-scoped 3MF figures and stored mapping, but not the
  2898. # tray-change log, and that log is the only record of which spool fed
  2899. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  2900. # it on one side only would leave Spoolman users with the mid-print
  2901. # restart bug this fixes for everyone else.
  2902. try:
  2903. async with async_session() as db:
  2904. from backend.app.api.routes.settings import get_setting
  2905. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  2906. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2907. await usage_on_print_start(
  2908. printer_id,
  2909. data,
  2910. printer_manager,
  2911. db=db,
  2912. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  2913. )
  2914. except Exception as e:
  2915. logger.warning("Usage tracker on_print_start failed: %s", e)
  2916. # Track if notification was sent (to avoid sending twice)
  2917. notification_sent = False
  2918. # Smart plug automation: turn on plug when print starts
  2919. try:
  2920. async with async_session() as db:
  2921. await smart_plug_manager.on_print_start(printer_id, db)
  2922. except Exception as e:
  2923. logger.warning("Smart plug on_print_start failed: %s", e)
  2924. async with async_session() as db:
  2925. from backend.app.models.printer import Printer
  2926. from backend.app.services.bambu_ftp import list_files_async
  2927. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2928. printer = result.scalar_one_or_none()
  2929. # Plate detection check - pause if objects detected on build plate
  2930. logger.info(
  2931. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  2932. )
  2933. if printer and printer.plate_detection_enabled:
  2934. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  2935. # Release the pooled DB connection before the plate-detection camera
  2936. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  2937. # printer SELECT has run so far — nothing to persist — so this commit
  2938. # is a data-noop that ends the read transaction and returns the
  2939. # connection to the pool during the I/O (issue #2572). expire_on_commit
  2940. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  2941. # archive lookups below re-acquire a fresh connection on next execute.
  2942. await db.commit()
  2943. try:
  2944. from backend.app.services.plate_detection import check_plate_empty
  2945. # Build ROI tuple from printer settings if available
  2946. roi = None
  2947. if all(
  2948. [
  2949. printer.plate_detection_roi_x is not None,
  2950. printer.plate_detection_roi_y is not None,
  2951. printer.plate_detection_roi_w is not None,
  2952. printer.plate_detection_roi_h is not None,
  2953. ]
  2954. ):
  2955. roi = (
  2956. printer.plate_detection_roi_x,
  2957. printer.plate_detection_roi_y,
  2958. printer.plate_detection_roi_w,
  2959. printer.plate_detection_roi_h,
  2960. )
  2961. # Auto-turn on chamber light if it's off for better detection
  2962. light_was_off = False
  2963. client = printer_manager.get_client(printer_id)
  2964. if client and client.state:
  2965. light_was_off = not client.state.chamber_light
  2966. if light_was_off:
  2967. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  2968. client.set_chamber_light(True)
  2969. # Wait for light to physically turn on and camera to adjust exposure
  2970. await asyncio.sleep(2.5)
  2971. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  2972. plate_result = await check_plate_empty(
  2973. printer_id=printer_id,
  2974. ip_address=printer.ip_address,
  2975. access_code=printer.access_code,
  2976. model=printer.model,
  2977. include_debug_image=False,
  2978. external_camera_url=printer.external_camera_url,
  2979. external_camera_type=printer.external_camera_type,
  2980. use_external=printer.external_camera_enabled,
  2981. roi=roi,
  2982. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  2983. )
  2984. # Restore chamber light to original state
  2985. if light_was_off and client:
  2986. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  2987. client.set_chamber_light(False)
  2988. if not plate_result.needs_calibration and not plate_result.is_empty:
  2989. # Objects detected - pause the print!
  2990. logger.warning(
  2991. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  2992. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  2993. )
  2994. client = printer_manager.get_client(printer_id)
  2995. if client:
  2996. client.pause_print()
  2997. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  2998. # Send notification about plate not empty
  2999. await ws_manager.broadcast(
  3000. {
  3001. "type": "plate_not_empty",
  3002. "printer_id": printer_id,
  3003. "printer_name": printer.name,
  3004. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  3005. }
  3006. )
  3007. # Also send push notification
  3008. try:
  3009. await notification_service.on_plate_not_empty(
  3010. printer_id=printer_id,
  3011. printer_name=printer.name,
  3012. db=db,
  3013. difference_percent=plate_result.difference_percent,
  3014. )
  3015. except Exception as notif_err:
  3016. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  3017. else:
  3018. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  3019. except Exception as plate_err:
  3020. # Don't block print on plate detection errors
  3021. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  3022. if not printer:
  3023. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  3024. if not notification_sent:
  3025. await _send_print_start_notification(printer_id, data, logger=logger)
  3026. return
  3027. if not printer.auto_archive:
  3028. # auto-archive disabled — check if there's an expected print (dispatched
  3029. # by BamBuddy via queue/reprint) that already has an archive to promote.
  3030. # If so, fall through to the expected-print handling below so the archive
  3031. # is tracked in _active_prints and usage tracking works at completion.
  3032. _fn = data.get("filename", "")
  3033. _sn = data.get("subtask_name", "")
  3034. _check_keys: list[tuple[int, str]] = []
  3035. if _sn:
  3036. _check_keys += [
  3037. (printer_id, _sn),
  3038. (printer_id, f"{_sn}.3mf"),
  3039. (printer_id, f"{_sn}.gcode.3mf"),
  3040. ]
  3041. if _fn:
  3042. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  3043. _check_keys.append((printer_id, _base_fn))
  3044. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  3045. _check_keys += [
  3046. (printer_id, _no_archive_base),
  3047. (printer_id, f"{_no_archive_base}.3mf"),
  3048. ]
  3049. _has_expected = any(k in _expected_prints for k in _check_keys)
  3050. if not _has_expected:
  3051. # No expected print — truly external print (started from slicer/touchscreen)
  3052. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  3053. if not notification_sent:
  3054. _no_archive_creator: int | None = None
  3055. for _key in _check_keys:
  3056. _expected_prints.pop(_key, None)
  3057. _expected_print_registered_at.pop(_key, None)
  3058. popped_creator = _expected_print_creators.pop(_key, None)
  3059. if _no_archive_creator is None:
  3060. _no_archive_creator = popped_creator
  3061. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  3062. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  3063. return
  3064. else:
  3065. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  3066. # Get the filename and subtask_name
  3067. filename = data.get("filename", "")
  3068. subtask_name = data.get("subtask_name", "")
  3069. # MQTT subtask_id uniquely identifies a print job on the printer. When
  3070. # present, it lets us match an archive across a backend restart (#972):
  3071. # same id → same print → resume the existing row instead of cancelling
  3072. # it and recreating from scratch (which loses started_at). Treat "0"
  3073. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  3074. raw_mqtt = data.get("raw_data") or {}
  3075. subtask_id = raw_mqtt.get("subtask_id")
  3076. if subtask_id is not None:
  3077. subtask_id = str(subtask_id).strip()
  3078. if subtask_id in ("", "0"):
  3079. subtask_id = None
  3080. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  3081. # Skip the printer's own jobs — a calibration run is not a user's print.
  3082. # See is_internal_printer_job for what counts and why both fields are
  3083. # tested; the pressure-advance line reports as a subtask name with no
  3084. # /usr/ path, which the old prefix-only test here missed entirely.
  3085. #
  3086. # No notification either. The event describes the printer calibrating
  3087. # itself, so "Print started" is as wrong as the archive was, and the
  3088. # matching completion is suppressed in on_print_complete for the same
  3089. # reason.
  3090. if is_internal_printer_job(filename, subtask_name):
  3091. logger.info(
  3092. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  3093. filename,
  3094. subtask_name,
  3095. )
  3096. return
  3097. if not filename and not subtask_name:
  3098. # Send notification without archive data (no filename)
  3099. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  3100. if not notification_sent:
  3101. await _send_print_start_notification(printer_id, data, logger=logger)
  3102. return
  3103. # Check if this is an expected print from reprint/scheduled
  3104. # Build list of possible keys to check
  3105. expected_keys = []
  3106. if subtask_name:
  3107. expected_keys.append((printer_id, subtask_name))
  3108. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  3109. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3110. if filename:
  3111. fname = filename.split("/")[-1] if "/" in filename else filename
  3112. expected_keys.append((printer_id, fname))
  3113. # Strip extensions to match
  3114. base = fname.replace(".gcode", "").replace(".3mf", "")
  3115. expected_keys.append((printer_id, base))
  3116. expected_keys.append((printer_id, f"{base}.3mf"))
  3117. expected_archive_id = None
  3118. for key in expected_keys:
  3119. expected_archive_id = _expected_prints.pop(key, None)
  3120. _expected_print_registered_at.pop(key, None)
  3121. if expected_archive_id:
  3122. # Clean up other possible keys for this print
  3123. for other_key in expected_keys:
  3124. _expected_prints.pop(other_key, None)
  3125. _expected_print_registered_at.pop(other_key, None)
  3126. break
  3127. if expected_archive_id:
  3128. # This is a reprint/scheduled print - use existing archive, don't create new one
  3129. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  3130. from backend.app.models.archive import PrintArchive
  3131. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  3132. archive = result.scalar_one_or_none()
  3133. if archive:
  3134. # Update archive status to printing
  3135. archive.status = "printing"
  3136. archive.started_at = datetime.now(timezone.utc)
  3137. # Reprint of an archive reuses the source row. Without resetting
  3138. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  3139. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  3140. # extracts the *original* print's last frame, which then ships in
  3141. # the completion notification (#1707). Clear the path so the
  3142. # scanner runs fresh; also unlink the old video file so reprints
  3143. # don't accumulate orphans in the archive directory. Photos list
  3144. # is left alone — accumulating one finish photo per run is fine.
  3145. # The print-start baseline (#2704) is stale for the same reason:
  3146. # it describes the printer before the previous run. The capture
  3147. # below overwrites it, but clear it here too so an early failure
  3148. # can't leave the scan diffing against the wrong snapshot.
  3149. archive.timelapse_baseline = None
  3150. stale_timelapse_relpath = archive.timelapse_path
  3151. if stale_timelapse_relpath:
  3152. archive.timelapse_path = None
  3153. try:
  3154. stale_path = app_settings.base_dir / stale_timelapse_relpath
  3155. if stale_path.is_file():
  3156. stale_path.unlink()
  3157. logger.info(
  3158. "Deleted stale timelapse %s on reprint of archive %s",
  3159. stale_timelapse_relpath,
  3160. expected_archive_id,
  3161. )
  3162. except OSError as e:
  3163. logger.warning(
  3164. "Failed to delete stale timelapse %s on reprint: %s",
  3165. stale_timelapse_relpath,
  3166. e,
  3167. )
  3168. # Persist a restart-stable id so a later restart resumes this
  3169. # archive by subtask_id instead of name-matching + duplicating
  3170. # it (#1485). The printer often hasn't echoed subtask_id back
  3171. # this soon after dispatch, so fall back to the id Bambuddy
  3172. # minted when it sent the print command. Scoped to this
  3173. # expected-print branch on purpose: an expected match means
  3174. # Bambuddy dispatched this exact print in this process, so the
  3175. # client's last-dispatch id genuinely belongs to it — using it
  3176. # for an externally-started print could mis-tag the archive.
  3177. effective_subtask_id = subtask_id
  3178. if not effective_subtask_id:
  3179. _client = printer_manager.get_client(printer_id)
  3180. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  3181. if _dispatched:
  3182. effective_subtask_id = str(_dispatched).strip() or None
  3183. # Update on first-set OR on reprint (the queue dispatcher mints
  3184. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  3185. # the rewrite for reprints leaves the archive holding the FIRST
  3186. # run's id; if MQTT then reconnects mid-print, the reconciler
  3187. # (#1542) compares the stale stored id against the printer's
  3188. # live id, sees a mismatch, and synthesises a bogus PRINT
  3189. # COMPLETE — exactly the false-positive "Print Stopped" reported
  3190. # in #1807. Inequality check preserves the noop-on-stable-push
  3191. # behaviour the earlier `not archive.subtask_id` guard provided.
  3192. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  3193. archive.subtask_id = effective_subtask_id
  3194. # #1403 follow-up: VP-queue archives are created with
  3195. # printer_id=None at queue-add time (we don't know which
  3196. # printer will run the job yet). When the print actually
  3197. # starts on a specific printer the expected-archive lookup
  3198. # used to skip this assignment, leaving printer_id=None
  3199. # forever — which then disables the "Scan for timelapse"
  3200. # button in ArchivesPage (gated on !archive.printer_id).
  3201. if archive.printer_id != printer_id:
  3202. archive.printer_id = printer_id
  3203. await db.commit()
  3204. # Track as active print
  3205. _active_prints[(printer_id, archive.filename)] = archive.id
  3206. if subtask_name:
  3207. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  3208. # Start timelapse session if external camera is enabled (#1353).
  3209. # Queue / VP-dispatched prints land here in the expected-archive
  3210. # branch and used to skip start_session entirely — frames were
  3211. # never captured and the post-print stitch silently returned None.
  3212. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  3213. # Inject ams_mapping into usage tracker session — the session was created
  3214. # before expected-print promotion, so it may have ams_mapping=None when
  3215. # the MQTT request topic subscription failed (common on P1S/A1).
  3216. _stored_map = _print_ams_mappings.get(expected_archive_id)
  3217. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  3218. if _stored_map or _stored_plate_id is not None:
  3219. try:
  3220. from backend.app.services.usage_tracker import _active_sessions
  3221. _ut_session = _active_sessions.get(printer_id)
  3222. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  3223. _ut_session.ams_mapping = _stored_map
  3224. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  3225. # plate_id injection covers direct-Print of plate N of a multi-plate
  3226. # 3MF — queue prints already capture it via the on_print_start queue
  3227. # lookup, but direct-Print never goes through the queue (#1697).
  3228. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  3229. _ut_session.plate_id = _stored_plate_id
  3230. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  3231. except Exception:
  3232. pass
  3233. # Set up energy tracking (#941: persist start on archive row)
  3234. await _record_energy_start(archive, printer_id, db, context="expected-print")
  3235. await ws_manager.send_archive_updated(
  3236. {
  3237. "id": archive.id,
  3238. "status": "printing",
  3239. }
  3240. )
  3241. # Send notification with archive data (reprint/scheduled)
  3242. if not notification_sent:
  3243. # Use archive's created_by_id; fall back to the creator registered via
  3244. # register_expected_print (handles library-file-based queue items where
  3245. # the freshly-created archive has no created_by_id yet).
  3246. # Pop ALL matching keys so no stale entries remain in the dict.
  3247. fallback_creator = None
  3248. for key in expected_keys:
  3249. popped = _expected_print_creators.pop(key, None)
  3250. if fallback_creator is None:
  3251. fallback_creator = popped
  3252. archive_data = {
  3253. "print_time_seconds": archive.print_time_seconds,
  3254. "created_by_id": archive.created_by_id or fallback_creator,
  3255. }
  3256. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3257. # Extract printable objects from the archived 3MF file
  3258. _load_objects_from_archive(archive, printer_id, logger)
  3259. # Store Spoolman tracking data for per-filament usage reporting
  3260. try:
  3261. await _store_spoolman_print_data(
  3262. printer_id,
  3263. archive.id,
  3264. archive.file_path,
  3265. db,
  3266. printer_manager,
  3267. ams_mapping=_get_start_ams_mapping(data, archive.id),
  3268. plate_id=_get_start_plate_id(archive.id),
  3269. )
  3270. except Exception as e:
  3271. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  3272. # Capture timelapse file baseline for snapshot-diff on completion
  3273. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  3274. # hit this branch — without the baseline the completion-time scan
  3275. # falls into its "take baseline now" fallback, which snapshots
  3276. # AFTER the new MP4 already exists and never matches a diff
  3277. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  3278. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  3279. return # Skip creating a new archive
  3280. # Check if there's already a "printing" archive for this printer/file
  3281. # This prevents duplicates when backend restarts during an active print
  3282. from backend.app.models.archive import PrintArchive
  3283. existing_archive: PrintArchive | None = None
  3284. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  3285. # across a backend restart for the same print, so this is the most
  3286. # reliable way to reattach. We also accept a previously stale-cancelled
  3287. # archive here so users upgrading mid-print get revived when the row
  3288. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  3289. if subtask_id:
  3290. by_id = await db.execute(
  3291. select(PrintArchive)
  3292. .where(PrintArchive.printer_id == printer_id)
  3293. .where(PrintArchive.subtask_id == subtask_id)
  3294. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  3295. .order_by(PrintArchive.created_at.desc())
  3296. .limit(1)
  3297. )
  3298. candidate = by_id.scalar_one_or_none()
  3299. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  3300. existing_archive = candidate
  3301. # Fallback match: name-based lookup. Kept as-is for prints whose
  3302. # subtask_id is missing ("0" / local / non-cloud prints).
  3303. if existing_archive is None:
  3304. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  3305. existing = await db.execute(
  3306. select(PrintArchive)
  3307. .where(PrintArchive.printer_id == printer_id)
  3308. .where(PrintArchive.status == "printing")
  3309. .where(
  3310. or_(
  3311. PrintArchive.print_name == check_name,
  3312. PrintArchive.filename.in_(
  3313. [
  3314. f"{check_name}.3mf",
  3315. f"{check_name}.gcode.3mf",
  3316. ]
  3317. ),
  3318. )
  3319. )
  3320. .order_by(PrintArchive.created_at.desc())
  3321. .limit(1)
  3322. )
  3323. existing_archive = existing.scalar_one_or_none()
  3324. if existing_archive:
  3325. # subtask_id match → always resume, regardless of age. Same print,
  3326. # just a backend restart. Revive if it was previously stale-cancelled.
  3327. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  3328. if subtask_match:
  3329. if existing_archive.status == "cancelled":
  3330. logger.warning(
  3331. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  3332. existing_archive.id,
  3333. subtask_id,
  3334. )
  3335. existing_archive.status = "printing"
  3336. existing_archive.failure_reason = None
  3337. await db.commit()
  3338. else:
  3339. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  3340. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  3341. if existing_archive.energy_start_kwh is None:
  3342. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  3343. if not notification_sent:
  3344. archive_data = {
  3345. "print_time_seconds": existing_archive.print_time_seconds,
  3346. "created_by_id": existing_archive.created_by_id,
  3347. }
  3348. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3349. _load_objects_from_archive(existing_archive, printer_id, logger)
  3350. return
  3351. # Name-match only (no subtask_id to anchor on): decide resume vs.
  3352. # stale from the printer's *current* progress, not wall-clock age.
  3353. # A genuinely long print used to trip a blind 4h cutoff and have its
  3354. # live archive cancelled + duplicated on every backend restart
  3355. # (#1485). If the printer reports real progress, this name-matched
  3356. # 'printing' archive IS that ongoing print — resume it whatever its
  3357. # age. Only treat it as a stale leftover when the printer clearly
  3358. # shows a different, freshly-started print: near-0% progress on an
  3359. # archive far too old to still be at 0%. Unknown progress (printer
  3360. # not connected) never cancels — resuming is the safe default.
  3361. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  3362. live_status = printer_manager.get_status(printer_id)
  3363. live_progress = getattr(live_status, "progress", None) if live_status else None
  3364. looks_stale = (
  3365. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  3366. )
  3367. if looks_stale:
  3368. logger.warning(
  3369. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  3370. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  3371. )
  3372. existing_archive.status = "cancelled"
  3373. existing_archive.failure_reason = "Stale - print likely cancelled or failed without status update"
  3374. await db.commit()
  3375. # Fall through to create new archive (don't return)
  3376. else:
  3377. logger.info(
  3378. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  3379. )
  3380. # Track this as the active print
  3381. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  3382. # Attach subtask_id retroactively so future restarts can resume.
  3383. # Compare for inequality (not "is empty") to also pick up reprint
  3384. # dispatches that mint a fresh id — see #1807 for the bogus
  3385. # "Print Stopped" the strict-empty guard caused on reconnect.
  3386. if subtask_id and existing_archive.subtask_id != subtask_id:
  3387. existing_archive.subtask_id = subtask_id
  3388. await db.commit()
  3389. # Also set up energy tracking if not already tracked (#941: persisted column)
  3390. if existing_archive.energy_start_kwh is None:
  3391. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  3392. # Send notification with archive data (existing archive)
  3393. if not notification_sent:
  3394. archive_data = {
  3395. "print_time_seconds": existing_archive.print_time_seconds,
  3396. "created_by_id": existing_archive.created_by_id,
  3397. }
  3398. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3399. # Extract printable objects from the archived 3MF file
  3400. _load_objects_from_archive(existing_archive, printer_id, logger)
  3401. return
  3402. # Build list of possible 3MF filenames to try
  3403. possible_names = []
  3404. # Bambu printers typically store files as "Name.gcode.3mf"
  3405. # The subtask_name is usually the best source for the filename
  3406. if subtask_name:
  3407. # Try common Bambu naming patterns
  3408. possible_names.append(f"{subtask_name}.gcode.3mf")
  3409. possible_names.append(f"{subtask_name}.3mf")
  3410. # Try original filename with .3mf extension
  3411. if filename:
  3412. # Extract just the filename part, not the full path
  3413. fname = filename.split("/")[-1] if "/" in filename else filename
  3414. if fname.endswith(".3mf"):
  3415. possible_names.append(fname)
  3416. elif fname.endswith(".gcode"):
  3417. base = fname.rsplit(".", 1)[0]
  3418. possible_names.append(f"{base}.gcode.3mf")
  3419. possible_names.append(f"{base}.3mf")
  3420. else:
  3421. possible_names.append(f"{fname}.gcode.3mf")
  3422. possible_names.append(f"{fname}.3mf")
  3423. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  3424. space_variants = []
  3425. for name in possible_names:
  3426. if " " in name:
  3427. space_variants.append(name.replace(" ", "_"))
  3428. possible_names.extend(space_variants)
  3429. # Remove duplicates while preserving order
  3430. seen = set()
  3431. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  3432. logger.info("Trying filenames: %s", possible_names)
  3433. # Release the pooled DB connection before the 3MF FTP download. Reaching
  3434. # here means none of the expected-/existing-archive write branches ran
  3435. # (they all return earlier) — only SELECTs have executed on this path, so
  3436. # this commit persists nothing; it ends the read transaction so the
  3437. # connection returns to the pool during the download. That download tries
  3438. # up to five remote paths per candidate filename with retry/backoff and
  3439. # can run for minutes under FTP contention; holding the session across it
  3440. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  3441. # work runs during the download — the new-archive writes below re-acquire
  3442. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  3443. await db.commit()
  3444. # Try to find and download the 3MF file
  3445. temp_path = None
  3446. downloaded_filename = None
  3447. # Cache check: cover endpoint may have already pulled this 3MF during
  3448. # the print (frontend opens the card and shows the thumbnail) — reuse
  3449. # that file instead of re-downloading 36MB over the same FTP link that
  3450. # just served it (#972). The cache keys on a normalized filename so
  3451. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  3452. for try_filename in possible_names:
  3453. if not try_filename.endswith(".3mf"):
  3454. continue
  3455. cached = get_cached_3mf(printer_id, try_filename)
  3456. if cached:
  3457. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  3458. temp_path = cached
  3459. downloaded_filename = try_filename
  3460. break
  3461. # Does this printer keep the sliced file somewhere FTPS can reach? On
  3462. # H2-series and P2S the answer is routinely no — the file stays on
  3463. # internal eMMC and port 990 only ever serves external storage — and
  3464. # then the whole sweep below (six filenames x five directories x four
  3465. # retries, then the directory walk) is ~110 connections that cannot
  3466. # succeed. Skip it and say why (#2780).
  3467. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  3468. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  3469. # running rather than because the file is somewhere unreachable. The
  3470. # distinction is the whole of #2957: one is permanent, the other clears
  3471. # in minutes with the file still sitting on the printer.
  3472. blocked_by_ftps_cooloff = False
  3473. # Get FTP retry settings
  3474. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  3475. # ...but "the printer put it on eMMC" is where it went, not whether we
  3476. # can read it. An H2D with a card in mirrors the job to /cache and
  3477. # serves it happily, and skipping on the URL alone cost that reporter
  3478. # every archive for two days (#2856). So ask the printer instead of
  3479. # guessing: the dispatch named the exact file, which is one connection
  3480. # walking five paths rather than the sweep's ~110. Only when the probe
  3481. # comes back empty does the verdict's reason stand.
  3482. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  3483. if ftps_handshake_blocked(printer.ip_address):
  3484. # Deliberately NOT recorded as a cool-off give-up. This branch
  3485. # only runs on an unreachable verdict, and that verdict is the
  3486. # honest, permanent reason the archive is empty — the probe was
  3487. # a long shot on top of it. Blaming the cool-off here would
  3488. # schedule a retry for a file sitting on internal eMMC, which is
  3489. # the sweep #2780 removed (#2957).
  3490. logger.debug(
  3491. "Not probing for %s on printer %s: its file service is not answering over TLS",
  3492. storage.probe_filename,
  3493. printer_id,
  3494. )
  3495. else:
  3496. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  3497. probe_path.parent.mkdir(parents=True, exist_ok=True)
  3498. try:
  3499. probe_hit = await download_file_try_paths_async(
  3500. printer.ip_address,
  3501. printer.access_code,
  3502. ftp_probe_paths(storage.probe_filename),
  3503. probe_path,
  3504. socket_timeout=ftp_timeout,
  3505. printer_model=printer.model,
  3506. )
  3507. except Exception as e:
  3508. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  3509. probe_hit = False
  3510. if probe_hit:
  3511. downloaded_filename = storage.probe_filename
  3512. temp_path = probe_path
  3513. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  3514. # Naming the path, not just the file: a printer that keeps
  3515. # uploads around for weeks can serve a same-named copy of an
  3516. # earlier slice, and without the directory in the log that
  3517. # mismatch is invisible rather than merely rare (#1820).
  3518. logger.info(
  3519. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  3520. downloaded_filename,
  3521. probe_hit,
  3522. printer_id,
  3523. storage.reason,
  3524. )
  3525. if not storage.reachable and not downloaded_filename:
  3526. # Same opening words whether or not a probe ran, because that is
  3527. # the phrase support asks people to grep for — only the tail says
  3528. # which of the two happened.
  3529. logger.info(
  3530. "Skipping the 3MF lookup for printer %s: %s — %s",
  3531. printer_id,
  3532. storage.reason,
  3533. "no copy of it on external storage either"
  3534. if storage.probe_filename
  3535. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  3536. )
  3537. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  3538. if not try_filename.endswith(".3mf"):
  3539. continue
  3540. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  3541. # printers, so try it first — deferring it to last cost #972's reporter
  3542. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  3543. # landing on the path that actually had the file.
  3544. remote_paths = [
  3545. f"/{try_filename}",
  3546. f"/cache/{try_filename}",
  3547. f"/model/{try_filename}",
  3548. f"/data/{try_filename}",
  3549. f"/data/Metadata/{try_filename}",
  3550. ]
  3551. temp_path = app_settings.archive_dir / "temp" / try_filename
  3552. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3553. for remote_path in remote_paths:
  3554. if ftps_handshake_blocked(printer.ip_address):
  3555. # The printer's FTPS service is not completing a TLS
  3556. # handshake, so it has no path we could reach — walking the
  3557. # remaining candidates only re-runs the same failure
  3558. # (#2780). Fall through to the no-3MF archive now.
  3559. #
  3560. # Remember *why*, though. This is the one give-up that is
  3561. # temporary: the cool-off clears in minutes and the file was
  3562. # on the printer the whole time. The fallback archive is
  3563. # stamped with it so a retry can be scheduled, and so the
  3564. # Archives banner stops blaming storage (#2957).
  3565. blocked_by_ftps_cooloff = True
  3566. logger.warning(
  3567. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  3568. printer_id,
  3569. )
  3570. break
  3571. logger.debug("Trying FTP download: %s", remote_path)
  3572. try:
  3573. if ftp_retry_enabled:
  3574. downloaded = await with_ftp_retry(
  3575. download_file_async,
  3576. printer.ip_address,
  3577. printer.access_code,
  3578. remote_path,
  3579. temp_path,
  3580. timeout=ftp_timeout,
  3581. socket_timeout=ftp_timeout,
  3582. printer_model=printer.model,
  3583. max_retries=ftp_retry_count,
  3584. retry_delay=ftp_retry_delay,
  3585. operation_name=f"Download 3MF from {remote_path}",
  3586. cooloff_ip=printer.ip_address,
  3587. non_retry_exceptions=(FileNotOnPrinterError,),
  3588. )
  3589. else:
  3590. downloaded = await download_file_async(
  3591. printer.ip_address,
  3592. printer.access_code,
  3593. remote_path,
  3594. temp_path,
  3595. timeout=ftp_timeout,
  3596. socket_timeout=ftp_timeout,
  3597. printer_model=printer.model,
  3598. )
  3599. if downloaded:
  3600. downloaded_filename = try_filename
  3601. logger.info("Downloaded: %s", remote_path)
  3602. # Populate shared cache so the cover endpoint (if it
  3603. # runs next) doesn't refetch the same 36MB over FTP.
  3604. cache_3mf_download(printer_id, try_filename, temp_path)
  3605. break
  3606. except FileNotOnPrinterError:
  3607. # 550 — file isn't at this path. Advance to next candidate
  3608. # without burning the retry budget.
  3609. logger.debug("3MF not at %s (550), trying next path", remote_path)
  3610. except Exception as e:
  3611. logger.debug("FTP download failed for %s: %s", remote_path, e)
  3612. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  3613. break
  3614. # If still not found, try listing directories to find matching file
  3615. # Different printer models use different directory structures. Skipped
  3616. # when the printer's FTPS handshake is failing — the directory walk is
  3617. # five more connections that cannot get further than the download did.
  3618. if (
  3619. not downloaded_filename
  3620. and storage.reachable
  3621. and (filename or subtask_name)
  3622. and not ftps_handshake_blocked(printer.ip_address)
  3623. ):
  3624. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  3625. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  3626. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  3627. for search_dir in search_dirs:
  3628. if downloaded_filename:
  3629. break
  3630. try:
  3631. dir_files = await list_files_async(
  3632. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  3633. )
  3634. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  3635. if threemf_files:
  3636. logger.info(
  3637. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  3638. )
  3639. for f in dir_files:
  3640. if f.get("is_directory"):
  3641. continue
  3642. fname = f.get("name", "")
  3643. # Normalize both for comparison (spaces and underscores are equivalent)
  3644. fname_normalized = fname.lower().replace(" ", "_")
  3645. search_normalized = search_term.replace(" ", "_")
  3646. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  3647. logger.info("Found matching file in %s: %s", search_dir, fname)
  3648. temp_path = app_settings.archive_dir / "temp" / fname
  3649. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3650. remote_full_path = posixpath.join(search_dir, fname)
  3651. if ftp_retry_enabled:
  3652. downloaded = await with_ftp_retry(
  3653. download_file_async,
  3654. printer.ip_address,
  3655. printer.access_code,
  3656. remote_full_path,
  3657. temp_path,
  3658. timeout=ftp_timeout,
  3659. socket_timeout=ftp_timeout,
  3660. printer_model=printer.model,
  3661. max_retries=ftp_retry_count,
  3662. retry_delay=ftp_retry_delay,
  3663. operation_name=f"Download 3MF from {remote_full_path}",
  3664. cooloff_ip=printer.ip_address,
  3665. )
  3666. else:
  3667. downloaded = await download_file_async(
  3668. printer.ip_address,
  3669. printer.access_code,
  3670. remote_full_path,
  3671. temp_path,
  3672. timeout=ftp_timeout,
  3673. socket_timeout=ftp_timeout,
  3674. printer_model=printer.model,
  3675. )
  3676. if downloaded:
  3677. downloaded_filename = fname
  3678. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  3679. cache_3mf_download(printer_id, fname, temp_path)
  3680. break
  3681. except Exception as e:
  3682. logger.debug("Failed to list %s: %s", search_dir, e)
  3683. # Validate the downloaded 3MF actually matches the plate that's running
  3684. # (#1204): subtask_name lags across consecutive plates of the same model,
  3685. # so the first FTP candidate (built from subtask_name) can land on the
  3686. # previous plate's still-resident upload. Cross-check the slice_info
  3687. # plate index against the plate parsed from gcode_file (always fresh —
  3688. # it's the field whose change triggered this callback).
  3689. if downloaded_filename and temp_path:
  3690. expected_plate = parse_plate_id(filename)
  3691. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  3692. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  3693. logger.warning(
  3694. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  3695. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  3696. downloaded_filename,
  3697. actual_plate,
  3698. expected_plate,
  3699. subtask_name,
  3700. )
  3701. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  3702. retry_succeeded = False
  3703. if corrected_subtask and corrected_subtask != subtask_name:
  3704. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  3705. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  3706. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  3707. for remote_path in (
  3708. f"/{try_filename}",
  3709. f"/cache/{try_filename}",
  3710. f"/model/{try_filename}",
  3711. f"/data/{try_filename}",
  3712. f"/data/Metadata/{try_filename}",
  3713. ):
  3714. try:
  3715. if ftp_retry_enabled:
  3716. downloaded = await with_ftp_retry(
  3717. download_file_async,
  3718. printer.ip_address,
  3719. printer.access_code,
  3720. remote_path,
  3721. retry_temp_path,
  3722. timeout=ftp_timeout,
  3723. socket_timeout=ftp_timeout,
  3724. printer_model=printer.model,
  3725. max_retries=ftp_retry_count,
  3726. retry_delay=ftp_retry_delay,
  3727. operation_name=f"Re-download 3MF from {remote_path}",
  3728. cooloff_ip=printer.ip_address,
  3729. non_retry_exceptions=(FileNotOnPrinterError,),
  3730. )
  3731. else:
  3732. downloaded = await download_file_async(
  3733. printer.ip_address,
  3734. printer.access_code,
  3735. remote_path,
  3736. retry_temp_path,
  3737. timeout=ftp_timeout,
  3738. socket_timeout=ftp_timeout,
  3739. printer_model=printer.model,
  3740. )
  3741. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  3742. logger.info(
  3743. "[CALLBACK] Re-download succeeded with corrected name %s "
  3744. "(plate %s) — replacing wrong file",
  3745. try_filename,
  3746. expected_plate,
  3747. )
  3748. try:
  3749. temp_path.unlink(missing_ok=True)
  3750. except OSError:
  3751. pass
  3752. temp_path = retry_temp_path
  3753. downloaded_filename = try_filename
  3754. subtask_name = corrected_subtask
  3755. cache_3mf_download(printer_id, try_filename, temp_path)
  3756. retry_succeeded = True
  3757. break
  3758. elif downloaded:
  3759. # Wrong plate again — discard and keep trying
  3760. try:
  3761. retry_temp_path.unlink(missing_ok=True)
  3762. except OSError:
  3763. pass
  3764. except FileNotOnPrinterError:
  3765. continue
  3766. except Exception as e:
  3767. logger.debug("Re-download failed for %s: %s", remote_path, e)
  3768. if retry_succeeded:
  3769. break
  3770. # If the retry didn't find a matching file, drop the wrong 3MF
  3771. # so the no-3MF fallback below creates an archive whose name
  3772. # at least reflects the right plate.
  3773. if not retry_succeeded:
  3774. logger.warning(
  3775. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  3776. expected_plate,
  3777. )
  3778. try:
  3779. temp_path.unlink(missing_ok=True)
  3780. except OSError:
  3781. pass
  3782. temp_path = None
  3783. downloaded_filename = None
  3784. # Override the stale subtask_name so the fallback archive's
  3785. # print_name reflects the correct plate. Prefer the swapped
  3786. # name when we have one; otherwise let filename win.
  3787. if corrected_subtask:
  3788. subtask_name = corrected_subtask
  3789. else:
  3790. subtask_name = ""
  3791. if not downloaded_filename or not temp_path:
  3792. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  3793. # Create a fallback archive without 3MF data so the print is still tracked
  3794. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  3795. try:
  3796. from backend.app.models.archive import PrintArchive
  3797. # Derive print name from subtask_name or filename
  3798. print_name = subtask_name or filename
  3799. if print_name:
  3800. # Clean up the name (remove extensions, path parts)
  3801. print_name = print_name.split("/")[-1]
  3802. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  3803. else:
  3804. print_name = "Unknown Print"
  3805. # Recover estimated print time from MQTT (best-effort for notifications)
  3806. fallback_print_time = None
  3807. mqtt_remaining = data.get("remaining_time")
  3808. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  3809. fallback_print_time = int(mqtt_remaining)
  3810. if fallback_print_time is None:
  3811. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  3812. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  3813. fallback_print_time = int(mc_remaining * 60)
  3814. # Best-effort filament metadata from MQTT — see
  3815. # _extract_filament_data_from_mqtt. Without this the fallback
  3816. # archive's filament fields stayed NULL even though the AMS
  3817. # state at print start was sitting right there in `data`.
  3818. # The slicer's ams_mapping (when present) narrows the result
  3819. # to slots actually used by the print (#1533).
  3820. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  3821. # Create minimal archive entry
  3822. fallback_archive = PrintArchive(
  3823. printer_id=printer_id,
  3824. filename=filename or f"{print_name}.3mf",
  3825. file_path="", # Empty - no 3MF file available
  3826. file_size=0,
  3827. print_name=print_name,
  3828. print_time_seconds=fallback_print_time,
  3829. status="printing",
  3830. started_at=datetime.now(timezone.utc),
  3831. subtask_id=subtask_id,
  3832. filament_type=mqtt_filament_meta.get("filament_type"),
  3833. filament_color=mqtt_filament_meta.get("filament_color"),
  3834. extra_data={
  3835. "no_3mf_available": True,
  3836. # Why the card is empty, when we know. The banner reads
  3837. # this to stop telling H2/P2 owners to switch on a
  3838. # setting that is already on and would not help (#2780).
  3839. # A cool-off outranks the storage verdict: the sweep was
  3840. # skipped at the transport, so the verdict never got to
  3841. # be tested, and reporting it would blame the SD card
  3842. # for a TLS handshake (#2957).
  3843. "no_3mf_reason": REASON_FTPS_COOLOFF if blocked_by_ftps_cooloff else storage.reason,
  3844. "original_subtask": subtask_name,
  3845. "_print_data": data,
  3846. },
  3847. )
  3848. db.add(fallback_archive)
  3849. await db.commit()
  3850. await db.refresh(fallback_archive)
  3851. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  3852. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  3853. # Track as active print
  3854. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  3855. if filename:
  3856. _active_prints[(printer_id, filename)] = fallback_archive.id
  3857. if subtask_name:
  3858. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  3859. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  3860. # Record starting energy if smart plug available (#941: persisted column)
  3861. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  3862. # Send WebSocket notification
  3863. await ws_manager.send_archive_created(
  3864. {
  3865. "id": fallback_archive.id,
  3866. "printer_id": fallback_archive.printer_id,
  3867. "filename": fallback_archive.filename,
  3868. "print_name": fallback_archive.print_name,
  3869. "status": fallback_archive.status,
  3870. }
  3871. )
  3872. # MQTT relay - publish archive created
  3873. try:
  3874. await mqtt_relay.on_archive_created(
  3875. archive_id=fallback_archive.id,
  3876. print_name=fallback_archive.print_name,
  3877. printer_name=printer.name,
  3878. status=fallback_archive.status,
  3879. )
  3880. except Exception:
  3881. pass # Don't fail if MQTT fails
  3882. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  3883. try:
  3884. await _store_spoolman_print_data(
  3885. printer_id,
  3886. fallback_archive.id,
  3887. fallback_archive.file_path,
  3888. db,
  3889. printer_manager,
  3890. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  3891. plate_id=_get_start_plate_id(fallback_archive.id),
  3892. )
  3893. except Exception as e:
  3894. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  3895. # A cool-off give-up is temporary and the file is on the
  3896. # printer — come back for it once the handshake block clears
  3897. # (#2957). Deliberately not scheduled for a storage verdict:
  3898. # a file on internal eMMC will not appear at any FTPS path
  3899. # however long we wait, and retrying it is exactly the sweep
  3900. # #2780 removed.
  3901. if blocked_by_ftps_cooloff and possible_names:
  3902. # `possible_names`, not the raw MQTT strings: it is the exact
  3903. # list this flow just tried, already stripped of any path
  3904. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  3905. # some firmware) and deduped.
  3906. _schedule_fallback_3mf_retry(
  3907. printer_id=printer_id,
  3908. archive_id=fallback_archive.id,
  3909. filenames=list(possible_names),
  3910. )
  3911. # Send notification without archive data (file not found)
  3912. if not notification_sent:
  3913. await _send_print_start_notification(printer_id, data, logger=logger)
  3914. return
  3915. except Exception as e:
  3916. logger.error("Failed to create fallback archive: %s", e)
  3917. # Send notification without archive data (file not found)
  3918. if not notification_sent:
  3919. await _send_print_start_notification(printer_id, data, logger=logger)
  3920. return
  3921. try:
  3922. # Archive the file with status "printing"
  3923. service = ArchiveService(db)
  3924. archive = await service.archive_print(
  3925. printer_id=printer_id,
  3926. source_file=temp_path,
  3927. print_data={**data, "status": "printing"},
  3928. subtask_id=subtask_id,
  3929. )
  3930. if archive:
  3931. # Track this active print (use both original filename and downloaded filename)
  3932. _active_prints[(printer_id, downloaded_filename)] = archive.id
  3933. if filename and filename != downloaded_filename:
  3934. _active_prints[(printer_id, filename)] = archive.id
  3935. if subtask_name:
  3936. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  3937. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  3938. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  3939. # Record starting energy from smart plug if available (#941: persisted column)
  3940. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  3941. await ws_manager.send_archive_created(
  3942. {
  3943. "id": archive.id,
  3944. "printer_id": archive.printer_id,
  3945. "filename": archive.filename,
  3946. "print_name": archive.print_name,
  3947. "status": archive.status,
  3948. }
  3949. )
  3950. # MQTT relay - publish archive created
  3951. try:
  3952. await mqtt_relay.on_archive_created(
  3953. archive_id=archive.id,
  3954. print_name=archive.print_name,
  3955. printer_name=printer.name,
  3956. status=archive.status,
  3957. )
  3958. except Exception:
  3959. pass # Don't fail if MQTT fails
  3960. # Send notification with archive data (new archive created)
  3961. if not notification_sent:
  3962. archive_data = {
  3963. "print_time_seconds": archive.print_time_seconds,
  3964. "created_by_id": archive.created_by_id,
  3965. }
  3966. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3967. # Extract printable objects for skip object functionality
  3968. try:
  3969. from backend.app.services.archive import extract_printable_objects_from_3mf
  3970. client = printer_manager.get_client(printer_id)
  3971. if client:
  3972. with open(temp_path, "rb") as f:
  3973. threemf_data = f.read()
  3974. # Extract with positions for UI overlay, scoped to the
  3975. # plate that is printing — an all-plates 3MF carries
  3976. # every plate's objects (#2522).
  3977. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  3978. threemf_data,
  3979. plate_number=resolve_plate_id(client.state),
  3980. include_positions=True,
  3981. )
  3982. if printable_objects:
  3983. # Store objects in printer state
  3984. client.state.printable_objects = printable_objects
  3985. client.state.printable_objects_bbox_all = bbox_all
  3986. client.state.skipped_objects = [] # Reset skipped objects for new print
  3987. logger.info(
  3988. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  3989. )
  3990. except Exception as e:
  3991. logger.debug("Failed to extract printable objects: %s", e)
  3992. # Store Spoolman tracking data for per-filament usage reporting
  3993. try:
  3994. await _store_spoolman_print_data(
  3995. printer_id,
  3996. archive.id,
  3997. archive.file_path,
  3998. db,
  3999. printer_manager,
  4000. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4001. plate_id=_get_start_plate_id(archive.id),
  4002. )
  4003. except Exception as e:
  4004. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4005. # Capture timelapse file baseline for snapshot-diff on completion
  4006. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4007. finally:
  4008. # Keep temp_path around until print completes so the cover endpoint
  4009. # can reuse it (#972). Cache eviction in on_print_complete deletes
  4010. # the file. If the cache entry was evicted early (file vanished),
  4011. # clean up any stragglers here to avoid leaking disk on retries.
  4012. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  4013. if temp_path and temp_path.exists() and cached_now != temp_path:
  4014. temp_path.unlink()
  4015. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  4016. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  4017. # tests can shrink them without waiting out real delays.
  4018. #
  4019. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  4020. # looking. Across 247 support bundles the attempt that found the video was #1
  4021. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  4022. # decaying one, which is the signature of a budget that expires while files are
  4023. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  4024. # prints make big videos and the printer writes them after the print ends, so
  4025. # the poll now runs for minutes and costs one FTP LIST per round.
  4026. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  4027. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  4028. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  4029. def _timelapse_scan_max_attempts() -> int:
  4030. """Round cap for the poll, derived from the wall-clock budget.
  4031. The deadline alone is not a sufficient bound: it assumes each round really
  4032. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  4033. and an FTP list that fails immediately would otherwise spin against the
  4034. printer at full speed for the whole window. Whichever bound is reached
  4035. first ends the poll.
  4036. """
  4037. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  4038. # A zero interval makes the wall-clock budget meaningless; fall back to
  4039. # the round count the production interval would have given.
  4040. return 32
  4041. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  4042. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  4043. """Video filenames already attached to some other archive of this printer.
  4044. Used to disambiguate when more than one file is new since the baseline —
  4045. which happens when a previous print's video landed after this print's
  4046. baseline was taken. Ordering the candidates would be the obvious fix and is
  4047. the wrong one: it can only be done on mtime or on the filename timestamp,
  4048. both of which come from the printer's own clock, and a LAN-only printer
  4049. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  4050. ``attach_timelapse`` saves the video into the archive directory under the
  4051. printer's original filename, and the later MP4 conversion keeps the stem,
  4052. so the stem of ``timelapse_path`` recovers what was claimed.
  4053. """
  4054. from backend.app.models.archive import PrintArchive
  4055. rows = await db.execute(
  4056. select(PrintArchive.timelapse_path).where(
  4057. PrintArchive.printer_id == printer_id,
  4058. PrintArchive.id != exclude_archive_id,
  4059. PrintArchive.timelapse_path.is_not(None),
  4060. )
  4061. )
  4062. return {Path(p).stem for p in rows.scalars().all() if p}
  4063. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  4064. """List video files from printer's timelapse directory.
  4065. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  4066. Returns (video_files, found_path) where video_files is a list of file dicts
  4067. and found_path is the directory where they were found, or ([], None).
  4068. """
  4069. from backend.app.services.bambu_ftp import list_files_async
  4070. logger = logging.getLogger(__name__)
  4071. # No card in the slot means no /timelapse to walk — four connections that
  4072. # can only fail, on a path whose failures are swallowed and so would go on
  4073. # costing time silently forever (#2780).
  4074. #
  4075. # ``getattr`` rather than ``printer.id``: every dereference below happens
  4076. # inside the loop's own try/except, so a caller that passed something
  4077. # unexpected used to get an empty listing rather than an exception. Keep
  4078. # that, instead of making this gate the first thing that can raise here.
  4079. printer_id = getattr(printer, "id", None)
  4080. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  4081. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  4082. return [], None
  4083. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  4084. try:
  4085. found_files = await list_files_async(
  4086. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  4087. )
  4088. if found_files:
  4089. video_files = [
  4090. f
  4091. for f in found_files
  4092. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  4093. ]
  4094. if video_files:
  4095. return video_files, timelapse_path
  4096. except Exception as e:
  4097. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  4098. continue
  4099. return [], None
  4100. async def _capture_timelapse_baseline_at_start(
  4101. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  4102. ) -> None:
  4103. """Snapshot the printer's timelapse directory at print start so the
  4104. completion-time scan can pick the new file by set-difference.
  4105. Must be called from every on_print_start path that proceeds to a real
  4106. print — both the new-archive branch and the expected-archive branch (which
  4107. queue / VP-dispatched prints take). Without a baseline,
  4108. _scan_for_timelapse_with_retries falls into its "take baseline now"
  4109. fallback that runs AFTER the new MP4 has already landed on the SD card,
  4110. so the new file ends up in the "baseline" set and no diff ever matches.
  4111. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  4112. unreliable — the snapshot-diff approach sidesteps that entirely.
  4113. When ``archive_id`` is known the baseline is also written to the archive
  4114. row, so it survives a restart and the manual "Scan for Timelapse" button
  4115. can run the same diff instead of falling back to clock-based matching
  4116. (#2704). Only baselines taken at print start are persisted — one taken at
  4117. completion already contains the new video and would poison a later scan.
  4118. """
  4119. names: set[str] | None = None
  4120. try:
  4121. baseline_files, _ = await _list_timelapse_videos(printer)
  4122. names = {f.get("name", "") for f in baseline_files}
  4123. _timelapse_baselines[printer_id] = names
  4124. logger.info(
  4125. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  4126. len(names),
  4127. printer_id,
  4128. )
  4129. except Exception as e:
  4130. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  4131. if archive_id is None:
  4132. return
  4133. try:
  4134. async with async_session() as db:
  4135. from backend.app.models.archive import PrintArchive
  4136. archive = await db.get(PrintArchive, archive_id)
  4137. if archive is not None:
  4138. # Written even when the listing failed, and then as NULL. A
  4139. # reprint reuses the archive row, so leaving the previous run's
  4140. # baseline in place would have the scan diff this print against
  4141. # the state of the printer before the *last* one — and a stale
  4142. # baseline reads as authoritative, where NULL correctly falls
  4143. # back to a fresh snapshot.
  4144. archive.timelapse_baseline = sorted(names) if names is not None else None
  4145. await db.commit()
  4146. except Exception as e:
  4147. # In-memory baseline still covers the normal completion path.
  4148. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  4149. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  4150. """Poll the printer for this print's timelapse and attach it.
  4151. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  4152. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  4153. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  4154. (#2704). Comparing the current listing against the set of filenames that
  4155. existed when the print started needs no clock at all, because the printer
  4156. writes the video only once the print has ended.
  4157. Baseline precedence: the caller's in-memory set, then the one persisted on
  4158. the archive at print start, then a snapshot taken now. The last of those is
  4159. a poor substitute — by completion the new video may already be on the card,
  4160. in which case it lands in the "baseline" and no diff can ever match — but it
  4161. is all that is available for a print that began before Bambuddy started.
  4162. On success the video is deleted from the printer, which keeps ``/timelapse``
  4163. down to the unclaimed files and makes the next diff unambiguous.
  4164. """
  4165. logger = logging.getLogger(__name__)
  4166. # --- Phase 1: establish the baseline -------------------------------------
  4167. try:
  4168. async with async_session() as db:
  4169. from backend.app.models.printer import Printer
  4170. service = ArchiveService(db)
  4171. archive = await service.get_archive(archive_id)
  4172. if not archive:
  4173. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  4174. return
  4175. if archive.timelapse_path:
  4176. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  4177. return
  4178. if not archive.printer_id:
  4179. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  4180. return
  4181. if baseline_names is not None:
  4182. logger.info(
  4183. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  4184. len(baseline_names),
  4185. archive_id,
  4186. )
  4187. elif archive.timelapse_baseline is not None:
  4188. # Persisted at print start — survives a restart mid-print.
  4189. baseline_names = set(archive.timelapse_baseline)
  4190. logger.info(
  4191. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  4192. len(baseline_names),
  4193. archive_id,
  4194. )
  4195. else:
  4196. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  4197. printer = result.scalar_one_or_none()
  4198. if not printer:
  4199. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  4200. return
  4201. baseline_files, _ = await _list_timelapse_videos(printer)
  4202. baseline_names = {f.get("name", "") for f in baseline_files}
  4203. logger.info(
  4204. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  4205. len(baseline_names),
  4206. archive_id,
  4207. )
  4208. except Exception as e:
  4209. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  4210. return
  4211. # --- Phase 2: poll for a file that was not there when the print began -----
  4212. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  4213. max_attempts = _timelapse_scan_max_attempts()
  4214. seen_names: set[str] = set()
  4215. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  4216. attempt = 0
  4217. while True:
  4218. await asyncio.sleep(delay)
  4219. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  4220. attempt += 1
  4221. try:
  4222. from backend.app.models.printer import Printer
  4223. # Read phase: fetch archive + printer in a short session and release
  4224. # the pooled connection BEFORE the FTP list/download below. Holding it
  4225. # across the FTP round-trips left one connection idle-in-transaction per
  4226. # in-flight scan (issue #2572).
  4227. async with async_session() as db:
  4228. service = ArchiveService(db)
  4229. archive = await service.get_archive(archive_id)
  4230. if not archive:
  4231. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  4232. return
  4233. if archive.timelapse_path:
  4234. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  4235. return
  4236. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  4237. printer = result.scalar_one_or_none()
  4238. if not printer:
  4239. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  4240. return
  4241. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  4242. # I/O phase (no DB connection held): FTP list + download.
  4243. video_files, found_path = await _list_timelapse_videos(printer)
  4244. # The poll can run for dozens of rounds, so only narrate a round
  4245. # that saw something change. Repeating the whole listing every 30 s
  4246. # would bury the one interesting line in the support bundle.
  4247. names_now = {f.get("name", "") for f in video_files}
  4248. changed = attempt == 1 or names_now != seen_names
  4249. seen_names = names_now
  4250. speak = logger.info if changed else logger.debug
  4251. if video_files:
  4252. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  4253. if changed:
  4254. for f in video_files[:5]:
  4255. logger.info("[TIMELAPSE] - %s", f.get("name"))
  4256. attached = await _attach_first_unclaimed_timelapse(
  4257. archive_id, printer, video_files, baseline_names, claimed, attempt, logger, quiet=not changed
  4258. )
  4259. if attached:
  4260. return
  4261. else:
  4262. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  4263. except Exception as e:
  4264. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  4265. if attempt >= max_attempts or time.monotonic() >= deadline:
  4266. break
  4267. # No name-match fallback: it compared the print name against the filename,
  4268. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  4269. # bundles it fired 159 times and matched zero times, so all it added was a
  4270. # misleading log line before giving up.
  4271. logger.warning(
  4272. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  4273. archive_id,
  4274. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  4275. )
  4276. async def _attach_first_unclaimed_timelapse(
  4277. archive_id: int,
  4278. printer,
  4279. video_files: list[dict],
  4280. baseline_names: set[str],
  4281. claimed: set[str],
  4282. attempt: int,
  4283. logger: logging.Logger,
  4284. *,
  4285. quiet: bool = False,
  4286. ) -> bool:
  4287. """Download and attach the one video that belongs to this print.
  4288. A candidate is any file absent from the print-start baseline. More than one
  4289. can qualify when a previous print's video landed late, after this print's
  4290. baseline was taken — those are filtered out by name, because they are
  4291. already attached to another archive. Sorting the candidates instead would
  4292. mean sorting on mtime or on the filename timestamp, both of which come from
  4293. the printer's unsynced clock.
  4294. Returns True once a video is attached. The printer's copy is deleted only
  4295. after the attach succeeds on bytes whose length matched the listing.
  4296. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  4297. already seen this exact listing — the poll runs for many rounds and only the
  4298. rounds where something changed are worth an INFO line.
  4299. """
  4300. from backend.app.services.bambu_ftp import (
  4301. delete_archived_timelapse,
  4302. download_file_bytes_async,
  4303. remote_file_settled,
  4304. )
  4305. speak = logger.debug if quiet else logger.info
  4306. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  4307. if not new_files:
  4308. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  4309. return False
  4310. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  4311. if not candidates:
  4312. speak(
  4313. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  4314. attempt,
  4315. len(new_files),
  4316. )
  4317. return False
  4318. if len(candidates) > 1:
  4319. logger.warning(
  4320. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  4321. "the rest stay on the printer for manual selection",
  4322. attempt,
  4323. len(candidates),
  4324. ", ".join(str(f.get("name")) for f in candidates),
  4325. )
  4326. target = candidates[0]
  4327. file_name = target.get("name")
  4328. remote_path = target.get("path") or f"/timelapse/{file_name}"
  4329. logger.info(
  4330. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  4331. attempt,
  4332. file_name,
  4333. archive_id,
  4334. )
  4335. # The listing always carries a size (`list_files` skips entries it can't
  4336. # parse), but read it explicitly: the delete below is destructive and must
  4337. # depend on a size we actually had, not on one we hoped was there.
  4338. expected_size = target.get("size")
  4339. timelapse_data = await download_file_bytes_async(
  4340. printer.ip_address,
  4341. printer.access_code,
  4342. remote_path,
  4343. printer_model=printer.model,
  4344. expected_size=expected_size,
  4345. )
  4346. if not timelapse_data:
  4347. # Short or failed transfer. The printer keeps its copy, so the next
  4348. # round can try again — which is exactly why the delete below is
  4349. # gated on a verified download.
  4350. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  4351. return False
  4352. # The length check above proves we got what the listing said, not that the
  4353. # printer had finished writing. A video still being written can be listed
  4354. # short, served short, and pass — so confirm it has stopped growing before
  4355. # committing to it and deleting the original (#2704).
  4356. if not await remote_file_settled(
  4357. printer.ip_address,
  4358. printer.access_code,
  4359. remote_path,
  4360. len(timelapse_data),
  4361. printer_model=printer.model,
  4362. ):
  4363. return False
  4364. # Write phase: attach in a fresh short-lived session.
  4365. async with async_session() as db:
  4366. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name)
  4367. if not success:
  4368. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  4369. return False
  4370. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  4371. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  4372. await delete_archived_timelapse(
  4373. printer.ip_address,
  4374. printer.access_code,
  4375. remote_path,
  4376. verified=expected_size is not None,
  4377. printer_model=printer.model,
  4378. printer_name=printer.name,
  4379. )
  4380. return True
  4381. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  4382. # module-level so tests can monkeypatch them down to ~0 without timing out.
  4383. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  4384. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  4385. # How long the *background* upgrade keeps waiting after the notification has
  4386. # already gone out (#2704 follow-up). The short bound above exists so a slow
  4387. # printer can't hold up the print-complete notification; this one exists so the
  4388. # archive still ends up with the better frame afterwards.
  4389. #
  4390. # Measured across 261 attaches in the support bundles, the video lands a median
  4391. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  4392. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  4393. # was 546s. Every other model was inside 26s. The long budget is therefore
  4394. # almost entirely for P1-series users; on everything else the short wait already
  4395. # wins and this task never runs.
  4396. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  4397. async def _capture_finish_photo_from_timelapse(
  4398. archive_id: int,
  4399. archive_dir: Path,
  4400. timeout: float | None = None,
  4401. rotation: int = 0,
  4402. ) -> tuple[str | None, bool]:
  4403. """Wait for the per-print timelapse to land on the archive and extract its
  4404. last frame as the finish photo (#1397).
  4405. Bambu firmware stops timelapse recording after the toolhead parks but
  4406. before the bed-drop end-gcode runs, so the last frame frames the finished
  4407. print correctly. A live camera grab at gcode_state=FINISH captures the
  4408. bed already lowered.
  4409. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  4410. ``archive.timelapse_path`` when the file lands. This function polls for
  4411. that field.
  4412. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  4413. the wait ran out with no video on the archive yet — i.e. the video may
  4414. still be coming and a later attempt could succeed. It is False when the
  4415. video landed (whether or not extraction worked), because in that case
  4416. waiting longer changes nothing. The caller uses that to decide between
  4417. falling back permanently and scheduling a background upgrade.
  4418. ``rotation`` is the printer's camera_rotation, applied to the extracted
  4419. still (#2708) so this source agrees with every other finish-photo source.
  4420. The archived video itself is the printer's own file and is left alone —
  4421. rotating it would mean re-encoding it.
  4422. """
  4423. import uuid
  4424. from backend.app.models.archive import PrintArchive
  4425. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  4426. logger = logging.getLogger(__name__)
  4427. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  4428. deadline = asyncio.get_event_loop().time() + budget
  4429. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  4430. while True:
  4431. async with async_session() as db:
  4432. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  4433. archive = result.scalar_one_or_none()
  4434. timelapse_relpath = archive.timelapse_path if archive else None
  4435. if timelapse_relpath:
  4436. video_path = app_settings.base_dir / timelapse_relpath
  4437. if video_path.exists() and video_path.stat().st_size > 0:
  4438. photos_dir = archive_dir / "photos"
  4439. photos_dir.mkdir(parents=True, exist_ok=True)
  4440. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  4441. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  4442. output_path = photos_dir / filename
  4443. if await extract_video_last_frame(video_path, output_path):
  4444. await apply_camera_rotation_to_file(output_path, rotation, logger)
  4445. logger.info(
  4446. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  4447. video_path.name,
  4448. archive_id,
  4449. )
  4450. return filename, False
  4451. logger.warning(
  4452. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  4453. video_path.name,
  4454. archive_id,
  4455. )
  4456. return None, False
  4457. if asyncio.get_event_loop().time() >= deadline:
  4458. logger.info(
  4459. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  4460. archive_id,
  4461. budget,
  4462. )
  4463. return None, True
  4464. await asyncio.sleep(poll_interval)
  4465. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  4466. """Add the timelapse's last frame to an archive after the fact (#2704).
  4467. The print-complete notification waits only ~60s for the video, because
  4468. holding a notification for minutes is worse than sending it with a live
  4469. camera grab. On a P1-series printer the video often lands well after that,
  4470. so the archive used to be stuck with the live grab — which is taken at
  4471. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  4472. the worse photo of the two.
  4473. This keeps waiting in the background and, when the video arrives, extracts
  4474. the frame and puts it *first* in the archive's photo list, so opening the
  4475. gallery shows it. The live grab is deliberately kept: the notification that
  4476. already went out links to that exact file, and deleting it would leave a
  4477. broken image in Discord or Telegram.
  4478. """
  4479. logger = logging.getLogger(__name__)
  4480. filename, _ = await _capture_finish_photo_from_timelapse(
  4481. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  4482. )
  4483. if not filename:
  4484. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  4485. return
  4486. try:
  4487. async with async_session() as db:
  4488. from backend.app.models.archive import PrintArchive
  4489. archive = await db.get(PrintArchive, archive_id)
  4490. if archive is None:
  4491. return
  4492. photos = list(archive.photos or [])
  4493. if filename in photos:
  4494. return
  4495. # Front of the list: PhotoGalleryModal opens at index 0.
  4496. archive.photos = [filename, *photos]
  4497. await db.commit()
  4498. except Exception as e:
  4499. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  4500. return
  4501. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  4502. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  4503. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  4504. """Put the filament-attribution context back after a restart mid-print.
  4505. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  4506. both die with the process. The print keeps running, so at completion the
  4507. tracker would fall back to whatever the printer reports *now* — and AMS
  4508. filament backup makes "now" the substitute tray, charging the whole print
  4509. to the spool that only finished it.
  4510. The persisted row is only trusted when its print name still matches what
  4511. the printer says it is running: a row left behind by a completion we never
  4512. saw must not attach itself to the next print.
  4513. """
  4514. try:
  4515. from backend.app.api.routes.settings import get_setting
  4516. from backend.app.services.usage_tracker import (
  4517. clear_persisted_session,
  4518. get_persisted_print_name,
  4519. restore_session,
  4520. )
  4521. persisted_name = await get_persisted_print_name(db, printer_id)
  4522. current_name = (state.subtask_name or "").strip()
  4523. if persisted_name and current_name and persisted_name.strip() != current_name:
  4524. logger.info(
  4525. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  4526. printer_id,
  4527. persisted_name,
  4528. current_name,
  4529. )
  4530. await clear_persisted_session(db, printer_id)
  4531. # Fall through to seeding: the print on the printer is real, it just
  4532. # isn't the one the row described.
  4533. persisted_log = None
  4534. else:
  4535. # Spoolman users get the tray-change log back but no in-memory
  4536. # session — see ``on_print_start`` on why that dict is load-bearing
  4537. # for the remain%-sync guard.
  4538. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4539. persisted_log = await restore_session(
  4540. db,
  4541. printer_id,
  4542. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  4543. )
  4544. if persisted_log:
  4545. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  4546. # Anything this process already observed goes after the persisted
  4547. # history — the log is ordered by layer, and a fresh process can
  4548. # only have seen changes from later in the print.
  4549. for entry in state.tray_change_log or []:
  4550. if tuple(entry) not in restored:
  4551. restored.append(tuple(entry))
  4552. state.tray_change_log = restored
  4553. tray_now = state.tray_now
  4554. if 0 <= tray_now <= 254:
  4555. if not state.tray_change_log:
  4556. # No persisted history — a print that started before this build,
  4557. # or before the row existed. Seed with the tray feeding right
  4558. # now so the remainder of the print is at least attributable to
  4559. # the right spool.
  4560. state.tray_change_log = [(tray_now, state.layer_num)]
  4561. logger.info(
  4562. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  4563. printer_id,
  4564. tray_now,
  4565. state.layer_num,
  4566. )
  4567. # The tray handler updates ``last_loaded_tray`` on every push
  4568. # regardless of whether it logged a change, so re-align it to avoid
  4569. # a duplicate entry on the next push. Only ever with a real tray:
  4570. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  4571. # 255" fallback, and writing 255 into it would defeat that.
  4572. state.last_loaded_tray = tray_now
  4573. except Exception:
  4574. # Never let attribution recovery cost the caller its timelapse
  4575. # baseline — that capture has to happen before the printer uploads
  4576. # the in-flight MP4 and there is no second chance at it.
  4577. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  4578. async def on_print_running_observed(printer_id: int, data: dict):
  4579. """Restart-recovery for a print that started before Bambuddy came up.
  4580. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  4581. after Bambuddy startup (#1304 guard, prevents duplicate archive
  4582. creation). This hook restores the persisted archive into ``_active_prints``
  4583. and captures the timelapse baseline that normally hangs off print start.
  4584. Fires once per session, in lieu of on_print_start when restart-recovery
  4585. kicks in. The printer doesn't upload the timelapse until after PRINT
  4586. COMPLETE, so a baseline captured any time during the print is still
  4587. pre-upload.
  4588. """
  4589. logger = logging.getLogger(__name__)
  4590. async with async_session() as db:
  4591. from backend.app.models.printer import Printer
  4592. state = printer_manager.get_status(printer_id)
  4593. if state is not None:
  4594. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  4595. if authorization is True:
  4596. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  4597. await _restore_usage_tracking_session(printer_id, state, db, logger)
  4598. await _restore_printable_objects(printer_id, state, db, logger)
  4599. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4600. printer = result.scalar_one_or_none()
  4601. if not printer:
  4602. logger.warning(
  4603. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  4604. printer_id,
  4605. )
  4606. return
  4607. # Avoid double-capture: ownership reconciliation above must still run when
  4608. # a baseline already exists, but the camera work itself is one-shot.
  4609. if printer_id in _timelapse_baselines:
  4610. logger.debug(
  4611. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  4612. printer_id,
  4613. )
  4614. return
  4615. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  4616. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  4617. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  4618. against the printer's current MQTT state.
  4619. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  4620. COMPLETE events, typically a print finishing during an MQTT disconnect
  4621. window followed by a smart-plug power cycle):
  4622. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  4623. provably not running anymore — only branch that should fire under
  4624. normal disconnect-then-reconnect timing.
  4625. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  4626. firmware mints a fresh ``subtask_id`` for each print, including the
  4627. ghost replay it runs after a power cycle from a leftover SD file —
  4628. so a mismatch unambiguously means the in-DB archive is no longer
  4629. the print on the printer.
  4630. 3. Printer is running but ``subtask_name`` is empty. The printer
  4631. doesn't know what it's running; the archive's reference to it is
  4632. already broken.
  4633. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  4634. with matching subtask_id+subtask_name is left alone. The cost of a false
  4635. positive is a duplicate archive on the next real PRINT COMPLETE — the
  4636. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  4637. clears on synthesis, so the real completion creates a fresh row instead
  4638. of overwriting the synthesised one (#1679). The cost of a false negative
  4639. is the ghost-print loop in #1542.
  4640. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  4641. MQTT has connected but the first ``push_status`` response hasn't been
  4642. applied yet — ``PrinterState`` is sitting on its construction defaults.
  4643. The reconcile caller in ``on_printer_status_change`` is already gated
  4644. on a real ``state.state``, so in normal operation this branch is
  4645. unreachable; it's kept as belt-and-braces for future callers and for
  4646. the narrow window where a partial state update could arrive
  4647. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  4648. ``not stale`` on degenerate input is strictly conservative: a real
  4649. stale archive will still be caught by the next push_status arriving
  4650. with terminal state.
  4651. """
  4652. current_state = (state.state or "").upper()
  4653. if current_state in ("", "UNKNOWN"):
  4654. # No real push_status yet — PrinterState defaults are not evidence.
  4655. return False, ""
  4656. if current_state in ("IDLE", "FINISH", "FAILED"):
  4657. return True, f"printer state {current_state}"
  4658. # Below here the printer is in a running / pre-running state (RUNNING /
  4659. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  4660. current_subtask_id = (state.subtask_id or "").strip()
  4661. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  4662. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  4663. current_subtask_name = (state.subtask_name or "").strip()
  4664. if not current_subtask_name:
  4665. return True, "printer subtask_name empty"
  4666. return False, ""
  4667. async def reconcile_stale_active_prints(printer_id: int) -> int:
  4668. """Synthesise ``on_print_complete`` for archives whose print can't be
  4669. running on the printer anymore.
  4670. Called once per MQTT (re)connection (from on_printer_status_change when
  4671. the connected edge flips False → True) and at Bambuddy startup (from
  4672. the FastAPI lifespan). Without this, a print that completes during a
  4673. disconnect window — followed by a smart-plug-driven power cycle — leaves
  4674. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  4675. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  4676. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  4677. power cycle until the operator notices (#1542 follow-up). Reconciliation
  4678. closes the loop by faking the missed PRINT COMPLETE — the existing
  4679. cleanup chain handles SD-file deletion, status updates, usage tracking,
  4680. and notifications.
  4681. Synthesised ``status="aborted"`` is the conservative label: we have no
  4682. proof the print finished successfully (and no progress evidence to
  4683. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  4684. fires later, overwrites the status with the correct value.
  4685. Returns the number of archives reconciled.
  4686. """
  4687. state = printer_manager.get_status(printer_id)
  4688. if not state:
  4689. return 0
  4690. # Don't reconcile while disconnected — we'd be making a decision against
  4691. # stale cached state. The connected → reconcile edge handles this.
  4692. if not state.connected:
  4693. return 0
  4694. from backend.app.models.archive import PrintArchive
  4695. reconciled = 0
  4696. async with async_session() as db:
  4697. result = await db.execute(
  4698. select(PrintArchive).where(
  4699. PrintArchive.printer_id == printer_id,
  4700. PrintArchive.status == "printing",
  4701. )
  4702. )
  4703. active = list(result.scalars().all())
  4704. if not active:
  4705. return 0
  4706. logger = logging.getLogger(__name__)
  4707. for archive in active:
  4708. is_stale, reason = _is_active_archive_stale(archive, state)
  4709. if not is_stale:
  4710. continue
  4711. logger.info(
  4712. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  4713. printer_id,
  4714. archive.id,
  4715. archive.filename,
  4716. reason,
  4717. )
  4718. # Synthesised payload: minimal fields the on_print_complete chain
  4719. # needs. `_reconciled` marker lets downstream code distinguish this
  4720. # from a real MQTT-driven completion if it ever needs to (e.g. for
  4721. # metrics / debug logging). raw_data is the live printer state so
  4722. # the usage tracker can compare end-of-print remain% against the
  4723. # captured start values.
  4724. try:
  4725. await on_print_complete(
  4726. printer_id,
  4727. {
  4728. "status": "aborted",
  4729. "filename": archive.filename,
  4730. "subtask_name": archive.print_name or "",
  4731. "subtask_id": archive.subtask_id or "",
  4732. "raw_data": state.raw_data or {},
  4733. "_reconciled": True,
  4734. },
  4735. )
  4736. reconciled += 1
  4737. except Exception as e:
  4738. # Catch-all: a reconciliation failure must not block the
  4739. # printer's normal status flow. The archive stays in
  4740. # ``status="printing"`` and the next reconnect retries.
  4741. logger.warning(
  4742. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  4743. archive.id,
  4744. e,
  4745. )
  4746. return reconciled
  4747. # #2547: clearance left between the nozzle and the top of the print when the
  4748. # plate is commanded back into camera framing. The nozzle is parked away from
  4749. # the part by then, so this is belt-and-braces against a max_z_height that
  4750. # under-reports (e.g. a slicer that excludes a final Z hop).
  4751. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  4752. # How far below the restored position to drop the plate again afterwards, so
  4753. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  4754. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  4755. # on machines with less headroom.
  4756. _PLATE_PARK_DROP_MM = 100.0
  4757. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  4758. # this axis, so it is a proven-safe speed for the full travel.
  4759. _PLATE_RESTORE_FEEDRATE = 600
  4760. # Time allowed for the plate to reach the restored position before the camera
  4761. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  4762. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  4763. # How long `_background_finish_photo` waits for this producer. Must cover the
  4764. # settle window plus a worst-case RTSP grab (15s), and stay below the
  4765. # notification path's own photo wait so a slow producer degrades to a
  4766. # photo-less notification rather than a missed one.
  4767. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  4768. async def _max_z_for_current_print(printer_id: int, data: dict, logger) -> float | None:
  4769. """Height of the print that just finished on ``printer_id``, or None (#2547).
  4770. This number becomes the target of a real Z move, so every step here refuses
  4771. rather than guesses. A height belonging to some *other* print is the one
  4772. failure that could drive the nozzle into the model: 20 mm carried onto a
  4773. 200 mm print would command the plate up through the part.
  4774. Two independent things therefore have to agree before a height is returned:
  4775. 1. **Identity.** The archive is matched by the finished print's own
  4776. ``subtask_name``, by equality rather than a ``LIKE``, so "Cube" can never
  4777. resolve to "Cube v2". Matching on "most recent archive for this printer"
  4778. is not good enough — ``on_print_complete`` pops the ``_active_prints``
  4779. binding concurrently with us, and a print Bambuddy failed to archive
  4780. would silently resolve to its predecessor.
  4781. 2. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  4782. match the layer count the printer itself reported over MQTT for the print
  4783. that just ended. These come from genuinely different sources, so a
  4784. mismatch means the row is not this print, whatever its name says.
  4785. ``completed`` is accepted alongside ``printing`` only because
  4786. ``on_print_complete`` may already have flipped the status by the time we
  4787. run; the identity check above is what actually selects the row.
  4788. """
  4789. subtask_name = (data.get("subtask_name") or "").strip()
  4790. if not subtask_name:
  4791. # Nothing to identify the print by — refuse rather than fall back to
  4792. # "whatever ran last on this printer".
  4793. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  4794. return None
  4795. try:
  4796. from backend.app.models.archive import PrintArchive
  4797. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  4798. async with async_session() as db:
  4799. result = await db.execute(
  4800. select(PrintArchive)
  4801. .where(
  4802. PrintArchive.printer_id == printer_id,
  4803. PrintArchive.status.in_(("printing", "completed")),
  4804. PrintArchive.deleted_at.is_(None),
  4805. or_(
  4806. PrintArchive.print_name == subtask_name,
  4807. PrintArchive.filename == subtask_name,
  4808. PrintArchive.filename == f"{subtask_name}.3mf",
  4809. PrintArchive.filename == f"{subtask_name}.gcode.3mf",
  4810. ),
  4811. )
  4812. .order_by(PrintArchive.id.desc())
  4813. .limit(1)
  4814. )
  4815. archive = result.scalar_one_or_none()
  4816. if archive is None or not archive.file_path:
  4817. logger.info("[PLATE-RESTORE] printer %s: no archive matches %r — skipping", printer_id, subtask_name)
  4818. return None
  4819. client = printer_manager.get_client(printer_id)
  4820. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  4821. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  4822. logger.warning(
  4823. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  4824. "— refusing to move the plate on a height that may not be this print's",
  4825. printer_id,
  4826. archive.id,
  4827. archive.total_layers,
  4828. reported_layers,
  4829. )
  4830. return None
  4831. path = Path(archive.file_path)
  4832. if not path.is_absolute():
  4833. path = Path(app_settings.data_dir) / path
  4834. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, archive.plate_id or 1)
  4835. except Exception as e:
  4836. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  4837. return None
  4838. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  4839. """Raise the plate back into camera framing before the finish photo (#2547).
  4840. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  4841. the time ``gcode_state`` reaches FINISH the finished print sits far below
  4842. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  4843. This commands an absolute ``G1 Z`` back to just above the last printed
  4844. layer.
  4845. Absolute, not relative, is the whole safety argument. ``max_z_height +
  4846. clearance`` is a height the toolhead was physically at seconds earlier, so
  4847. it is inside the travel limits by construction and leaves the nozzle above
  4848. the part. It is also unambiguous across model families: Z is the
  4849. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  4850. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  4851. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  4852. (#2579).
  4853. Returns True if the move was sent and waited out, False if it was skipped.
  4854. """
  4855. client = printer_manager.get_client(printer_id)
  4856. if client is None:
  4857. return False
  4858. # Re-read state immediately before commanding motion. If the queue has
  4859. # already started the next print, the printer is no longer ours to move.
  4860. state = getattr(client, "state", None)
  4861. if state is None or state.state != "FINISH":
  4862. logger.info(
  4863. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  4864. printer_id,
  4865. getattr(state, "state", "unknown"),
  4866. )
  4867. return False
  4868. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  4869. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  4870. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  4871. return False
  4872. logger.info(
  4873. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  4874. printer_id,
  4875. target_z,
  4876. max_z_height,
  4877. _PLATE_RESTORE_CLEARANCE_MM,
  4878. _PLATE_RESTORE_SETTLE_SECONDS,
  4879. )
  4880. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  4881. return True
  4882. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  4883. """Drop the plate again after the finish photo (#2547).
  4884. Without this the user walks up to a finished print sitting just under the
  4885. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  4886. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  4887. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  4888. print homes anyway.
  4889. """
  4890. client = printer_manager.get_client(printer_id)
  4891. state = getattr(client, "state", None) if client else None
  4892. if client is None or state is None or state.state != "FINISH":
  4893. return
  4894. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  4895. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  4896. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  4897. """True if a queue item is about to take this printer (#2547).
  4898. The scheduler dispatches the next job the moment a print completes, and a
  4899. plate move interleaved with a print start is not a race worth having. The
  4900. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  4901. this window; this closes the head of it.
  4902. """
  4903. try:
  4904. from backend.app.models.print_queue import PrintQueueItem
  4905. async with async_session() as db:
  4906. result = await db.execute(
  4907. select(PrintQueueItem.id)
  4908. .where(
  4909. PrintQueueItem.printer_id == printer_id,
  4910. PrintQueueItem.status.in_(("pending", "printing")),
  4911. )
  4912. .limit(1)
  4913. )
  4914. return result.scalar_one_or_none() is not None
  4915. except Exception as e:
  4916. # Fail closed: if we can't tell, don't move the plate.
  4917. logging.getLogger(__name__).debug(
  4918. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  4919. )
  4920. return True
  4921. async def on_finish_photo_moment(printer_id: int, data: dict):
  4922. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  4923. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  4924. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  4925. fallback for prints that skip stage 22 (cancel, external-spool-only,
  4926. HMS halt, firmware variants). Grabs one frame via the same
  4927. external-camera / RTSP path the post-completion fallback uses, stores
  4928. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  4929. ``_background_finish_photo`` consume the cached bytes when it runs.
  4930. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  4931. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  4932. set to Smooth (#1721). No force-on now means the user's explicit
  4933. timelapse=off in the slicer send dialog is respected.
  4934. """
  4935. logger = logging.getLogger(__name__)
  4936. trigger = data.get("trigger", "unknown")
  4937. timelapse_was_active = bool(data.get("timelapse_was_active"))
  4938. logger.info(
  4939. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  4940. printer_id,
  4941. trigger,
  4942. timelapse_was_active,
  4943. )
  4944. # If a timelapse is actively recording, skip the pre-capture — the
  4945. # post-completion path will extract the last frame from the recorded
  4946. # video, which still provides the best framing (toolhead parked,
  4947. # before bed drop) without the per-layer parking side effects.
  4948. if timelapse_was_active:
  4949. logger.info(
  4950. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  4951. printer_id,
  4952. )
  4953. return
  4954. # #1790: register the producer-done event BEFORE the first await so the
  4955. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  4956. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  4957. # The `finally` below guarantees `set()` runs on every exit, including
  4958. # early returns and exceptions, so the consumer's bounded wait can't hang.
  4959. producer_done = asyncio.Event()
  4960. _stage22_finish_in_flight[printer_id] = producer_done
  4961. # #2547: set once the plate has actually been raised, and read by the
  4962. # `finally` below. Declared out here so a failure anywhere after the move —
  4963. # a camera timeout, a DB error — still lowers the plate again.
  4964. restore_max_z: float | None = None
  4965. try:
  4966. async with async_session() as db:
  4967. from backend.app.api.routes.settings import get_setting
  4968. from backend.app.models.printer import Printer
  4969. capture_setting = await get_setting(db, "capture_finish_photo")
  4970. if capture_setting is not None and capture_setting.lower() != "true":
  4971. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  4972. return
  4973. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  4974. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  4975. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4976. printer = result.scalar_one_or_none()
  4977. if printer is None:
  4978. logger.warning(
  4979. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  4980. printer_id,
  4981. )
  4982. return
  4983. frame_bytes: bytes | None = None
  4984. # #2708: the banked frame arrives already rotated — it comes from
  4985. # `_capture_snapshot_for_notification`, which rotates before returning.
  4986. # Every other source below is a raw grab. Tracking which lets us store
  4987. # exactly one rotation in `_stage22_finish_frames` either way.
  4988. frame_already_rotated = False
  4989. # On the FINISH-state path the End G-code has already run, and two very
  4990. # different situations arrive here needing opposite answers.
  4991. #
  4992. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  4993. # snippet may have ejected the plate — the scene in front of the camera
  4994. # is no longer the finished print, and no amount of moving the plate
  4995. # brings it back. Use the banked in-print frame instead.
  4996. #
  4997. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  4998. # than the camera frames well, and the toolhead is parked out of the
  4999. # way. That is the *best* moment available on firmware that never emits
  5000. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  5001. # back. Preferring the bank here unconditionally, as this code used to,
  5002. # is what shipped a mid-print photo with the toolhead over the part.
  5003. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  5004. banked = _inprint_frame_bank.get(printer_id)
  5005. if banked:
  5006. frame_bytes = banked
  5007. frame_already_rotated = True
  5008. logger.info(
  5009. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  5010. "frame (%d bytes) instead of a post-swap live grab",
  5011. len(banked),
  5012. )
  5013. else:
  5014. logger.warning(
  5015. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  5016. "in-print bank is empty — falling back to a live grab, which may show a "
  5017. "swapped or empty plate",
  5018. printer_id,
  5019. )
  5020. # `restore_max_z` is set only once the plate is actually up, because the
  5021. # `finally` reads it to decide whether it owes a move back down.
  5022. #
  5023. # Never on a print whose End G-code Bambuddy injected, even when the bank
  5024. # came up empty above: that machine may have just ejected its plate, and
  5025. # driving Z into whatever a swap mechanism is doing is not a risk worth
  5026. # taking for a photo of a bed we already know may be bare.
  5027. if (
  5028. frame_bytes is None
  5029. and trigger == "finish_state"
  5030. and restore_plate_enabled
  5031. and not print_dispatch_context.end_gcode_injected(printer_id)
  5032. ):
  5033. wants_restore = await _max_z_for_current_print(printer_id, data, logger)
  5034. if wants_restore is None:
  5035. logger.info(
  5036. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  5037. printer_id,
  5038. )
  5039. elif await _plate_restore_is_blocked_by_queue(printer_id):
  5040. logger.info(
  5041. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  5042. printer_id,
  5043. )
  5044. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  5045. restore_max_z = wants_restore
  5046. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  5047. from backend.app.api.routes.camera import live_frame_for_capture
  5048. from backend.app.services.external_camera import capture_frame
  5049. # #2707: this used to collide with the live view and fail, which is
  5050. # how finish-photo notifications went out with no image attached.
  5051. # Leaving frame_bytes None keeps the rest of the fallback chain.
  5052. defer, buffered = live_frame_for_capture(printer_id)
  5053. if defer:
  5054. frame_bytes = buffered
  5055. else:
  5056. frame_bytes = await capture_frame(
  5057. printer.external_camera_url,
  5058. printer.external_camera_type or "mjpeg",
  5059. snapshot_url=printer.external_camera_snapshot_url,
  5060. )
  5061. if frame_bytes:
  5062. logger.info(
  5063. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  5064. len(frame_bytes),
  5065. )
  5066. elif frame_bytes is None:
  5067. from backend.app.api.routes.camera import get_buffered_frame
  5068. buffered = get_buffered_frame(printer_id)
  5069. if buffered:
  5070. frame_bytes = buffered
  5071. logger.info(
  5072. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  5073. len(frame_bytes),
  5074. )
  5075. else:
  5076. from backend.app.services.camera import capture_camera_frame_bytes
  5077. frame_bytes = await capture_camera_frame_bytes(
  5078. ip_address=printer.ip_address,
  5079. access_code=printer.access_code,
  5080. model=printer.model,
  5081. timeout=15,
  5082. )
  5083. if frame_bytes:
  5084. logger.info(
  5085. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  5086. len(frame_bytes),
  5087. )
  5088. if frame_bytes:
  5089. if not frame_already_rotated:
  5090. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  5091. _stage22_finish_frames[printer_id] = frame_bytes
  5092. else:
  5093. logger.warning(
  5094. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  5095. printer_id,
  5096. )
  5097. except Exception as e:
  5098. logger.warning(
  5099. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  5100. printer_id,
  5101. e,
  5102. )
  5103. finally:
  5104. # #2547: we raised the plate, so we own lowering it — including when the
  5105. # capture above failed or threw partway through.
  5106. if restore_max_z is not None:
  5107. try:
  5108. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  5109. except Exception as e:
  5110. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  5111. # #1790: always unblock the consumer's bounded wait — whether we stored
  5112. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  5113. # dict entry by the consumer doesn't affect signalling.
  5114. producer_done.set()
  5115. def _subtask_name_from_filename(filename: str) -> str:
  5116. """Recover the subtask name a print command would have carried for *filename*.
  5117. The dispatcher derives the printer-facing subtask name from the archive's
  5118. file name, so stripping the extensions back off gives the value MQTT echoes
  5119. on completion. Only the two extensions Bambuddy actually stores are removed,
  5120. and in the order they nest (``.gcode.3mf``), so a model whose own name
  5121. contains a dot -- ``My.Model.3mf`` -- keeps it.
  5122. """
  5123. name = PurePosixPath(filename).name
  5124. for suffix in (".3mf", ".gcode"):
  5125. if name.lower().endswith(suffix):
  5126. name = name[: -len(suffix)]
  5127. return name
  5128. # How the printer marks a subtask name it had to cut short. Observed on real
  5129. # hardware at ~100 characters, but the cut-off is not a fixed character count
  5130. # (a name with multibyte characters came back at 98), so match the marker
  5131. # rather than a length.
  5132. _SUBTASK_TRUNCATION_MARKER = "..."
  5133. def _normalise_subtask_name(name: str) -> str:
  5134. """Canonical form for comparing a dispatched name against MQTT's echo.
  5135. The printer does not echo the name back verbatim: it substitutes
  5136. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  5137. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  5138. The 3MF lookup in this module has always known that -- it builds
  5139. space-to-underscore variants of every candidate filename, and its
  5140. directory search normalises both sides before comparing. This exists so
  5141. the completion check reads the same rule from the same place instead of
  5142. growing its own, which is exactly how it came to disagree (#2829).
  5143. """
  5144. return name.strip().replace(" ", "_").casefold()
  5145. def _subtask_names_match(expected: str, observed: str) -> bool:
  5146. """Whether two subtask names describe the same print.
  5147. Beyond the space/underscore substitution, the printer truncates long names
  5148. and marks the cut with ``...``. A truncated echo has to count as a match or
  5149. every print with a long name strands its queue item the same way.
  5150. """
  5151. expected_n = _normalise_subtask_name(expected)
  5152. observed_n = _normalise_subtask_name(observed)
  5153. if expected_n == observed_n:
  5154. return True
  5155. # Either side can be the truncated one: the printer truncates what it
  5156. # echoes, and an archive whose own filename was recorded from a previous
  5157. # truncated echo carries the marker too.
  5158. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  5159. if cut.endswith(_SUBTASK_TRUNCATION_MARKER) and full.startswith(cut[: -len(_SUBTASK_TRUNCATION_MARKER)]):
  5160. return True
  5161. return False
  5162. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  5163. """Whether this completion event is plausibly about *item*'s print.
  5164. The caller finds its queue row by printer and ``status='printing'`` alone,
  5165. which is all a completion event gives it -- there is no run identifier in
  5166. the MQTT payload to match on. That makes the lookup indiscriminate: any
  5167. completion delivered for this printer closes whichever row happens to be
  5168. printing, however unrelated. Comparing the subtask name against the archive
  5169. the row was dispatched with costs one primary-key load and rules that out.
  5170. Deliberately permissive: it answers False only on a positive disagreement
  5171. between two names we actually have. A row with no archive, an archive with
  5172. no file name, or an event with no subtask name is unverifiable rather than
  5173. wrong, and refusing those would strand the item in ``printing`` and wedge
  5174. the printer's queue -- a worse failure than the one being prevented.
  5175. """
  5176. observed = (data.get("subtask_name") or "").strip()
  5177. if not observed or item.archive_id is None:
  5178. return True
  5179. from backend.app.models.archive import PrintArchive
  5180. archive = await db.get(PrintArchive, item.archive_id)
  5181. if archive is None or not archive.filename:
  5182. return True
  5183. expected = _subtask_name_from_filename(archive.filename)
  5184. if not expected or _subtask_names_match(expected, observed):
  5185. return True
  5186. logging.getLogger(__name__).warning(
  5187. "Ignoring print completion for queue item %s: it was dispatched as %r "
  5188. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  5189. "printing rather than closing a run this event is not about.",
  5190. item.id,
  5191. expected,
  5192. archive.id,
  5193. archive.filename,
  5194. observed,
  5195. )
  5196. return False
  5197. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  5198. """Spend the 3MF download cache on a still-empty fallback archive.
  5199. ``on_print_complete`` drops the cache as its first act, which deletes the
  5200. file. If the cover endpoint (or anything else) pulled the 3MF while the
  5201. print ran and the archive never got one, this is the last moment those bytes
  5202. exist (#2957).
  5203. """
  5204. logger = logging.getLogger(__name__)
  5205. names = [
  5206. n
  5207. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  5208. if n
  5209. ]
  5210. for name in names:
  5211. try:
  5212. cached = get_cached_3mf(printer_id, name)
  5213. if cached and await try_recover_fallback_archive(printer_id, name, cached):
  5214. return
  5215. except Exception as e:
  5216. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  5217. async def on_print_complete(printer_id: int, data: dict):
  5218. """Handle print completion - update the archive status."""
  5219. import time
  5220. logger = logging.getLogger(__name__)
  5221. start_time = time.time()
  5222. def log_timing(section: str):
  5223. elapsed = time.time() - start_time
  5224. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  5225. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  5226. # A kill-switch stop sends its provider notification immediately. Keep the
  5227. # task so the later notification path can await it and avoid a duplicate;
  5228. # if that immediate attempt failed, the regular completion path retries.
  5229. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  5230. # Last chance before the bytes go: if this print's archive is still an empty
  5231. # fallback and something downloaded the 3MF while it ran, fill the archive in
  5232. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  5233. # below deletes the file (#2957).
  5234. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  5235. # A pending cool-off retry has nothing left to recover for — the cache is
  5236. # about to be dropped and the print is over.
  5237. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  5238. if retry_task and not retry_task.done():
  5239. retry_task.cancel()
  5240. # Drop the 3MF download cache for this printer (#972). The print is over,
  5241. # nothing else legitimately needs the bytes; keeping them would only risk
  5242. # handing a stale file to the next print if it reuses the same name.
  5243. clear_3mf_cache(printer_id)
  5244. try:
  5245. ws_data = {
  5246. "status": data.get("status"),
  5247. "filename": data.get("filename"),
  5248. "subtask_name": data.get("subtask_name"),
  5249. "timelapse_was_active": data.get("timelapse_was_active"),
  5250. }
  5251. await ws_manager.send_print_complete(printer_id, ws_data)
  5252. log_timing("WebSocket send_print_complete")
  5253. except Exception as e:
  5254. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  5255. # Capture user info before clearing (needed for print log entry)
  5256. _print_user_info = printer_manager.get_current_print_user(printer_id)
  5257. # Clear current print user tracking (Issue #206)
  5258. printer_manager.clear_current_print_user(printer_id)
  5259. # If the user explicitly stopped this print from the queue UI the printer will
  5260. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  5261. # correct "print stopped" notification/email is sent instead of a failure alert.
  5262. _raw_status = data.get("status", "completed")
  5263. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  5264. logger.info(
  5265. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  5266. _raw_status,
  5267. printer_id,
  5268. )
  5269. data = {**data, "status": "cancelled"}
  5270. _user_stopped_printers.discard(printer_id)
  5271. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  5272. # may have left material on the bed: a user can cancel ten hours into a
  5273. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  5274. # touchscreen-stop reports `aborted` rather than `cancelled` because
  5275. # `_user_stopped_printers` is only populated when the user stops via the
  5276. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  5277. # which auto-dispatched the next queued print onto a fouled bed two seconds
  5278. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  5279. # Auto Off power cycles and Bambuddy restarts.
  5280. _final_status = data.get("status", "completed")
  5281. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  5282. printer_manager.set_awaiting_plate_clear(printer_id, True)
  5283. # MQTT relay - publish print complete
  5284. try:
  5285. printer_info = printer_manager.get_printer(printer_id)
  5286. if printer_info:
  5287. await mqtt_relay.on_print_complete(
  5288. printer_id,
  5289. printer_info.name,
  5290. printer_info.serial_number,
  5291. data.get("filename", ""),
  5292. data.get("subtask_name", ""),
  5293. data.get("status", "completed"),
  5294. )
  5295. except Exception:
  5296. pass # Don't fail print complete callback if MQTT fails
  5297. filename = data.get("filename", "")
  5298. subtask_name = data.get("subtask_name", "")
  5299. if not filename and not subtask_name:
  5300. logger.warning("Print complete without filename or subtask_name")
  5301. return
  5302. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  5303. # Build list of possible keys to try (matching how they were registered in on_print_start)
  5304. possible_keys = []
  5305. # Try subtask_name variations first (most reliable for matching)
  5306. if subtask_name:
  5307. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  5308. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  5309. possible_keys.append((printer_id, subtask_name))
  5310. # Try filename variations
  5311. if filename:
  5312. # Extract just the filename if it's a path
  5313. fname = filename.split("/")[-1] if "/" in filename else filename
  5314. if fname.endswith(".3mf"):
  5315. possible_keys.append((printer_id, fname))
  5316. elif fname.endswith(".gcode"):
  5317. base_name = fname.rsplit(".", 1)[0]
  5318. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  5319. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5320. possible_keys.append((printer_id, fname))
  5321. else:
  5322. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  5323. possible_keys.append((printer_id, f"{fname}.3mf"))
  5324. possible_keys.append((printer_id, fname))
  5325. # Also try full path versions
  5326. if filename.endswith(".3mf"):
  5327. possible_keys.append((printer_id, filename))
  5328. elif filename.endswith(".gcode"):
  5329. base_name = filename.rsplit(".", 1)[0]
  5330. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5331. possible_keys.append((printer_id, filename))
  5332. else:
  5333. possible_keys.append((printer_id, f"{filename}.3mf"))
  5334. possible_keys.append((printer_id, filename))
  5335. # Find the archive for this print
  5336. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  5337. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  5338. archive_id = None
  5339. for key in possible_keys:
  5340. archive_id = _active_prints.pop(key, None)
  5341. if archive_id:
  5342. logger.info("Found archive %s with key %s", archive_id, key)
  5343. # Also clean up any other keys pointing to this archive
  5344. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  5345. for k in keys_to_remove:
  5346. _active_prints.pop(k, None)
  5347. break
  5348. if not archive_id:
  5349. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  5350. async with async_session() as db:
  5351. from backend.app.models.archive import PrintArchive
  5352. # Try matching by subtask_name (stored as print_name) first
  5353. if subtask_name:
  5354. result = await db.execute(
  5355. select(PrintArchive)
  5356. .where(PrintArchive.printer_id == printer_id)
  5357. .where(PrintArchive.status == "printing")
  5358. .where(
  5359. or_(
  5360. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  5361. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  5362. )
  5363. )
  5364. .order_by(PrintArchive.created_at.desc())
  5365. .limit(1)
  5366. )
  5367. archive = result.scalar_one_or_none()
  5368. if archive:
  5369. archive_id = archive.id
  5370. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  5371. # Also try by filename
  5372. if not archive_id and filename:
  5373. result = await db.execute(
  5374. select(PrintArchive)
  5375. .where(PrintArchive.printer_id == printer_id)
  5376. .where(PrintArchive.filename == filename)
  5377. .where(PrintArchive.status == "printing")
  5378. .order_by(PrintArchive.created_at.desc())
  5379. .limit(1)
  5380. )
  5381. archive = result.scalar_one_or_none()
  5382. if archive:
  5383. archive_id = archive.id
  5384. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  5385. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  5386. # auto-start files found in root on power cycle, causing ghost prints.
  5387. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  5388. try:
  5389. if subtask_name:
  5390. archive_filename: str | None = None
  5391. async with async_session() as db:
  5392. from backend.app.models.archive import PrintArchive
  5393. from backend.app.models.printer import Printer
  5394. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5395. printer = result.scalar_one_or_none()
  5396. if archive_id:
  5397. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  5398. archive_filename = archive_row.scalar_one_or_none()
  5399. if printer:
  5400. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  5401. from backend.app.utils.filename import derive_remote_filename
  5402. # Primary candidate: the exact path the dispatcher uploaded to
  5403. # (derived from archive.filename via the same rule as upload).
  5404. # Without it, a library row that ended up with a doubled
  5405. # .gcode.3mf (#1542) leaves the real file behind because the
  5406. # subtask_name + ext fallbacks below don't match what's on the
  5407. # SD card. Fallbacks remain for archive-less prints (subtask
  5408. # never resolved to an archive) and for older naming variants.
  5409. candidate_paths: list[str] = []
  5410. if archive_filename:
  5411. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  5412. for ext in (".3mf", ".gcode"):
  5413. fallback = f"/{subtask_name}{ext}"
  5414. if fallback not in candidate_paths:
  5415. candidate_paths.append(fallback)
  5416. # Three outcomes track across all candidates so the final log
  5417. # line reflects what actually happened. The A1 in #1721 always
  5418. # ends here with ``any_not_found=True`` and the others False
  5419. # — its firmware auto-cleans the SD card before our cleanup
  5420. # runs, every candidate FTP-DELE returns 550, and the old
  5421. # code burned 3 retries × 2 s × 3 candidates per print
  5422. # logging a misleading "may linger" WARNING on a successful
  5423. # print.
  5424. any_deleted = False
  5425. any_real_failure = False
  5426. any_not_found = False
  5427. for remote_path in candidate_paths:
  5428. # Retry only the FAILED case — 550 NOT_FOUND will never
  5429. # recover by waiting, so a "file isn't here" answer
  5430. # advances immediately to the next candidate without
  5431. # consuming the retry budget.
  5432. for attempt in range(1, 4):
  5433. try:
  5434. delete_result = await delete_file_async(
  5435. printer.ip_address,
  5436. printer.access_code,
  5437. remote_path,
  5438. printer_model=printer.model,
  5439. )
  5440. except Exception as e:
  5441. delete_result = DeleteResult.FAILED
  5442. logger.warning(
  5443. "SD card cleanup attempt %d/3 raised for %s: %s",
  5444. attempt,
  5445. remote_path,
  5446. e,
  5447. )
  5448. if delete_result == DeleteResult.DELETED:
  5449. any_deleted = True
  5450. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  5451. break
  5452. if delete_result == DeleteResult.NOT_FOUND:
  5453. any_not_found = True
  5454. break # 550 will not recover; try next candidate
  5455. # FAILED: real error — retry with backoff, then give up
  5456. if attempt < 3:
  5457. await asyncio.sleep(2)
  5458. else:
  5459. any_real_failure = True
  5460. logger.warning(
  5461. "SD card cleanup failed after 3 attempts for %s "
  5462. "(network/auth/transient error — file may linger on SD card)",
  5463. remote_path,
  5464. )
  5465. if not any_deleted and not any_real_failure and any_not_found:
  5466. # Every candidate said "not here." Either the printer
  5467. # firmware swept the SD card itself (common on A1) or the
  5468. # dispatcher's upload path doesn't match our candidate
  5469. # rule. Either way: nothing to clean up, no warning.
  5470. logger.debug(
  5471. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  5472. "(printer likely self-cleaned)",
  5473. printer.name,
  5474. )
  5475. except Exception as e:
  5476. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  5477. log_timing("SD card cleanup")
  5478. # Update queue item status early — must run before the archive_id early-return
  5479. # so queue items don't get stuck in "printing" when archive lookup fails.
  5480. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  5481. queue_item_id = None
  5482. billing_run_id: str | None = None
  5483. billing_user_id: int | None = None
  5484. billing_cost_center_id: int | None = None
  5485. billing_plate_id: int | None = None
  5486. queue_status = None
  5487. queue_auto_off = False
  5488. try:
  5489. from backend.app.core.database import run_with_retry
  5490. from backend.app.models.print_queue import PrintQueueItem
  5491. async def _update_queue_status(db):
  5492. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  5493. nonlocal queue_item_id, queue_status, queue_auto_off
  5494. result = await db.execute(
  5495. select(PrintQueueItem)
  5496. .where(PrintQueueItem.printer_id == printer_id)
  5497. .where(PrintQueueItem.status == "printing")
  5498. )
  5499. printing_items = list(result.scalars().all())
  5500. if len(printing_items) > 1:
  5501. logger.warning(
  5502. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  5503. printer_id,
  5504. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  5505. )
  5506. item = printing_items[0] if printing_items else None
  5507. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  5508. return
  5509. if item:
  5510. queue_status = data.get("status", "completed")
  5511. # MQTT sends "aborted" for cancelled prints; normalise to
  5512. # "cancelled" so it matches the queue schema Literal.
  5513. if queue_status == "aborted":
  5514. queue_status = "cancelled"
  5515. item.status = queue_status
  5516. item.completed_at = datetime.now(timezone.utc)
  5517. if queue_status == "failed" and not item.error_message:
  5518. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  5519. # Bump usage counters on the source library file so admins can
  5520. # sort by "last printed" and (eventually) auto-purge stale
  5521. # files — #1008.
  5522. await _bump_library_file_usage_if_completed(db, item, queue_status)
  5523. await db.commit()
  5524. queue_item_id = item.id
  5525. billing_run_id = item.billing_run_id
  5526. billing_user_id = item.created_by_id
  5527. billing_cost_center_id = item.cost_center_id
  5528. billing_plate_id = item.plate_id
  5529. queue_auto_off = item.auto_off_after
  5530. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  5531. await run_with_retry(_update_queue_status, label="queue status update")
  5532. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  5533. # their own sessions and have their own error handling — no retry needed.
  5534. if queue_item_id is not None:
  5535. # Batch orders (#342): this run may have been the last one an order
  5536. # owed. Re-evaluate here rather than lazily on read, so a finished
  5537. # order reports itself complete without someone opening the page.
  5538. try:
  5539. from backend.app.services.print_batch import refresh_batch_status_for_item
  5540. async with async_session() as db:
  5541. await refresh_batch_status_for_item(db, queue_item_id)
  5542. await db.commit()
  5543. except Exception as e:
  5544. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  5545. # MQTT relay - publish queue job completed
  5546. try:
  5547. printer_info = printer_manager.get_printer(printer_id)
  5548. await mqtt_relay.on_queue_job_completed(
  5549. job_id=queue_item_id,
  5550. filename=filename or subtask_name,
  5551. printer_id=printer_id,
  5552. printer_name=printer_info.name if printer_info else "Unknown",
  5553. status=queue_status,
  5554. )
  5555. except Exception:
  5556. pass # Don't fail if MQTT fails
  5557. # Check if queue is now empty and send notification
  5558. try:
  5559. from sqlalchemy import func as sa_func
  5560. async with async_session() as db:
  5561. count_result = await db.execute(
  5562. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  5563. )
  5564. pending_count = count_result.scalar() or 0
  5565. if pending_count == 0:
  5566. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  5567. completed_result = await db.execute(
  5568. select(sa_func.count(PrintQueueItem.id)).where(
  5569. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  5570. PrintQueueItem.completed_at >= today_start,
  5571. )
  5572. )
  5573. completed_count = completed_result.scalar() or 1
  5574. await notification_service.on_queue_completed(
  5575. completed_count=completed_count,
  5576. db=db,
  5577. )
  5578. except Exception:
  5579. pass # Don't fail if notification fails
  5580. # Handle auto_off_after - power off printer if the queue item opted
  5581. # in. Delegates to the smart-plug manager so the off honours each
  5582. # plug's configured strategy (time delay or temperature threshold),
  5583. # is cancelled if the printer starts printing again, and never cuts
  5584. # power on a loaded print (#1890). Previously an inline block here
  5585. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  5586. # timeout regardless of print state — cutting a touchscreen reprint.
  5587. if queue_auto_off:
  5588. try:
  5589. async with async_session() as db:
  5590. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  5591. except Exception as e:
  5592. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  5593. except Exception as e:
  5594. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  5595. log_timing("Queue item update")
  5596. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  5597. # Must run before archive_id early-return so it fires for all prints (including
  5598. # prints started from BambuStudio/touchscreen that have no archive).
  5599. if data.get("status") == "completed":
  5600. try:
  5601. from backend.app.api.routes.settings import get_setting
  5602. async with async_session() as db:
  5603. threshold_str = await get_setting(db, "bed_cooled_threshold")
  5604. threshold = float(threshold_str) if threshold_str else 35.0
  5605. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  5606. async with async_session() as db:
  5607. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  5608. if providers:
  5609. _bed_cool_waiters[printer_id] = {
  5610. "threshold": threshold,
  5611. "filename": filename or subtask_name or "",
  5612. "registered_at": time.time(),
  5613. }
  5614. logger.info(
  5615. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  5616. printer_id,
  5617. threshold,
  5618. )
  5619. else:
  5620. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  5621. except Exception as e:
  5622. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  5623. # Capture the slicer estimate before usage tracking runs. The tracker may
  5624. # update archive.cost with this run's measured cost; billing partial runs
  5625. # against that already-partial value would discount the charge twice.
  5626. billing_planned_grams: float | None = None
  5627. billing_base_cost: float | None = None
  5628. if archive_id:
  5629. try:
  5630. async with async_session() as db:
  5631. from backend.app.models.archive import PrintArchive
  5632. billing_archive = await db.get(PrintArchive, archive_id)
  5633. if billing_archive:
  5634. billing_path = (
  5635. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  5636. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  5637. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  5638. billing_archive,
  5639. billing_path,
  5640. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  5641. )
  5642. except Exception as e:
  5643. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  5644. # --- Track filament consumption (must run before archive_id early-return so usage
  5645. # is recorded even when auto-archive is disabled) ---
  5646. usage_results: list[dict] = []
  5647. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  5648. stored_ams_mapping = data.get("ams_mapping")
  5649. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  5650. if not stored_ams_mapping and archive_id:
  5651. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  5652. # Always drain the plate_id register on completion — the session already
  5653. # consumed it at print-start injection; leaving it would leak into the next
  5654. # print on the same archive_id (rare but possible with reprints) (#1697).
  5655. # Capture the popped value so the completion notification can scope the
  5656. # archive-level (summed-across-plates per #1593) filament + time totals
  5657. # down to the single plate that was actually printed (#1785).
  5658. notify_plate_id: int | None = None
  5659. if archive_id:
  5660. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  5661. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  5662. try:
  5663. async with async_session() as db:
  5664. from backend.app.api.routes.settings import get_setting
  5665. _spoolman_on = await get_setting(db, "spoolman_enabled")
  5666. if not _spoolman_on or _spoolman_on.lower() != "true":
  5667. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  5668. async with async_session() as db:
  5669. usage_results = await usage_on_print_complete(
  5670. printer_id,
  5671. data,
  5672. printer_manager,
  5673. db,
  5674. archive_id=archive_id,
  5675. ams_mapping=stored_ams_mapping,
  5676. )
  5677. if usage_results:
  5678. await ws_manager.broadcast(
  5679. {
  5680. "type": "spool_usage_logged",
  5681. "printer_id": printer_id,
  5682. "usage": usage_results,
  5683. }
  5684. )
  5685. log_timing("Usage tracker")
  5686. except Exception as e:
  5687. logger.warning("Usage tracker on_print_complete failed: %s", e)
  5688. # Drop the print-start context unconditionally — the Spoolman branch above
  5689. # skips the internal tracker entirely, so nothing else would clear what
  5690. # print start captured, and a row surviving its print would be restored
  5691. # onto the next one after a restart.
  5692. try:
  5693. from backend.app.services.usage_tracker import discard_session
  5694. async with async_session() as db:
  5695. await discard_session(db, printer_id)
  5696. except Exception as e:
  5697. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  5698. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  5699. if archive_id:
  5700. if data.get("status") == "completed":
  5701. try:
  5702. await _report_spoolman_usage(printer_id, archive_id)
  5703. log_timing("Spoolman usage report")
  5704. except Exception as e:
  5705. logger.warning("Spoolman usage reporting failed: %s", e)
  5706. else:
  5707. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  5708. try:
  5709. async with async_session() as db:
  5710. await _cleanup_spoolman_tracking(
  5711. printer_id,
  5712. archive_id,
  5713. db,
  5714. last_layer_num=data.get("last_layer_num"),
  5715. last_progress=data.get("last_progress"),
  5716. )
  5717. except Exception as e:
  5718. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  5719. log_timing("Filament usage tracking")
  5720. if not archive_id:
  5721. # The printer's own calibration run has no archive by design, so this
  5722. # arrives here every time one finishes. Returning before the no-archive
  5723. # notification is not just noise control: that path attributes an
  5724. # unmatched completion to any queue item this printer finished in the
  5725. # last five minutes, which for a calibration that runs alongside a real
  5726. # print means emailing its owner that their print is done, twice and
  5727. # early. Everything above this point has already run — the plate-clear
  5728. # gate, the queue reconciliation, the SD-card cleanup — so only the
  5729. # notification is skipped.
  5730. if is_internal_printer_job(filename, subtask_name):
  5731. logger.info(
  5732. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  5733. filename,
  5734. subtask_name,
  5735. )
  5736. return
  5737. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  5738. # Still send print-complete/failed/stopped notifications even without an archive.
  5739. # Try to enrich with queue/library-file data so user-specific emails work too.
  5740. async def _notify_no_archive():
  5741. try:
  5742. async with async_session() as db:
  5743. from backend.app.models.library import LibraryFile
  5744. from backend.app.models.print_queue import PrintQueueItem
  5745. from backend.app.models.printer import Printer
  5746. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5747. printer_obj = result.scalar_one_or_none()
  5748. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  5749. # Try to find the most-recent queue item for this printer so we can
  5750. # recover created_by_id and estimated print time.
  5751. # NOTE: By the time this task runs the queue item status has already
  5752. # been updated to a terminal state (completed/failed/cancelled), so
  5753. # we look for recently-completed items (within the last 5 minutes).
  5754. no_archive_data: dict | None = None
  5755. try:
  5756. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  5757. q_result = await db.execute(
  5758. select(PrintQueueItem)
  5759. .where(PrintQueueItem.printer_id == printer_id)
  5760. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  5761. .where(PrintQueueItem.completed_at >= cutoff)
  5762. .order_by(PrintQueueItem.completed_at.desc())
  5763. .limit(1)
  5764. )
  5765. queue_item = q_result.scalar_one_or_none()
  5766. if queue_item:
  5767. no_archive_data = {"created_by_id": queue_item.created_by_id}
  5768. # Pull estimated time from library file when available
  5769. if queue_item.library_file_id:
  5770. lib_result = await db.execute(
  5771. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  5772. )
  5773. lib_file = lib_result.scalar_one_or_none()
  5774. if lib_file and lib_file.print_time_seconds:
  5775. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  5776. except Exception as lookup_err:
  5777. logger.debug(
  5778. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  5779. )
  5780. # Enrich with usage tracker results (captured in enclosing scope)
  5781. if usage_results:
  5782. if no_archive_data is None:
  5783. no_archive_data = {}
  5784. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  5785. if total_from_usage > 0:
  5786. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  5787. no_archive_data["usage_results"] = usage_results
  5788. # Try MQTT remaining_time for print duration when no queue/library data
  5789. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  5790. mqtt_remaining = data.get("remaining_time")
  5791. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5792. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  5793. ps = data.get("status", "completed")
  5794. logger.info(
  5795. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  5796. )
  5797. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  5798. await notification_service.on_print_complete(
  5799. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  5800. )
  5801. else:
  5802. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  5803. # Send user-specific email if we have a created_by_id
  5804. if no_archive_data and no_archive_data.get("created_by_id"):
  5805. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  5806. await _dispatch_user_print_email(
  5807. ps,
  5808. no_archive_data["created_by_id"],
  5809. p_name,
  5810. raw_filename,
  5811. db,
  5812. )
  5813. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  5814. except Exception as e:
  5815. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  5816. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  5817. return
  5818. log_timing("Archive lookup")
  5819. # Update archive status
  5820. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  5821. try:
  5822. async with async_session() as db:
  5823. service = ArchiveService(db)
  5824. status = data.get("status", "completed")
  5825. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  5826. if hms_errors:
  5827. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  5828. failure_reason = derive_failure_reason(status, hms_errors)
  5829. if data.get("_reconciled"):
  5830. # A reconciled completion closes out a stale archive at
  5831. # reconnect — it is not a user action, so don't mislabel it
  5832. # "User cancelled". The "Stale" prefix matches the existing
  5833. # stale-cleanup convention and records that the real end time
  5834. # is unknown, which is also why its logged duration is 0 (#2592).
  5835. failure_reason = "Stale - reconciled after reconnect, end time unknown"
  5836. if failure_reason:
  5837. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  5838. elif status == "failed" and hms_errors:
  5839. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  5840. await service.update_archive_status(
  5841. archive_id,
  5842. status=status,
  5843. completed_at=(
  5844. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  5845. ),
  5846. failure_reason=failure_reason,
  5847. )
  5848. logger.info(
  5849. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  5850. )
  5851. await ws_manager.send_archive_updated(
  5852. {
  5853. "id": archive_id,
  5854. "status": status,
  5855. }
  5856. )
  5857. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  5858. # MQTT relay - publish archive updated
  5859. try:
  5860. await mqtt_relay.on_archive_updated(
  5861. archive_id=archive_id,
  5862. print_name=filename or subtask_name,
  5863. status=status,
  5864. )
  5865. except Exception:
  5866. pass # Don't fail if MQTT fails
  5867. except Exception as e:
  5868. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  5869. # Continue with other operations even if archive update fails
  5870. log_timing("Archive status update")
  5871. # Apply finance wallet charge or release reservations once. For all partial
  5872. # terminal states (failed, aborted at the printer display, or cancelled via
  5873. # Bambuddy) use this run's measured spool delta, falling back to the last
  5874. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  5875. # estimate and therefore cannot represent an interrupted run.
  5876. try:
  5877. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  5878. async with async_session() as db:
  5879. from backend.app.models.archive import PrintArchive
  5880. from backend.app.services.finance_billing import apply_print_charge_for_archive
  5881. archive = await db.get(PrintArchive, archive_id)
  5882. if archive and billing_run_id is None:
  5883. billing_run_id = getattr(archive, "billing_run_id", None)
  5884. if archive and archive.created_by_id is None and _print_user_info:
  5885. archive.created_by_id = _print_user_info.get("user_id")
  5886. await db.flush()
  5887. run_status = data.get("status", "completed")
  5888. last_progress = data.get("last_progress")
  5889. if last_progress is None:
  5890. last_progress = data.get("progress")
  5891. actual_run_grams = _compute_run_filament_grams(
  5892. run_status,
  5893. billing_planned_grams,
  5894. last_progress,
  5895. usage_results,
  5896. )
  5897. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  5898. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  5899. charged = await apply_print_charge_for_archive(
  5900. db,
  5901. archive_id,
  5902. charged_user_id=billing_user_id,
  5903. cost_center_id=(
  5904. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  5905. ),
  5906. print_queue_id=queue_item_id,
  5907. print_run_id=billing_run_id,
  5908. base_cost_override=billing_base_cost,
  5909. filament_usage=filament_usage,
  5910. )
  5911. await db.commit()
  5912. if charged:
  5913. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  5914. except Exception as e:
  5915. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  5916. printer_info = printer_manager.get_printer(printer_id)
  5917. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  5918. billing_filename = filename or subtask_name or "Unknown"
  5919. billing_error = str(e)
  5920. try:
  5921. await ws_manager.broadcast(
  5922. {
  5923. "type": "billing_charge_failed",
  5924. "printer_id": printer_id,
  5925. "printer_name": billing_printer_name,
  5926. "filename": billing_filename,
  5927. "archive_id": archive_id,
  5928. }
  5929. )
  5930. except Exception as notification_error:
  5931. logger.error(
  5932. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  5933. archive_id,
  5934. notification_error,
  5935. )
  5936. async def _notify_billing_charge_failed() -> None:
  5937. try:
  5938. async with async_session() as notification_db:
  5939. await notification_service.on_billing_charge_failed(
  5940. printer_id,
  5941. billing_printer_name,
  5942. billing_filename,
  5943. archive_id,
  5944. billing_error,
  5945. notification_db,
  5946. )
  5947. except Exception as provider_error:
  5948. logger.error(
  5949. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  5950. archive_id,
  5951. provider_error,
  5952. exc_info=True,
  5953. )
  5954. spawn_background_task(
  5955. _notify_billing_charge_failed(),
  5956. name=f"billing-charge-failed-{archive_id}",
  5957. )
  5958. log_timing("Finance charge update")
  5959. # Write independent print log entry (separate table, never touches archives)
  5960. try:
  5961. async with async_session() as db:
  5962. from backend.app.models.archive import PrintArchive
  5963. from backend.app.services.print_log import write_log_entry
  5964. archive = await db.get(PrintArchive, archive_id)
  5965. if archive:
  5966. # Back-fill created_by_id on reprint (#730): reprint reuses the
  5967. # source archive row rather than creating a new one, so an
  5968. # archive that was auto-created from a printer-initiated
  5969. # print (created_by_id=NULL) would otherwise stay unattributed
  5970. # forever. When we have a print-session user AND the archive
  5971. # has no attribution yet, credit the current user. Never
  5972. # overwrite an existing attribution — the original uploader
  5973. # keeps ownership.
  5974. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  5975. if archive.created_by_id is None and _print_user_id is not None:
  5976. archive.created_by_id = _print_user_id
  5977. p_info = printer_manager.get_printer(printer_id)
  5978. # Per-run actuals — written to PrintLogEntry so stats reflect
  5979. # what THIS print actually used, not the source archive's
  5980. # first-run values (#1378). Helper handles the partial-print
  5981. # math (failed / cancelled / stopped get scaled to progress
  5982. # or to tracked spool deltas).
  5983. _run_status = data.get("status", "completed")
  5984. # #2614: scope the per-run estimate to the printed plate. For a
  5985. # multi-plate 3MF dispatched one plate at a time, the archive's
  5986. # filament/cost are the whole-file totals; the PrintLogEntry must
  5987. # reflect only this plate. No effect on single-plate archives (the
  5988. # plate estimate equals the whole-file value) or on the tracker
  5989. # path (measured spool deltas win in _compute_run_filament_grams).
  5990. _est_full_path = (
  5991. app_settings.base_dir / archive.file_path if archive.file_path else None
  5992. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  5993. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path)
  5994. _run_grams = _compute_run_filament_grams(
  5995. _run_status,
  5996. _est_grams,
  5997. data.get("last_progress", data.get("progress")),
  5998. usage_results,
  5999. )
  6000. # Per-run cost — prefer usage_results sum. For partial prints
  6001. # we deliberately skip the topup-to-estimate logic in
  6002. # usage_tracker (which assumes the print completed); the raw
  6003. # tracked-spool sum is closer to what THIS run actually cost.
  6004. _run_cost: float | None = None
  6005. if usage_results:
  6006. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  6007. if _run_cost is None and _run_status == "completed":
  6008. _run_cost = _est_cost
  6009. await write_log_entry(
  6010. db,
  6011. archive_id=archive.id,
  6012. # Captured by _update_queue_status above; None for
  6013. # printer-initiated prints with no queue row. Batch
  6014. # cost/energy roll-up joins on it (#342).
  6015. queue_item_id=queue_item_id,
  6016. status=_run_status,
  6017. print_name=archive.print_name,
  6018. printer_name=p_info.name if p_info else None,
  6019. printer_id=printer_id,
  6020. started_at=archive.started_at,
  6021. completed_at=archive.completed_at,
  6022. filament_type=archive.filament_type,
  6023. filament_color=archive.filament_color,
  6024. filament_used_grams=_run_grams,
  6025. cost=_run_cost,
  6026. failure_reason=archive.failure_reason,
  6027. thumbnail_path=archive.thumbnail_path,
  6028. created_by_id=archive.created_by_id,
  6029. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  6030. # Reconciled completions have an unknown real end time —
  6031. # log 0 duration instead of the whole disconnect gap (#2592).
  6032. reconciled=bool(data.get("_reconciled")),
  6033. )
  6034. await db.commit()
  6035. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  6036. except Exception as e:
  6037. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  6038. log_timing("Print log entry")
  6039. # Run slow operations as background tasks to avoid blocking the event loop
  6040. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  6041. async def _background_energy_calculation():
  6042. """Calculate and save energy usage in background.
  6043. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  6044. backend restart no longer loses per-print energy data).
  6045. """
  6046. try:
  6047. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  6048. async with async_session() as db:
  6049. from backend.app.models.archive import PrintArchive
  6050. archive = await db.get(PrintArchive, archive_id)
  6051. if archive is None:
  6052. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  6053. return
  6054. starting_kwh = archive.energy_start_kwh
  6055. if starting_kwh is None:
  6056. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  6057. return
  6058. candidates = await energy_plug_candidates(db, printer_id)
  6059. if not candidates:
  6060. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  6061. return
  6062. # Same ordering as the start reading, so the delta below is
  6063. # against the counter that produced `starting_kwh` (#2859).
  6064. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  6065. if selected is None:
  6066. logger.warning(
  6067. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  6068. printer_id,
  6069. ", ".join(plug.name for plug in candidates),
  6070. )
  6071. return
  6072. plug, energy = selected
  6073. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  6074. energy_used = round(energy["total"] - starting_kwh, 4)
  6075. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  6076. if energy_used < 0:
  6077. logger.warning(
  6078. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  6079. archive_id,
  6080. starting_kwh,
  6081. energy["total"],
  6082. )
  6083. return
  6084. from backend.app.api.routes.settings import get_setting
  6085. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  6086. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  6087. energy_cost_value = round(energy_used * cost_per_kwh, 3)
  6088. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  6089. # reprint doesn't visually clobber the source archive's energy data
  6090. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  6091. from sqlalchemy import func
  6092. from backend.app.models.print_log import PrintLogEntry
  6093. existing_runs = await db.scalar(
  6094. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  6095. )
  6096. if (existing_runs or 0) <= 1:
  6097. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  6098. # we just wrote for THIS print. Either way it's the first run.
  6099. archive.energy_kwh = energy_used
  6100. archive.energy_cost = energy_cost_value
  6101. # Backfill the latest PrintLogEntry for this archive with energy
  6102. # (write_log_entry above ran before this background task completed,
  6103. # so energy fields are still NULL on that row).
  6104. latest_run = await db.execute(
  6105. select(PrintLogEntry)
  6106. .where(PrintLogEntry.archive_id == archive_id)
  6107. .order_by(PrintLogEntry.id.desc())
  6108. .limit(1)
  6109. )
  6110. run_row = latest_run.scalar_one_or_none()
  6111. if run_row is not None:
  6112. run_row.energy_kwh = energy_used
  6113. run_row.energy_cost = energy_cost_value
  6114. await db.commit()
  6115. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  6116. except Exception as e:
  6117. logger.warning("[ENERGY-BG] Failed: %s", e)
  6118. async def _background_finish_photo() -> str | None:
  6119. """Capture finish photo in background. Returns photo filename if captured."""
  6120. # #2547: set once this function has raised the plate itself (the
  6121. # timelapse path, where the moment producer returned without doing it).
  6122. # Declared out here so the `finally` can lower it again no matter where
  6123. # the capture below fails.
  6124. plate_restored_z: float | None = None
  6125. try:
  6126. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  6127. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  6128. # Read phase: settings + printer + archive in a short session, released
  6129. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  6130. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  6131. # tens of seconds; holding this session across it pinned one pooled
  6132. # connection idle-in-transaction per finishing print (issue #2572).
  6133. async with async_session() as db:
  6134. from backend.app.api.routes.settings import get_setting
  6135. from backend.app.models.archive import PrintArchive
  6136. from backend.app.models.printer import Printer
  6137. capture_enabled = await get_setting(db, "capture_finish_photo")
  6138. if capture_enabled is not None and capture_enabled.lower() != "true":
  6139. return None
  6140. if not archive_id:
  6141. return None
  6142. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  6143. archive = (
  6144. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6145. ).scalar_one_or_none()
  6146. if not printer or not archive:
  6147. return None
  6148. import uuid
  6149. from datetime import datetime
  6150. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  6151. if not archive.file_path:
  6152. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  6153. archive_dir = resolve_archive_dir(archive)
  6154. photo_filename = None
  6155. # Prefer the timelapse last-frame source when a timelapse was
  6156. # recording — it captures the moment after the toolhead parks
  6157. # but before the bed drops, which the live-camera grab below
  6158. # would miss (#1397). Skipped for external cameras (those have
  6159. # their own framing and don't see a Bambu timelapse). Only
  6160. # runs when the USER explicitly enabled timelapse for this
  6161. # print — #1721 removed Bambuddy's force-on at dispatch
  6162. # because it caused per-layer nozzle parking on Smooth-mode
  6163. # slicer profiles.
  6164. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  6165. printer.external_camera_enabled and printer.external_camera_url
  6166. )
  6167. timelapse_still_pending = False
  6168. if prefer_timelapse_source:
  6169. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  6170. archive_id=archive_id,
  6171. archive_dir=archive_dir,
  6172. rotation=getattr(printer, "camera_rotation", 0),
  6173. )
  6174. # #1721: replacement framing path — on_finish_photo_moment
  6175. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  6176. # parked, bed not yet dropped) and cached the JPEG bytes in
  6177. # _stage22_finish_frames. Consume them now so the saved photo
  6178. # has the better framing instead of the post-bed-drop angle
  6179. # the live-camera fallback below would give.
  6180. if not photo_filename:
  6181. # #1790: on the FINISH-state fallback path the producer
  6182. # task is dispatched back-to-back with this consumer, so
  6183. # a bare pop would race past with an empty result and
  6184. # the RTSP fallback below would collide with the
  6185. # producer's still-in-flight grab (single-client RTSP
  6186. # on Bambu printers). Wait for the producer to finish
  6187. # or give up before touching the cache.
  6188. #
  6189. # #2547: 20s was enough when the producer only ever grabbed a
  6190. # frame. It now also raises the plate first, which costs the
  6191. # settle window before the grab even starts — so the budget has
  6192. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  6193. # under the notification's own photo wait below.
  6194. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  6195. if in_flight is not None:
  6196. try:
  6197. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  6198. except asyncio.TimeoutError:
  6199. logger.warning(
  6200. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  6201. printer_id,
  6202. )
  6203. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  6204. if cached_frame:
  6205. # Already rotated by the producer (#2708) — rotating again
  6206. # here would undo the fix on the banked-frame path, whose
  6207. # bytes reach the cache having been rotated once already.
  6208. photos_dir = archive_dir / "photos"
  6209. photos_dir.mkdir(parents=True, exist_ok=True)
  6210. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6211. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6212. photo_path = photos_dir / photo_filename
  6213. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  6214. logger.info(
  6215. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  6216. photo_filename,
  6217. len(cached_frame),
  6218. )
  6219. # #2547: the timelapse path reaches the live grab below whenever the
  6220. # video hasn't landed in time — the documented usual outcome on
  6221. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  6222. # returned early for those prints without raising the plate, so
  6223. # without this the photo that actually ships in the notification is
  6224. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  6225. # asked us to fix. The archive still gets the better video frame
  6226. # later; this is about the image the user is sent.
  6227. #
  6228. # Gated on `timelapse_was_active` precisely because that is the
  6229. # condition under which the producer skipped. On every other path it
  6230. # has already raised and lowered the plate, and repeating that here
  6231. # would be a second pointless round trip.
  6232. if (
  6233. not photo_filename
  6234. and data.get("timelapse_was_active")
  6235. and not print_dispatch_context.end_gcode_injected(printer_id)
  6236. ):
  6237. try:
  6238. async with async_session() as db:
  6239. from backend.app.api.routes.settings import get_setting
  6240. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6241. if restore_setting is None or restore_setting.lower() == "true":
  6242. max_z = await _max_z_for_current_print(printer_id, data, logger)
  6243. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  6244. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  6245. plate_restored_z = max_z
  6246. except Exception as e:
  6247. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  6248. # Fallback chain: external camera → buffered live frame →
  6249. # fresh RTSP capture. Only runs if the timelapse path above
  6250. # didn't already produce a photo.
  6251. if not photo_filename:
  6252. if printer.external_camera_enabled and printer.external_camera_url:
  6253. logger.info("[PHOTO-BG] Using external camera")
  6254. from backend.app.api.routes.camera import live_frame_for_capture
  6255. from backend.app.services.external_camera import capture_frame
  6256. # #2707: the second half of the finish-photo failure — the
  6257. # pre-capture and this fallback both collided with the live
  6258. # view. None here continues down the fallback chain.
  6259. defer, buffered = live_frame_for_capture(printer_id)
  6260. if defer:
  6261. frame_data = buffered
  6262. else:
  6263. frame_data = await capture_frame(
  6264. printer.external_camera_url,
  6265. printer.external_camera_type or "mjpeg",
  6266. snapshot_url=printer.external_camera_snapshot_url,
  6267. )
  6268. if frame_data:
  6269. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  6270. photos_dir = archive_dir / "photos"
  6271. photos_dir.mkdir(parents=True, exist_ok=True)
  6272. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6273. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6274. photo_path = photos_dir / photo_filename
  6275. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  6276. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  6277. else:
  6278. # Check if camera stream is active - use buffered frame to avoid freeze
  6279. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  6280. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  6281. active_chamber_for_printer = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  6282. buffered_frame = get_buffered_frame(printer_id)
  6283. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  6284. # Use frame from active stream
  6285. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  6286. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  6287. photos_dir = archive_dir / "photos"
  6288. photos_dir.mkdir(parents=True, exist_ok=True)
  6289. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6290. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6291. photo_path = photos_dir / photo_filename
  6292. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  6293. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  6294. else:
  6295. # No active stream - capture new frame
  6296. from backend.app.services.camera import capture_finish_photo
  6297. photo_filename = await capture_finish_photo(
  6298. printer_id=printer_id,
  6299. ip_address=printer.ip_address,
  6300. access_code=printer.access_code,
  6301. model=printer.model,
  6302. archive_dir=archive_dir,
  6303. rotation=getattr(printer, "camera_rotation", 0),
  6304. )
  6305. # Write phase: attach the photo in a fresh short-lived session.
  6306. if photo_filename:
  6307. async with async_session() as db:
  6308. from backend.app.models.archive import PrintArchive
  6309. arch = await db.get(PrintArchive, archive_id)
  6310. if arch is not None:
  6311. photos = arch.photos or []
  6312. photos.append(photo_filename)
  6313. arch.photos = photos
  6314. await db.commit()
  6315. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  6316. # The short wait above is bounded so a slow printer can't hold up
  6317. # the print-complete notification, which is what the caller is
  6318. # blocking on. When it ran out with the video still on its way,
  6319. # keep waiting off to the side and add the better frame to the
  6320. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  6321. # users, whose videos routinely take minutes to transfer, never get
  6322. # the pre-bed-drop framing this path exists to provide.
  6323. #
  6324. # Spawned here rather than at the point the wait gave up: both this
  6325. # function and the upgrade do a read-modify-write on `photos`, and
  6326. # the live-camera fallback above can take tens of seconds. Starting
  6327. # the upgrade before that write means the two can interleave and one
  6328. # silently drops the other's entry, leaving a JPEG on disk that the
  6329. # gallery never lists.
  6330. if timelapse_still_pending:
  6331. spawn_background_task(
  6332. _upgrade_finish_photo_from_timelapse(
  6333. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  6334. ),
  6335. name=f"finish-photo-upgrade-{archive_id}",
  6336. )
  6337. return photo_filename
  6338. except Exception as e:
  6339. logger.warning("[PHOTO-BG] Failed: %s", e)
  6340. return None
  6341. finally:
  6342. # #2547: we raised the plate, so we owe the move back down — even if
  6343. # the capture in between threw. Otherwise the user finds the print
  6344. # pinned under the nozzle.
  6345. if plate_restored_z is not None:
  6346. try:
  6347. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  6348. except Exception as e:
  6349. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6350. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  6351. # Photo capture task - result will be used by notifications
  6352. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  6353. log_timing("Background tasks scheduled (energy, photo)")
  6354. # Also run smart plug, notifications, and maintenance as background tasks
  6355. print_status = data.get("status", "completed")
  6356. async def _background_smart_plug():
  6357. """Handle smart plug automation in background."""
  6358. try:
  6359. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  6360. async with async_session() as db:
  6361. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  6362. logger.info("[AUTO-OFF-BG] Completed")
  6363. except Exception as e:
  6364. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  6365. async def _background_notifications(finish_photo_filename: str | None = None):
  6366. """Send print complete notifications in background."""
  6367. try:
  6368. logger.info(
  6369. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  6370. )
  6371. async with async_session() as db:
  6372. from backend.app.models.archive import PrintArchive
  6373. from backend.app.models.printer import Printer
  6374. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6375. printer = result.scalar_one_or_none()
  6376. printer_name = printer.name if printer else f"Printer {printer_id}"
  6377. archive_data = None
  6378. if archive_id:
  6379. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6380. archive = archive_result.scalar_one_or_none()
  6381. if archive:
  6382. # Actual elapsed time from started_at/completed_at when both are
  6383. # populated (every terminal status sets completed_at after #1198).
  6384. # Falls back to None so the notification path can decide whether to
  6385. # render the slicer estimate as a last resort.
  6386. actual_time_seconds = None
  6387. if archive.started_at and archive.completed_at:
  6388. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  6389. if elapsed > 0:
  6390. actual_time_seconds = int(elapsed)
  6391. archive_data = {
  6392. "print_time_seconds": archive.print_time_seconds,
  6393. "actual_time_seconds": actual_time_seconds,
  6394. "actual_filament_grams": archive.filament_used_grams,
  6395. "failure_reason": archive.failure_reason,
  6396. "created_by_id": archive.created_by_id,
  6397. }
  6398. # Scale filament usage for partial prints
  6399. if print_status != "completed" and archive.filament_used_grams:
  6400. progress = data.get("progress") or 0
  6401. scale = _partial_progress_scale(progress)
  6402. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  6403. archive_data["progress"] = progress
  6404. # Pass per-slot data from archive.extra_data
  6405. if archive.extra_data and archive.extra_data.get("filament_slots"):
  6406. slots = archive.extra_data["filament_slots"]
  6407. if print_status != "completed":
  6408. scale = _partial_progress_scale(data.get("progress"))
  6409. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  6410. archive_data["filament_slots"] = slots
  6411. # Scope project-summed totals down to the plate that was
  6412. # actually printed — see _scope_notification_archive_data_to_plate
  6413. # for the why (#1785).
  6414. archive_data = _scope_notification_archive_data_to_plate(
  6415. archive_data,
  6416. archive.file_path,
  6417. notify_plate_id,
  6418. print_status,
  6419. data.get("progress"),
  6420. app_settings.base_dir,
  6421. )
  6422. # Enrich filament_grams from usage_results when archive has no 3MF data
  6423. if not archive_data.get("actual_filament_grams") and usage_results:
  6424. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  6425. if total_from_usage > 0:
  6426. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  6427. # Pass usage tracker results for AMS slot info in notifications
  6428. if usage_results:
  6429. archive_data["usage_results"] = usage_results
  6430. # Add finish photo URL and image bytes if available
  6431. if finish_photo_filename:
  6432. from backend.app.api.routes.settings import get_setting
  6433. external_url = await get_setting(db, "external_url")
  6434. if external_url:
  6435. external_url = external_url.rstrip("/")
  6436. archive_data["finish_photo_url"] = (
  6437. f"{external_url}/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  6438. )
  6439. else:
  6440. # Fallback to relative URL (won't work for external services)
  6441. archive_data["finish_photo_url"] = (
  6442. f"/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  6443. )
  6444. # Read finish photo bytes for image attachment (e.g. Pushover)
  6445. try:
  6446. from backend.app.utils.archive_paths import find_archive_photo
  6447. photo_path = find_archive_photo(archive, finish_photo_filename)
  6448. if photo_path is not None:
  6449. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  6450. if len(photo_bytes) <= 2_500_000:
  6451. archive_data["image_data"] = photo_bytes
  6452. logger.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  6453. else:
  6454. logger.warning(
  6455. f"[NOTIFY-BG] Finish photo too large for attachment: "
  6456. f"{len(photo_bytes)} bytes"
  6457. )
  6458. except Exception as e:
  6459. logger.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  6460. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  6461. await notification_service.on_print_complete(
  6462. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  6463. )
  6464. else:
  6465. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  6466. # Send user-specific email notification
  6467. if archive_data:
  6468. created_by_id = archive_data.get("created_by_id")
  6469. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  6470. await _dispatch_user_print_email(
  6471. print_status,
  6472. created_by_id,
  6473. printer_name,
  6474. raw_filename,
  6475. db,
  6476. )
  6477. logger.info("[NOTIFY-BG] Completed")
  6478. except Exception as e:
  6479. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  6480. async def _background_maintenance_check():
  6481. """Check for maintenance due in background."""
  6482. if print_status != "completed":
  6483. return
  6484. try:
  6485. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  6486. async with async_session() as db:
  6487. from backend.app.models.printer import Printer
  6488. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6489. printer = result.scalar_one_or_none()
  6490. printer_name = printer.name if printer else f"Printer {printer_id}"
  6491. await ensure_default_types(db)
  6492. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  6493. items_needing_attention = [
  6494. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  6495. for item in overview.maintenance_items
  6496. if item.enabled and (item.is_due or item.is_warning)
  6497. ]
  6498. if items_needing_attention:
  6499. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  6500. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  6501. # MQTT relay - publish maintenance alerts
  6502. for item in items_needing_attention:
  6503. try:
  6504. await mqtt_relay.on_maintenance_alert(
  6505. printer_id=printer_id,
  6506. printer_name=printer_name,
  6507. maintenance_type=item["name"],
  6508. current_value=0, # Not easily available here
  6509. threshold=0, # Not easily available here
  6510. )
  6511. except Exception:
  6512. pass # Don't fail if MQTT fails
  6513. else:
  6514. logger.info("[MAINT-BG] Completed (no items need attention)")
  6515. except Exception as e:
  6516. logger.warning("[MAINT-BG] Failed: %s", e)
  6517. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  6518. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  6519. # Notification task waits for photo capture to complete first (with timeout).
  6520. # When a timelapse was recording, photo sourcing polls the per-print
  6521. # timelapse for up to 60s (#1397) — extend the budget so the notification
  6522. # carries the correct bed-up photo instead of falling through to the
  6523. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  6524. #
  6525. # #2547: both budgets now have to cover a plate restore as well.
  6526. #
  6527. # Without timelapse, the wait is on the moment producer, which raises the
  6528. # plate before its grab — so this has to outlast that producer's own budget.
  6529. #
  6530. # With timelapse, the capture polls up to
  6531. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  6532. # falls back to a live grab, which is the case that raises the plate. At the
  6533. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  6534. # restore would have moved the plate for a photo nobody waited for.
  6535. photo_wait_timeout = (
  6536. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  6537. if data.get("timelapse_was_active")
  6538. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  6539. )
  6540. async def _photo_then_notify():
  6541. """Wait for photo capture, then send notification with photo URL."""
  6542. finish_photo = None
  6543. try:
  6544. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  6545. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  6546. except TimeoutError:
  6547. logger.warning(
  6548. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  6549. photo_wait_timeout,
  6550. )
  6551. except Exception as e:
  6552. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  6553. try:
  6554. await _background_notifications(finish_photo)
  6555. except Exception as e:
  6556. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  6557. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  6558. # Stitch external camera layer timelapse if session was active
  6559. print_status = data.get("status", "completed")
  6560. async def _background_layer_timelapse():
  6561. """Stitch layer timelapse and attach to archive."""
  6562. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  6563. try:
  6564. if print_status == "completed":
  6565. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  6566. timelapse_path = await tl_complete(printer_id)
  6567. if timelapse_path and archive_id:
  6568. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  6569. async with async_session() as db:
  6570. service = ArchiveService(db)
  6571. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  6572. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  6573. # Clean up the temp file
  6574. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6575. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  6576. elif timelapse_path:
  6577. # Timelapse created but no archive - just clean up
  6578. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6579. else:
  6580. # Print failed or cancelled - cancel timelapse session
  6581. cancel_session(printer_id)
  6582. logger.info(
  6583. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  6584. )
  6585. except Exception as e:
  6586. logger.warning("[LAYER-TL] Failed: %s", e)
  6587. # Try to cancel session on error
  6588. try:
  6589. cancel_session(printer_id)
  6590. except Exception:
  6591. pass # Best-effort timelapse session cancellation on error
  6592. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  6593. log_timing("All background tasks scheduled")
  6594. # Auto-scan for timelapse if recording was active during the print
  6595. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  6596. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  6597. # Schedule timelapse scan as background task with retries
  6598. # The printer needs time to encode the video after print completion
  6599. baseline = _timelapse_baselines.pop(printer_id, None)
  6600. spawn_background_task(
  6601. _scan_for_timelapse_with_retries(archive_id, baseline),
  6602. name=f"scan-timelapse-{archive_id}",
  6603. )
  6604. log_timing("Timelapse scan scheduled")
  6605. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  6606. # AMS sensor history recording
  6607. _ams_history_task: asyncio.Task | None = None
  6608. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  6609. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  6610. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  6611. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  6612. _ams_alarm_cooldown: dict[str, datetime] = {}
  6613. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  6614. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  6615. # through a cycle and the cool-down after it (#1802). Stored in the settings
  6616. # table rather than alongside _ams_alarm_cooldown above, because a restart
  6617. # partway through a cool-down would otherwise resume alarming about heat the
  6618. # user asked for — the same internal-timestamp-row pattern as
  6619. # support.py's debug_logging_enabled_at.
  6620. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  6621. # Upper bound on that suppression. The latch normally clears as soon as the unit
  6622. # reads at or below the threshold; see utils.ams_drying for why this cap only
  6623. # matters when it never does.
  6624. AMS_DRYING_GRACE_MINUTES = 120
  6625. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  6626. """Read the persisted per-AMS drying latch, dropping entries out of window.
  6627. Anything older than the grace cap would expire on its next visit anyway, so
  6628. discarding it here costs nothing and stops rows for deleted printers from
  6629. accumulating.
  6630. Stamps ahead of now get two defences, because a box whose clock jumps
  6631. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  6632. ones are discarded outright, and the rest are clamped to now. Without the
  6633. clamp the cap would measure from a moment that has not happened yet and hold
  6634. the alarm quiet for the skew on top of the cap. One unnecessary notification
  6635. after a clock jump is a far better failure than an alarm silently disabled
  6636. for hours.
  6637. """
  6638. from backend.app.models.settings import Settings
  6639. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  6640. setting = result.scalar_one_or_none()
  6641. if not setting or not setting.value:
  6642. return {}
  6643. try:
  6644. raw = json.loads(setting.value)
  6645. except (ValueError, TypeError):
  6646. return {} # Corrupted row → no latch, alarms behave as they did before
  6647. if not isinstance(raw, dict):
  6648. return {}
  6649. now = datetime.now(timezone.utc)
  6650. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  6651. latch: dict[str, datetime] = {}
  6652. for key, value in raw.items():
  6653. try:
  6654. stamp = datetime.fromisoformat(str(value))
  6655. except (ValueError, TypeError):
  6656. continue
  6657. if stamp.tzinfo is None:
  6658. stamp = stamp.replace(tzinfo=timezone.utc)
  6659. if not (now - window <= stamp <= now + window):
  6660. continue
  6661. # Nothing may sit in the future: suppression is measured as now minus
  6662. # the stamp, so a stamp ahead of now would extend it by the skew on top
  6663. # of the cap. Clamping the survivors keeps the cap an actual cap.
  6664. latch[str(key)] = min(stamp, now)
  6665. return latch
  6666. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  6667. """Persist the latch, writing only when it actually changed.
  6668. Adds the session change but does not commit — the caller's own commit
  6669. carries it, so the latch lands in the same transaction as the sensor rows
  6670. that produced it.
  6671. """
  6672. from backend.app.models.settings import Settings
  6673. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  6674. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  6675. setting = result.scalar_one_or_none()
  6676. if setting is None:
  6677. # Don't create the row on installs that never dry anything.
  6678. if payload != "{}":
  6679. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  6680. elif setting.value != payload:
  6681. setting.value = payload
  6682. def _ams_has_filament(ams_data: dict) -> bool:
  6683. """True if this AMS unit has at least one tray slot holding filament.
  6684. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  6685. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  6686. still report sensor readings, but those readings are ambient and not
  6687. actionable: no filament to dry, no humidity to push down. #1619 — gate
  6688. humidity/temperature alarms on this check so empty units don't generate
  6689. hourly noise. Sensor history still records regardless so the UI charts
  6690. stay continuous.
  6691. Fallback path inspects the `tray` array's `tray_type` fields for setups
  6692. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  6693. """
  6694. bits = ams_data.get("tray_exist_bits")
  6695. if isinstance(bits, str) and bits.strip():
  6696. try:
  6697. return int(bits, 16) > 0
  6698. except ValueError:
  6699. pass
  6700. trays = ams_data.get("tray")
  6701. if isinstance(trays, list):
  6702. return any(
  6703. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  6704. )
  6705. return False
  6706. async def record_ams_history():
  6707. """Background task to record AMS humidity and temperature data."""
  6708. logger = logging.getLogger(__name__)
  6709. # Wait a short time for MQTT connections to establish on startup
  6710. await asyncio.sleep(10)
  6711. while True:
  6712. try:
  6713. from backend.app.models.ams_history import AMSSensorHistory
  6714. from backend.app.models.printer import Printer
  6715. from backend.app.models.settings import Settings
  6716. async with async_session() as db:
  6717. # Get all active printers
  6718. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  6719. printers = result.scalars().all()
  6720. # Get alarm thresholds from settings
  6721. humidity_threshold = 60.0 # Default: fair threshold
  6722. temp_threshold = 35.0 # Default: fair threshold
  6723. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  6724. setting = result.scalar_one_or_none()
  6725. if setting:
  6726. try:
  6727. humidity_threshold = float(setting.value)
  6728. except (ValueError, TypeError):
  6729. pass # Keep default threshold if stored value is invalid
  6730. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  6731. setting = result.scalar_one_or_none()
  6732. if setting:
  6733. try:
  6734. temp_threshold = float(setting.value)
  6735. except (ValueError, TypeError):
  6736. pass # Keep default threshold if stored value is invalid
  6737. # Per-filament humidity threshold overrides (#1605) — resolved
  6738. # per-AMS below from the loaded tray types. Reuses the same
  6739. # resolver as the auto-drying scheduler so behavior stays in
  6740. # lockstep across both consumers.
  6741. from backend.app.services.print_scheduler import PrintScheduler
  6742. per_type_humidity_thresholds: dict[str, int] = {}
  6743. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  6744. setting = result.scalar_one_or_none()
  6745. if setting and setting.value:
  6746. try:
  6747. raw = json.loads(setting.value)
  6748. if isinstance(raw, dict):
  6749. for k, v in raw.items():
  6750. try:
  6751. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  6752. v
  6753. )
  6754. except (TypeError, ValueError):
  6755. continue
  6756. except (ValueError, TypeError):
  6757. pass # Invalid JSON → no overrides, fall through to global threshold
  6758. # Per-AMS drying latch (#1802), loaded once per pass and written
  6759. # back below only if a unit changed it.
  6760. drying_latch = await _load_ams_drying_latch(db)
  6761. drying_latch_before = dict(drying_latch)
  6762. recorded_count = 0
  6763. for printer in printers:
  6764. # Get current state from printer manager
  6765. state = printer_manager.get_status(printer.id)
  6766. if not state or not state.connected or not state.raw_data:
  6767. continue # Skip disconnected printers - don't use stale data
  6768. raw_data = state.raw_data
  6769. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  6770. continue
  6771. # Record data for each AMS unit
  6772. for ams_data in raw_data["ams"]:
  6773. ams_id = int(ams_data.get("id", 0))
  6774. # Get humidity (prefer humidity_raw)
  6775. humidity_raw = ams_data.get("humidity_raw")
  6776. humidity_idx = ams_data.get("humidity")
  6777. humidity = None
  6778. if humidity_raw is not None:
  6779. try:
  6780. humidity = float(humidity_raw)
  6781. except (ValueError, TypeError):
  6782. pass # Skip unparseable humidity; will try fallback
  6783. if humidity is None and humidity_idx is not None:
  6784. try:
  6785. humidity = float(humidity_idx)
  6786. except (ValueError, TypeError):
  6787. pass # Skip unparseable humidity index value
  6788. # Get temperature
  6789. temperature = None
  6790. temp_str = ams_data.get("temp")
  6791. if temp_str is not None:
  6792. try:
  6793. temperature = float(temp_str)
  6794. except (ValueError, TypeError):
  6795. pass # Skip unparseable temperature value
  6796. # Skip if no data
  6797. if humidity is None and temperature is None:
  6798. continue
  6799. # Record the data point
  6800. history = AMSSensorHistory(
  6801. printer_id=printer.id,
  6802. ams_id=ams_id,
  6803. humidity=humidity,
  6804. humidity_raw=float(humidity_raw) if humidity_raw else None,
  6805. temperature=temperature,
  6806. )
  6807. db.add(history)
  6808. recorded_count += 1
  6809. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  6810. is_ams_ht = ams_id >= 128
  6811. if is_ams_ht:
  6812. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  6813. else:
  6814. ams_label = f"AMS-{chr(65 + ams_id)}"
  6815. # Skip alarm dispatch for empty AMS units — humidity /
  6816. # temperature readings are ambient with no filament to
  6817. # protect, and the hourly notification just becomes
  6818. # noise. Sensor history was already recorded above so
  6819. # the UI charts stay continuous (#1619). Per-AMS check
  6820. # so a multi-AMS setup with one loaded + one empty
  6821. # still alarms on the loaded unit.
  6822. if not _ams_has_filament(ams_data):
  6823. continue
  6824. # Resolve per-filament humidity threshold for this AMS
  6825. # unit (#1605). Falls back to the global ams_humidity_fair
  6826. # when no per-type overrides are configured.
  6827. trays = ams_data.get("tray", []) or []
  6828. effective_humidity_threshold = float(
  6829. PrintScheduler.resolve_humidity_threshold(
  6830. trays, per_type_humidity_thresholds, int(humidity_threshold)
  6831. )
  6832. )
  6833. # Check humidity alarm (only if above threshold)
  6834. if humidity is not None and humidity > effective_humidity_threshold:
  6835. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  6836. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  6837. now = datetime.now(timezone.utc)
  6838. if (
  6839. last_alarm is None
  6840. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  6841. ):
  6842. _ams_alarm_cooldown[cooldown_key] = now
  6843. logger.info(
  6844. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  6845. )
  6846. try:
  6847. # Call different notification method based on AMS type
  6848. if is_ams_ht:
  6849. await notification_service.on_ams_ht_humidity_high(
  6850. printer.id,
  6851. printer.name,
  6852. ams_label,
  6853. humidity,
  6854. effective_humidity_threshold,
  6855. db,
  6856. )
  6857. else:
  6858. await notification_service.on_ams_humidity_high(
  6859. printer.id,
  6860. printer.name,
  6861. ams_label,
  6862. humidity,
  6863. effective_humidity_threshold,
  6864. db,
  6865. )
  6866. except Exception as e:
  6867. logger.warning("Failed to send humidity alarm: %s", e)
  6868. # A drying cycle heats the unit far past ams_temp_fair on
  6869. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  6870. # AMS-HT, against a 35 C default — so the alarm fired
  6871. # once an hour for the whole cycle and kept firing while
  6872. # the unit cooled back down (#1802). Latch on the
  6873. # firmware's own drying state and hold until the reading
  6874. # returns to normal. Humidity is deliberately left alone:
  6875. # it falls during drying, which is the whole point.
  6876. latch_key = f"{printer.id}:{ams_id}"
  6877. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  6878. drying_active=is_drying_active(ams_data),
  6879. temperature=temperature,
  6880. threshold=temp_threshold,
  6881. latched_at=drying_latch.get(latch_key),
  6882. now=datetime.now(timezone.utc),
  6883. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  6884. )
  6885. if new_latch is None:
  6886. drying_latch.pop(latch_key, None)
  6887. else:
  6888. drying_latch[latch_key] = new_latch
  6889. # Check temperature alarm (only if above threshold)
  6890. if temperature is not None and temperature > temp_threshold and not suppress_temp_alarm:
  6891. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  6892. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  6893. now = datetime.now(timezone.utc)
  6894. if (
  6895. last_alarm is None
  6896. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  6897. ):
  6898. _ams_alarm_cooldown[cooldown_key] = now
  6899. logger.info(
  6900. f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C"
  6901. )
  6902. try:
  6903. # Call different notification method based on AMS type
  6904. if is_ams_ht:
  6905. await notification_service.on_ams_ht_temperature_high(
  6906. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  6907. )
  6908. else:
  6909. await notification_service.on_ams_temperature_high(
  6910. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  6911. )
  6912. except Exception as e:
  6913. logger.warning("Failed to send temperature alarm: %s", e)
  6914. if drying_latch != drying_latch_before:
  6915. await _save_ams_drying_latch(db, drying_latch)
  6916. await db.commit()
  6917. if recorded_count > 0:
  6918. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  6919. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  6920. global _ams_cleanup_counter
  6921. _ams_cleanup_counter += 1
  6922. if _ams_cleanup_counter >= 288:
  6923. _ams_cleanup_counter = 0
  6924. # Get retention days from settings
  6925. from backend.app.models.settings import Settings
  6926. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  6927. setting = result.scalar_one_or_none()
  6928. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  6929. cutoff = utcnow_naive() - timedelta(days=retention_days)
  6930. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  6931. await db.commit()
  6932. if result.rowcount > 0:
  6933. logger.info(
  6934. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  6935. )
  6936. # Wait until next recording interval
  6937. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  6938. except asyncio.CancelledError:
  6939. break
  6940. except Exception as e:
  6941. logger.warning("AMS history recording failed: %s", e)
  6942. await asyncio.sleep(60) # Wait a bit before retrying
  6943. def start_ams_history_recording():
  6944. """Start the AMS history recording background task."""
  6945. global _ams_history_task
  6946. if _ams_history_task is None:
  6947. _ams_history_task = asyncio.create_task(record_ams_history())
  6948. logging.getLogger(__name__).info("AMS history recording started")
  6949. def stop_ams_history_recording():
  6950. """Stop the AMS history recording background task."""
  6951. global _ams_history_task
  6952. if _ams_history_task:
  6953. _ams_history_task.cancel()
  6954. _ams_history_task = None
  6955. logging.getLogger(__name__).info("AMS history recording stopped")
  6956. # Printer sensor history recording (nozzle / bed / chamber)
  6957. _printer_sensor_history_task: asyncio.Task | None = None
  6958. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  6959. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  6960. _printer_sensor_cleanup_counter = 0
  6961. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  6962. # MQTT parser writes, so we don't need to handle per-model field aliases here
  6963. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  6964. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  6965. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  6966. _SENSOR_TARGET_KEYS = {
  6967. "nozzle": "nozzle_target",
  6968. "nozzle_2": "nozzle_2_target",
  6969. "bed": "bed_target",
  6970. "chamber": "chamber_target",
  6971. }
  6972. async def record_printer_sensor_history():
  6973. """Background task to record nozzle / bed / chamber readings.
  6974. Pulls from `state.temperatures` (already normalised across all printer
  6975. models by the MQTT parser) rather than re-parsing raw_data, so we get
  6976. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  6977. """
  6978. logger = logging.getLogger(__name__)
  6979. await asyncio.sleep(10)
  6980. while True:
  6981. try:
  6982. from backend.app.models.printer import Printer
  6983. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  6984. from backend.app.models.settings import Settings
  6985. async with async_session() as db:
  6986. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  6987. printers = result.scalars().all()
  6988. recorded_count = 0
  6989. for printer in printers:
  6990. state = printer_manager.get_status(printer.id)
  6991. if not state or not state.connected:
  6992. continue
  6993. temps = getattr(state, "temperatures", None) or {}
  6994. if not isinstance(temps, dict):
  6995. continue
  6996. for kind in _SENSOR_KINDS:
  6997. if kind not in temps:
  6998. continue
  6999. try:
  7000. value = float(temps[kind])
  7001. except (ValueError, TypeError):
  7002. continue
  7003. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  7004. target_val: float | None = None
  7005. if target_raw is not None:
  7006. try:
  7007. target_val = float(target_raw)
  7008. except (ValueError, TypeError):
  7009. target_val = None
  7010. db.add(
  7011. PrinterSensorHistory(
  7012. printer_id=printer.id,
  7013. sensor_kind=kind,
  7014. value=value,
  7015. target=target_val,
  7016. )
  7017. )
  7018. recorded_count += 1
  7019. await db.commit()
  7020. if recorded_count > 0:
  7021. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  7022. # Periodic cleanup — once every ~24h at this interval.
  7023. global _printer_sensor_cleanup_counter
  7024. _printer_sensor_cleanup_counter += 1
  7025. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  7026. if _printer_sensor_cleanup_counter >= cleanup_every:
  7027. _printer_sensor_cleanup_counter = 0
  7028. result = await db.execute(
  7029. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  7030. )
  7031. setting = result.scalar_one_or_none()
  7032. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  7033. cutoff = utcnow_naive() - timedelta(days=retention_days)
  7034. cleanup = await db.execute(
  7035. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  7036. )
  7037. await db.commit()
  7038. if cleanup.rowcount > 0:
  7039. logger.info(
  7040. "Cleaned up %s old printer sensor history entries (older than %s days)",
  7041. cleanup.rowcount,
  7042. retention_days,
  7043. )
  7044. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  7045. except asyncio.CancelledError:
  7046. break
  7047. except Exception as e:
  7048. logger.warning("Printer sensor history recording failed: %s", e)
  7049. await asyncio.sleep(60)
  7050. def start_printer_sensor_history_recording():
  7051. global _printer_sensor_history_task
  7052. if _printer_sensor_history_task is None:
  7053. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  7054. logging.getLogger(__name__).info("Printer sensor history recording started")
  7055. def stop_printer_sensor_history_recording():
  7056. global _printer_sensor_history_task
  7057. if _printer_sensor_history_task:
  7058. _printer_sensor_history_task.cancel()
  7059. _printer_sensor_history_task = None
  7060. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  7061. # Printer runtime tracking
  7062. _runtime_tracking_task: asyncio.Task | None = None
  7063. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  7064. async def track_printer_runtime():
  7065. """Background task to track printer active runtime (RUNNING state only).
  7066. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  7067. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  7068. which track mechanical wear. Pause time has no motion and no wear, so
  7069. counting it inflates maintenance warnings (#1521).
  7070. """
  7071. logger = logging.getLogger(__name__)
  7072. # Wait for MQTT connections to establish on startup
  7073. await asyncio.sleep(15)
  7074. while True:
  7075. try:
  7076. from backend.app.models.printer import Printer
  7077. # Fetch printer IDs in a short-lived read-only session
  7078. async with async_session() as db:
  7079. result = await db.execute(
  7080. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  7081. Printer.is_active.is_(True)
  7082. )
  7083. )
  7084. printer_rows = result.all()
  7085. now = datetime.now(timezone.utc)
  7086. updated_count = 0
  7087. # Update each printer in its own short session to minimise write-lock
  7088. # hold time and avoid blocking critical commits like queue status
  7089. # updates (#897).
  7090. for pid, pname, runtime_secs, last_update in printer_rows:
  7091. state = printer_manager.get_status(pid)
  7092. if not state:
  7093. logger.debug("[%s] Runtime tracking: no state available", pname)
  7094. continue
  7095. if not state.connected:
  7096. logger.debug("[%s] Runtime tracking: not connected", pname)
  7097. continue
  7098. needs_commit = False
  7099. new_runtime = runtime_secs
  7100. new_last_update = last_update
  7101. if state.state == "RUNNING":
  7102. if last_update:
  7103. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  7104. elapsed = (now - lu).total_seconds()
  7105. if elapsed > 0:
  7106. new_runtime = runtime_secs + int(elapsed)
  7107. updated_count += 1
  7108. needs_commit = True
  7109. logger.debug(
  7110. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  7111. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  7112. )
  7113. else:
  7114. needs_commit = True
  7115. logger.debug("[%s] Runtime tracking: first active detection", pname)
  7116. new_last_update = now
  7117. else:
  7118. if last_update is not None:
  7119. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  7120. new_last_update = None
  7121. needs_commit = True
  7122. if needs_commit:
  7123. try:
  7124. async with async_session() as db:
  7125. result = await db.execute(select(Printer).where(Printer.id == pid))
  7126. printer = result.scalar_one_or_none()
  7127. if printer:
  7128. printer.runtime_seconds = new_runtime
  7129. printer.last_runtime_update = new_last_update
  7130. await db.commit()
  7131. except Exception as e:
  7132. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  7133. if updated_count > 0:
  7134. logger.debug("Updated runtime for %s printer(s)", updated_count)
  7135. except asyncio.CancelledError:
  7136. logger.info("Runtime tracking cancelled")
  7137. break
  7138. except Exception as e:
  7139. logger.warning("Runtime tracking failed: %s", e)
  7140. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  7141. def start_runtime_tracking():
  7142. """Start the printer runtime tracking background task."""
  7143. global _runtime_tracking_task
  7144. if _runtime_tracking_task is None:
  7145. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  7146. logging.getLogger(__name__).info("Printer runtime tracking started")
  7147. def stop_runtime_tracking():
  7148. """Stop the printer runtime tracking background task."""
  7149. global _runtime_tracking_task
  7150. if _runtime_tracking_task:
  7151. _runtime_tracking_task.cancel()
  7152. _runtime_tracking_task = None
  7153. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  7154. # SpoolBuddy device watchdog
  7155. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  7156. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  7157. async def _spoolbuddy_watchdog_loop():
  7158. """Periodic check for SpoolBuddy devices that have gone offline."""
  7159. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  7160. while True:
  7161. try:
  7162. await spoolbuddy_watchdog()
  7163. except asyncio.CancelledError:
  7164. break
  7165. except Exception as e:
  7166. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  7167. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  7168. def start_spoolbuddy_watchdog():
  7169. global _spoolbuddy_watchdog_task
  7170. if _spoolbuddy_watchdog_task is None:
  7171. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  7172. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  7173. def stop_spoolbuddy_watchdog():
  7174. global _spoolbuddy_watchdog_task
  7175. if _spoolbuddy_watchdog_task:
  7176. _spoolbuddy_watchdog_task.cancel()
  7177. _spoolbuddy_watchdog_task = None
  7178. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  7179. # Dead-MQTT-session recovery
  7180. #
  7181. # check_staleness() covers the "connected but silent" half-broken session. It
  7182. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  7183. # is the only thing left watching at that point. When paho stops making
  7184. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  7185. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  7186. # offline with the UI open the whole time, recovered only when something
  7187. # happened to nudge it.
  7188. #
  7189. # This loop is that backstop. It only touches printers that had a working
  7190. # session and lost it, and only when the MQTT port still answers — a printer
  7191. # that is simply switched off is left to paho, since rebuilding a client
  7192. # against an unreachable host achieves nothing and would fill the log every
  7193. # night.
  7194. _connection_watchdog_task: asyncio.Task | None = None
  7195. CONNECTION_WATCHDOG_INTERVAL = 60
  7196. # How long a printer must have been silent before we stop trusting paho.
  7197. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  7198. # so a session that is recovering on its own is never interrupted.
  7199. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  7200. # Per-printer floor between rebuild attempts.
  7201. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  7202. _connection_watchdog_last_attempt: dict[int, float] = {}
  7203. async def _recover_dead_printer_sessions() -> int:
  7204. """Rebuild MQTT clients that have been offline too long to still be trying.
  7205. Returns the number of printers a rebuild was attempted for (for tests and
  7206. for the caller's logging). Never raises: one unreachable printer must not
  7207. stop the sweep for the rest of the farm.
  7208. """
  7209. logger = logging.getLogger(__name__)
  7210. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  7211. now = time.monotonic()
  7212. recovered = 0
  7213. for printer_id, client in list(printer_manager._clients.items()):
  7214. try:
  7215. if client.state.connected:
  7216. _connection_watchdog_last_attempt.pop(printer_id, None)
  7217. continue
  7218. # Time since the last inbound message is the age of the last known
  7219. # good session — no extra bookkeeping needed, and it is the same
  7220. # clock is_stale() reads. 0 means this client has never had one:
  7221. # that is the initial-connect path, where paho retrying is the
  7222. # correct and only behaviour, so leave it be.
  7223. last_msg = client._last_message_time
  7224. if not last_msg:
  7225. continue
  7226. offline_for = time.time() - last_msg
  7227. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  7228. continue
  7229. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  7230. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  7231. continue
  7232. if not await check_port(client.ip_address, PORT_MQTT):
  7233. # Switched off, unplugged, or off the network. Paho's retry is
  7234. # the right handler; say so at debug level and move on.
  7235. logger.debug(
  7236. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  7237. "— leaving the reconnect to paho",
  7238. printer_id,
  7239. offline_for,
  7240. )
  7241. _connection_watchdog_last_attempt[printer_id] = now
  7242. continue
  7243. _connection_watchdog_last_attempt[printer_id] = now
  7244. recovered += 1
  7245. logger.warning(
  7246. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  7247. "rebuilding the client with a fresh session (last connect error: %s)",
  7248. printer_id,
  7249. offline_for,
  7250. PORT_MQTT,
  7251. client.last_connect_error or "none recorded",
  7252. )
  7253. # Async context, so this takes the hard-reset path: fresh client_id,
  7254. # paho's QoS 1 queue dropped. That matters — a project_file left
  7255. # unacked on the dead session would otherwise replay into the new
  7256. # one and trip 0500_4003 on the printer (#1136).
  7257. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  7258. except Exception as e:
  7259. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  7260. return recovered
  7261. async def _connection_watchdog_loop():
  7262. logger = logging.getLogger(__name__)
  7263. # Let the initial connects settle before judging anyone offline.
  7264. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  7265. while True:
  7266. try:
  7267. await _recover_dead_printer_sessions()
  7268. except asyncio.CancelledError:
  7269. break
  7270. except Exception as e:
  7271. logger.warning("Connection watchdog sweep failed: %s", e)
  7272. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  7273. def start_connection_watchdog():
  7274. global _connection_watchdog_task
  7275. if _connection_watchdog_task is None:
  7276. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  7277. logging.getLogger(__name__).info("Printer connection watchdog started")
  7278. def stop_connection_watchdog():
  7279. global _connection_watchdog_task
  7280. if _connection_watchdog_task:
  7281. _connection_watchdog_task.cancel()
  7282. _connection_watchdog_task = None
  7283. _connection_watchdog_last_attempt.clear()
  7284. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  7285. # Camera stream orphan cleanup
  7286. _camera_cleanup_task: asyncio.Task | None = None
  7287. CAMERA_CLEANUP_INTERVAL = 60
  7288. async def _camera_cleanup_loop():
  7289. """Periodically clean up orphaned ffmpeg processes."""
  7290. from backend.app.api.routes.camera import cleanup_orphaned_streams
  7291. while True:
  7292. try:
  7293. await cleanup_orphaned_streams()
  7294. except asyncio.CancelledError:
  7295. break
  7296. except Exception as e:
  7297. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  7298. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  7299. def start_camera_cleanup():
  7300. global _camera_cleanup_task
  7301. if _camera_cleanup_task is None:
  7302. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  7303. logging.getLogger(__name__).info("Camera stream cleanup started")
  7304. def stop_camera_cleanup():
  7305. global _camera_cleanup_task
  7306. if _camera_cleanup_task:
  7307. _camera_cleanup_task.cancel()
  7308. _camera_cleanup_task = None
  7309. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  7310. # ---------------------------------------------------------------------------
  7311. # Expected-print TTL eviction
  7312. # ---------------------------------------------------------------------------
  7313. def _evict_stale_expected_prints() -> None:
  7314. """Remove entries from _expected_prints / _expected_print_creators that are
  7315. older than _EXPECTED_PRINT_TTL_SECONDS.
  7316. This prevents unbounded growth when a print is registered (via
  7317. register_expected_print) but on_print_start never fires — e.g. because the
  7318. printer disconnects, the app restarts, or the print is started directly from
  7319. the printer panel without going through the queue.
  7320. """
  7321. # Use monotonic time so the TTL is unaffected by system clock adjustments
  7322. # (e.g. NTP sync, DST changes).
  7323. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  7324. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  7325. if not stale_keys:
  7326. return
  7327. evicted_archive_ids: set[int] = set()
  7328. for key in stale_keys:
  7329. archive_id = _expected_prints.pop(key, None)
  7330. if archive_id is not None:
  7331. evicted_archive_ids.add(archive_id)
  7332. _expected_print_creators.pop(key, None)
  7333. _expected_print_registered_at.pop(key, None)
  7334. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  7335. # that have no remaining live keys in _expected_prints (all variants
  7336. # were just evicted).
  7337. live_archive_ids = set(_expected_prints.values())
  7338. for archive_id in evicted_archive_ids:
  7339. if archive_id not in live_archive_ids:
  7340. _print_ams_mappings.pop(archive_id, None)
  7341. _print_cost_center_ids.pop(archive_id, None)
  7342. _print_plate_ids.pop(archive_id, None)
  7343. logging.getLogger(__name__).info(
  7344. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  7345. )
  7346. async def _expected_prints_cleanup_loop() -> None:
  7347. """Background task: periodically evict stale expected-print entries."""
  7348. while True:
  7349. try:
  7350. _evict_stale_expected_prints()
  7351. except asyncio.CancelledError:
  7352. raise
  7353. except Exception as e:
  7354. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  7355. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  7356. def start_expected_prints_cleanup() -> None:
  7357. global _expected_prints_cleanup_task
  7358. if _expected_prints_cleanup_task is None:
  7359. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  7360. logging.getLogger(__name__).info("Expected prints cleanup started")
  7361. def stop_expected_prints_cleanup() -> None:
  7362. global _expected_prints_cleanup_task
  7363. if _expected_prints_cleanup_task:
  7364. _expected_prints_cleanup_task.cancel()
  7365. _expected_prints_cleanup_task = None
  7366. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  7367. # ---------------------------------------------------------------------------
  7368. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  7369. # ---------------------------------------------------------------------------
  7370. _auth_cleanup_task: asyncio.Task | None = None
  7371. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  7372. async def _run_auth_cleanup() -> None:
  7373. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  7374. from backend.app.core.database import async_session
  7375. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  7376. from backend.app.models.user_totp import UserTOTP
  7377. now = datetime.now(timezone.utc)
  7378. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  7379. try:
  7380. async with async_session() as db:
  7381. stale_cutoff = now - timedelta(hours=1)
  7382. result = await db.execute(
  7383. select(UserTOTP).where(
  7384. UserTOTP.is_enabled.is_(False),
  7385. UserTOTP.created_at < stale_cutoff,
  7386. )
  7387. )
  7388. stale_records = result.scalars().all()
  7389. if stale_records:
  7390. for rec in stale_records:
  7391. await db.delete(rec)
  7392. await db.commit()
  7393. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  7394. except Exception as e:
  7395. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  7396. # Remove expired revoked-JTI entries (they are no longer needed once the
  7397. # original token's exp has passed — the token would be rejected by JWT
  7398. # signature verification regardless).
  7399. try:
  7400. async with async_session() as db:
  7401. await db.execute(
  7402. delete(AuthEphemeralToken).where(
  7403. AuthEphemeralToken.token_type == "revoked_jti",
  7404. AuthEphemeralToken.expires_at < now,
  7405. )
  7406. )
  7407. await db.commit()
  7408. except Exception as e:
  7409. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  7410. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  7411. # Events outside this window can never affect rate-limit decisions — they only
  7412. # consume DB space. Use the same window constant as the rate limiter so the
  7413. # two are always in sync.
  7414. try:
  7415. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  7416. async with async_session() as db:
  7417. await db.execute(
  7418. delete(AuthRateLimitEvent).where(
  7419. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  7420. )
  7421. )
  7422. await db.commit()
  7423. except Exception as e:
  7424. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  7425. async def _auth_cleanup_loop() -> None:
  7426. """Periodic background task: run auth cleanup every hour."""
  7427. while True:
  7428. try:
  7429. await _run_auth_cleanup()
  7430. except asyncio.CancelledError:
  7431. break
  7432. except Exception as e:
  7433. logging.warning("Auth cleanup loop error: %s", e)
  7434. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  7435. def start_auth_cleanup() -> None:
  7436. global _auth_cleanup_task
  7437. if _auth_cleanup_task is None:
  7438. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  7439. logging.getLogger(__name__).info("Auth periodic cleanup started")
  7440. def stop_auth_cleanup() -> None:
  7441. global _auth_cleanup_task
  7442. if _auth_cleanup_task:
  7443. _auth_cleanup_task.cancel()
  7444. _auth_cleanup_task = None
  7445. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  7446. @asynccontextmanager
  7447. async def lifespan(app: FastAPI):
  7448. # Startup
  7449. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  7450. # anything else can spawn tasks that might trip it.
  7451. from backend.app.core.asyncio_handlers import install_proactor_reset_filter
  7452. install_proactor_reset_filter()
  7453. await init_db()
  7454. # Browser download tokens expire after five minutes. Remove abandoned
  7455. # prepared ZIPs at startup as well as before each new preparation so a
  7456. # quiet appliance cannot retain an unusable bundle indefinitely.
  7457. try:
  7458. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  7459. await prune_stale_printer_file_bundles()
  7460. except Exception as exc:
  7461. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  7462. # After migrations, so the is_env_managed column exists. Never raises --
  7463. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  7464. # startup (see apply_env_oidc_provider).
  7465. from backend.app.core.oidc_env import apply_env_oidc_provider
  7466. async with async_session() as oidc_db:
  7467. await apply_env_oidc_provider(oidc_db)
  7468. # Close out batches that finished before `completed` was a reachable status
  7469. # (#342). Without this the Batches tab opens on every batch created since
  7470. # the feature shipped, all still marked active. Never blocks startup.
  7471. try:
  7472. from backend.app.services.print_batch import backfill_batch_statuses
  7473. async with async_session() as batch_db:
  7474. await backfill_batch_statuses(batch_db)
  7475. except Exception as exc:
  7476. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  7477. # Register an app-scoped httpx client for Bambu Cloud services so
  7478. # per-request BambuCloudService instances reuse the same connection pool
  7479. # (important for routes like /cloud/filament-info that chain many
  7480. # get_setting_detail calls). The shared client stores no region/token
  7481. # state, so the per-request ownership pattern that fixed the region-bleed
  7482. # bug is preserved.
  7483. import httpx as _httpx
  7484. from backend.app.services.bambu_cloud import set_shared_http_client
  7485. from backend.app.services.makerworld import (
  7486. set_shared_http_client as set_shared_makerworld_http_client,
  7487. )
  7488. from backend.app.services.orca_cloud import (
  7489. set_shared_http_client as set_shared_orca_http_client,
  7490. )
  7491. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  7492. set_shared_http_client(_shared_cloud_http_client)
  7493. # Reuse the same connection pool for MakerWorld — different host, same
  7494. # keep-alive pool saves a TLS handshake per request.
  7495. set_shared_makerworld_http_client(_shared_cloud_http_client)
  7496. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  7497. # each spun up (and never closed) its own client, leaking sockets.
  7498. set_shared_orca_http_client(_shared_cloud_http_client)
  7499. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  7500. # This can happen when a print was cancelled mid-print on versions before this fix.
  7501. try:
  7502. async with async_session() as db:
  7503. from backend.app.models.print_queue import PrintQueueItem
  7504. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  7505. aborted_items = result.scalars().all()
  7506. if aborted_items:
  7507. for item in aborted_items:
  7508. item.status = "cancelled"
  7509. await db.commit()
  7510. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  7511. except Exception as e:
  7512. logging.warning("Failed to fix aborted queue items: %s", e)
  7513. # Restore debug logging state from previous session
  7514. await init_debug_logging()
  7515. # Set up printer manager callbacks
  7516. loop = asyncio.get_event_loop()
  7517. printer_manager.set_event_loop(loop)
  7518. printer_manager.set_status_change_callback(on_printer_status_change)
  7519. printer_manager.set_print_start_callback(on_print_start)
  7520. printer_manager.set_print_complete_callback(on_print_complete)
  7521. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  7522. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  7523. printer_manager.set_ams_change_callback(on_ams_change)
  7524. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  7525. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  7526. await printer_manager.load_awaiting_plate_clear_from_db()
  7527. # Layer change callback for external camera timelapse
  7528. async def on_layer_change(printer_id: int, layer_num: int):
  7529. """Capture timelapse frame on layer change + first layer notification."""
  7530. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  7531. await tl_layer_change(printer_id, layer_num)
  7532. # #1867: bank a recent in-print frame so the finish-photo path has a
  7533. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  7534. # #2547 added `on_print_progress` as a second driver — this one alone
  7535. # stops firing once the final layer begins.
  7536. await _maybe_bank_inprint_frame(printer_id, layer_num)
  7537. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  7538. # Gate on actual printing state — Bambu firmware ticks layer_num during
  7539. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  7540. # nozzle clean), so a bare layer_num check can fire minutes before the
  7541. # first real extrusion. We require gcode_state == RUNNING and
  7542. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  7543. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  7544. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  7545. # edge fires later; _first_layer_notified stays clear until we actually send
  7546. # so a deferred re-evaluation can win. See issue #1837.
  7547. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  7548. client = printer_manager.get_client(printer_id)
  7549. state = client.state if client else None
  7550. if not state or state.state != "RUNNING":
  7551. return
  7552. if state.mc_print_sub_stage not in (None, 0):
  7553. return
  7554. _first_layer_notified[printer_id] = True
  7555. try:
  7556. async with async_session() as db:
  7557. from backend.app.models.printer import Printer
  7558. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7559. printer = result.scalar_one_or_none()
  7560. if not printer:
  7561. return
  7562. printer_name = printer.name
  7563. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  7564. total_layers = state.total_layers if state else 0
  7565. image_data = await _capture_snapshot_for_notification(
  7566. printer_id, printer, logging.getLogger(__name__)
  7567. )
  7568. await notification_service.on_first_layer_complete(
  7569. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  7570. )
  7571. except Exception as e:
  7572. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  7573. printer_manager.set_layer_change_callback(on_layer_change)
  7574. async def on_print_progress(printer_id: int, percent: int):
  7575. """#2547: keep the in-print frame bank fresh through the final layer.
  7576. `on_layer_change` stops the moment the last layer starts, which on the
  7577. H2C capture that closed #2547 left the bank stale for the three minutes
  7578. that layer took. Progress is the only field that keeps advancing there,
  7579. and it freezes before the End G-code runs — so banking on it stays
  7580. inside the print and never sees a swapped plate.
  7581. """
  7582. client = printer_manager.get_client(printer_id)
  7583. state = client.state if client else None
  7584. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  7585. printer_manager.set_print_progress_callback(on_print_progress)
  7586. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  7587. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  7588. waiter = _bed_cool_waiters.get(printer_id)
  7589. if not waiter:
  7590. return
  7591. threshold = waiter["threshold"]
  7592. if bed_temp > threshold:
  7593. return
  7594. # Bed is at or below threshold — fire notification and remove waiter
  7595. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  7596. if not waiter_info:
  7597. return # Another callback already handled it
  7598. bed_cool_logger = logging.getLogger(__name__)
  7599. bed_cool_logger.info(
  7600. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  7601. bed_temp,
  7602. printer_id,
  7603. threshold,
  7604. )
  7605. try:
  7606. printer_info = printer_manager.get_printer(printer_id)
  7607. p_name = printer_info.name if printer_info else "Unknown"
  7608. async with async_session() as db:
  7609. await notification_service.on_bed_cooled(
  7610. printer_id=printer_id,
  7611. printer_name=p_name,
  7612. bed_temp=bed_temp,
  7613. threshold=threshold,
  7614. filename=waiter_info["filename"],
  7615. db=db,
  7616. )
  7617. except Exception as e:
  7618. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  7619. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  7620. async def on_drying_complete(printer_id: int, ams_id: int):
  7621. """Smart-plug auto-off-after-drying trigger (#1349).
  7622. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  7623. manager walks all plugs linked to this printer and turns off only
  7624. the ones with ``auto_off_after_drying`` enabled, after their
  7625. per-plug delay. Multiple AMS units finishing close together (e.g. a
  7626. dual-AMS dry that ends within the same MQTT push) call this once
  7627. per unit — the manager's ``_cancel_pending_off`` collapses
  7628. repeated scheduling on the same plug to one timer, so duplicate
  7629. fires are safe.
  7630. """
  7631. try:
  7632. async with async_session() as db:
  7633. await smart_plug_manager.on_drying_complete(printer_id, db)
  7634. except Exception as e:
  7635. logging.getLogger(__name__).warning(
  7636. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  7637. printer_id,
  7638. ams_id,
  7639. e,
  7640. )
  7641. printer_manager.set_drying_complete_callback(on_drying_complete)
  7642. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  7643. """Surface the read-back result of a spool assignment to the UI (#2582).
  7644. The MQTT client confirms (or fails to confirm) that the tray telemetry
  7645. echoed back the filament id we pushed. We relay that as a websocket
  7646. event so the frontend can toast "loaded" / "assignment didn't take"
  7647. instead of the historic silent fire-and-forget, which made the
  7648. AMS→Studio hand-off feel random to users.
  7649. """
  7650. try:
  7651. from backend.app.services.spool_assignment_notifications import (
  7652. _slot_label_from_global_tray,
  7653. )
  7654. if ams_id == 255:
  7655. global_id = 254 + tray_id
  7656. elif ams_id >= 128:
  7657. global_id = ams_id
  7658. else:
  7659. global_id = ams_id * 4 + tray_id
  7660. slot_label = _slot_label_from_global_tray(global_id)
  7661. printer_info = printer_manager.get_printer(printer_id)
  7662. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7663. await ws_manager.broadcast(
  7664. {
  7665. "type": "spool_assignment_verified",
  7666. "printer_id": printer_id,
  7667. "printer_name": printer_name,
  7668. "ams_id": ams_id,
  7669. "tray_id": tray_id,
  7670. "slot": slot_label,
  7671. "verified": verified,
  7672. # Present on success: False means the filament setting landed
  7673. # but the K-profile (cali_idx) did not — the reporter's exact
  7674. # "loaded but no flow profile" symptom.
  7675. "kprofile_applied": detail.get("kprofile_applied", True),
  7676. # Present on failure: whether any tray telemetry was seen in
  7677. # the window (distinguishes "printer silent" from "printer
  7678. # stored something else").
  7679. "saw_tray": detail.get("saw_tray", False),
  7680. }
  7681. )
  7682. except Exception as e:
  7683. logging.getLogger(__name__).warning(
  7684. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  7685. printer_id,
  7686. ams_id,
  7687. tray_id,
  7688. e,
  7689. )
  7690. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  7691. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  7692. """Persist a mid-print tray change for completion-time attribution.
  7693. AMS filament backup switches trays without telling the slicer, so the
  7694. tray-change log is the only record of which spool fed which layers.
  7695. Keeping it only in memory meant a restart mid-print charged everything
  7696. to the tray that finished the job.
  7697. """
  7698. try:
  7699. from backend.app.services.usage_tracker import record_tray_change
  7700. async with async_session() as db:
  7701. await record_tray_change(db, printer_id, tray_global, layer_num)
  7702. except Exception as e:
  7703. logging.getLogger(__name__).warning(
  7704. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  7705. printer_id,
  7706. tray_global,
  7707. layer_num,
  7708. e,
  7709. )
  7710. printer_manager.set_tray_change_callback(on_tray_change)
  7711. # Initialize MQTT relay from settings
  7712. async with async_session() as db:
  7713. from backend.app.api.routes.settings import get_setting
  7714. mqtt_settings = {
  7715. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  7716. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  7717. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  7718. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  7719. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  7720. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  7721. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  7722. }
  7723. await mqtt_relay.configure(mqtt_settings)
  7724. # Restore MQTT smart plug subscriptions
  7725. if mqtt_settings.get("mqtt_enabled"):
  7726. from backend.app.models.smart_plug import SmartPlug
  7727. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  7728. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  7729. mqtt_plugs = result.scalars().all()
  7730. restored = 0
  7731. for plug in mqtt_plugs:
  7732. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  7733. restored += 1
  7734. if restored:
  7735. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  7736. # Connect to all active printers
  7737. async with async_session() as db:
  7738. await init_printer_connections(db)
  7739. # Auto-connect to Spoolman if enabled
  7740. async with async_session() as db:
  7741. from backend.app.api.routes.settings import get_setting
  7742. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  7743. spoolman_url = await get_setting(db, "spoolman_url")
  7744. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  7745. try:
  7746. client = await init_spoolman_client(spoolman_url)
  7747. if await client.health_check():
  7748. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  7749. # Ensure the 'tag' extra field exists for RFID/UUID storage
  7750. field_ok = await client.ensure_tag_extra_field()
  7751. if not field_ok:
  7752. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  7753. # Register the BambuStudio slicer-preset fields used by the
  7754. # spool-edit / assign flow. Spoolman rejects PATCHes with
  7755. # unknown extra keys, so these must exist before any update
  7756. # that touches them.
  7757. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  7758. if not await client.ensure_extra_field(field_name):
  7759. logging.warning(
  7760. "Spoolman extra field %r registration failed — "
  7761. "spool slicer-preset edits will return 502",
  7762. field_name,
  7763. )
  7764. else:
  7765. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  7766. except Exception as e:
  7767. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  7768. # Start the print scheduler
  7769. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  7770. # Start the smart plug scheduler for time-based on/off
  7771. smart_plug_manager.start_scheduler()
  7772. # Start the Home Assistant sensor poller (#1148)
  7773. ha_sensor_manager.start()
  7774. location_ha_sensor_manager.start()
  7775. # Resume any pending auto-offs that were interrupted by restart
  7776. await smart_plug_manager.resume_pending_auto_offs()
  7777. # Start the notification digest scheduler
  7778. notification_service.start_digest_scheduler()
  7779. # Start the GitHub backup scheduler
  7780. await github_backup_service.start_scheduler()
  7781. # Start the local backup scheduler
  7782. await local_backup_service.start_scheduler()
  7783. await obico_detection_service.start()
  7784. # Start the library trash sweeper (#1008)
  7785. await library_trash_service.start_scheduler()
  7786. # Start the archive auto-purge sweeper (#1008 follow-up)
  7787. await archive_purge_service.start_scheduler()
  7788. # Start AMS history recording
  7789. start_ams_history_recording()
  7790. # Start printer sensor (nozzle / bed / chamber) history recording
  7791. start_printer_sensor_history_recording()
  7792. # Start printer runtime tracking
  7793. start_runtime_tracking()
  7794. # Start SpoolBuddy device watchdog
  7795. start_spoolbuddy_watchdog()
  7796. # Start camera stream orphan cleanup
  7797. start_camera_cleanup()
  7798. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  7799. start_connection_watchdog()
  7800. # One-shot sweep for timelapse session directories orphaned by a crash
  7801. # or restart that happened mid-print (in-memory session tracking can't
  7802. # survive that, and nothing else reaps the leftover frames/output file)
  7803. try:
  7804. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  7805. removed = cleanup_orphaned_timelapse_sessions()
  7806. if removed:
  7807. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  7808. except Exception as e:
  7809. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  7810. # Start expected-print TTL eviction (prevents memory leak when prints are
  7811. # registered but on_print_start never fires)
  7812. start_expected_prints_cleanup()
  7813. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  7814. start_auth_cleanup()
  7815. from backend.app.services.printer_media import start_printer_download_cleanup
  7816. start_printer_download_cleanup()
  7817. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  7818. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  7819. from backend.app.services.loop_watchdog import start_loop_watchdog
  7820. start_loop_watchdog()
  7821. # Initialize virtual printer manager and sync from DB
  7822. from backend.app.services.virtual_printer import virtual_printer_manager
  7823. virtual_printer_manager.set_session_factory(async_session)
  7824. virtual_printer_manager.set_printer_manager(printer_manager)
  7825. try:
  7826. await virtual_printer_manager.sync_from_db()
  7827. logging.info("Virtual printer manager synced from database")
  7828. except Exception as e:
  7829. logging.warning("Failed to sync virtual printers: %s", e)
  7830. yield
  7831. # Shutdown
  7832. print_scheduler.stop()
  7833. smart_plug_manager.stop_scheduler()
  7834. ha_sensor_manager.stop()
  7835. location_ha_sensor_manager.stop()
  7836. notification_service.stop_digest_scheduler()
  7837. github_backup_service.stop_scheduler()
  7838. local_backup_service.stop_scheduler()
  7839. library_trash_service.stop_scheduler()
  7840. archive_purge_service.stop_scheduler()
  7841. obico_detection_service.stop()
  7842. stop_ams_history_recording()
  7843. stop_printer_sensor_history_recording()
  7844. stop_runtime_tracking()
  7845. stop_spoolbuddy_watchdog()
  7846. stop_camera_cleanup()
  7847. stop_connection_watchdog()
  7848. from backend.app.services.loop_watchdog import stop_loop_watchdog
  7849. stop_loop_watchdog()
  7850. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  7851. # cleanly rather than waiting on a queue that nothing will ever fill.
  7852. try:
  7853. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  7854. await shutdown_all_broadcasters()
  7855. except Exception as e:
  7856. logging.warning("Failed to shut down camera broadcasters: %s", e)
  7857. stop_expected_prints_cleanup()
  7858. stop_auth_cleanup()
  7859. from backend.app.services.printer_media import stop_printer_download_cleanup
  7860. await stop_printer_download_cleanup()
  7861. printer_manager.disconnect_all()
  7862. await close_spoolman_client()
  7863. # Stop all virtual printer services
  7864. await virtual_printer_manager.stop_all()
  7865. await mqtt_smart_plug_service.disconnect(timeout=2)
  7866. await mqtt_relay.disconnect(timeout=2)
  7867. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  7868. set_shared_http_client(None)
  7869. set_shared_makerworld_http_client(None)
  7870. set_shared_orca_http_client(None)
  7871. await _shared_cloud_http_client.aclose()
  7872. # Checkpoint WAL (SQLite only) and close all database connections
  7873. from backend.app.core.db_dialect import is_sqlite
  7874. if is_sqlite():
  7875. try:
  7876. async with engine.begin() as conn:
  7877. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  7878. logging.info("WAL checkpoint completed")
  7879. except Exception as e:
  7880. logging.warning("WAL checkpoint failed: %s", e)
  7881. await engine.dispose()
  7882. app = FastAPI(
  7883. title=app_settings.app_name,
  7884. description="Archive and manage Bambu Lab 3MF files",
  7885. version=APP_VERSION,
  7886. lifespan=lifespan,
  7887. )
  7888. # =============================================================================
  7889. # Authentication Middleware - Secures ALL API routes by default
  7890. # =============================================================================
  7891. # Public routes that don't require authentication even when auth is enabled
  7892. PUBLIC_API_ROUTES = {
  7893. # Auth routes needed before/during login
  7894. "/api/v1/auth/status",
  7895. "/api/v1/auth/login",
  7896. "/api/v1/auth/setup", # Needed for initial setup and recovery
  7897. # Advanced auth status needed for login page
  7898. "/api/v1/auth/advanced-auth/status",
  7899. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  7900. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  7901. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  7902. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  7903. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  7904. # OIDC routes that must be reachable without a JWT
  7905. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  7906. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  7907. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  7908. # Version check for updates (no sensitive data)
  7909. "/api/v1/updates/version",
  7910. # Metrics endpoint handles its own prometheus_token authentication
  7911. "/api/v1/metrics",
  7912. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  7913. # this BEFORE a JWT is available to pick up the firstboot wizard's
  7914. # hostname / timezone / locale and the chrony NTP-gate state. The
  7915. # response contains user-set defaults and a public sync flag — no
  7916. # secrets. Without this entry the global auth middleware returns 401
  7917. # before the route handler runs, regardless of the route's own
  7918. # "no auth required" intent.
  7919. "/api/v1/system/appliance",
  7920. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  7921. # authenticates with a long-lived ``camwall``-scoped token in the query
  7922. # string — exactly like the camera streams two lists below, and for the same
  7923. # reason (no header to put a JWT in). "Public" here only means the middleware
  7924. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  7925. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  7926. # plain ``camera_stream`` token does NOT open this door.
  7927. "/api/v1/camwall/printers",
  7928. }
  7929. # Route prefixes that are public (for routes with dynamic segments)
  7930. PUBLIC_API_PREFIXES = [
  7931. # WebSocket connections handle their own auth
  7932. "/api/v1/ws",
  7933. # OIDC authorize redirects — include provider_id in path
  7934. "/api/v1/auth/oidc/authorize/",
  7935. ]
  7936. # Route patterns that are public (read-only display data)
  7937. # These are checked with "in path" - needed because browsers load images/videos
  7938. # via <img src> and <video src> which don't include Authorization headers
  7939. PUBLIC_API_PATTERNS = [
  7940. # Thumbnails
  7941. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  7942. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  7943. # Images and media
  7944. "/photos/", # /archives/{id}/photos/{filename}
  7945. "/project-image/", # /archives/{id}/project-image/{path}
  7946. "/qrcode", # /archives/{id}/qrcode
  7947. "/timelapse", # /archives/{id}/timelapse (video)
  7948. "/cover", # /printers/{id}/cover
  7949. "/icon", # /external-links/{id}/icon
  7950. # Camera (streams loaded via <img> tag)
  7951. "/camera/stream", # /printers/{id}/camera/stream
  7952. "/camera/snapshot", # /printers/{id}/camera/snapshot
  7953. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  7954. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  7955. # string (same reasoning as the camera streams above — no header to carry a
  7956. # JWT). "Public" only means the middleware steps aside; the route still runs
  7957. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  7958. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  7959. "/overlay-status", # /printers/{id}/overlay-status
  7960. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  7961. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  7962. # download token in the URL path instead.
  7963. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  7964. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  7965. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  7966. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  7967. ]
  7968. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  7969. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  7970. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  7971. Format: comma-separated list of ``scheme://host[:port]`` origins.
  7972. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  7973. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  7974. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  7975. Invalid entries are dropped with a warning rather than failing startup, so
  7976. a typo in one origin doesn't take the whole deployment down.
  7977. """
  7978. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  7979. if not raw:
  7980. return ()
  7981. valid: list[str] = []
  7982. for item in raw.split(","):
  7983. candidate = item.strip()
  7984. if not candidate:
  7985. continue
  7986. try:
  7987. parsed = urlparse(candidate)
  7988. except ValueError as e:
  7989. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  7990. continue
  7991. if parsed.scheme not in ("http", "https"):
  7992. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  7993. continue
  7994. if not parsed.netloc:
  7995. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  7996. continue
  7997. if parsed.path and parsed.path != "/":
  7998. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  7999. continue
  8000. if parsed.query or parsed.fragment:
  8001. _security_headers_logger.warning(
  8002. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  8003. )
  8004. continue
  8005. if "*" in parsed.netloc:
  8006. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  8007. continue
  8008. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  8009. if valid:
  8010. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  8011. return tuple(valid)
  8012. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  8013. def _frame_ancestors(default_value: str) -> str:
  8014. """Compose the ``frame-ancestors`` CSP directive (#1191).
  8015. ``default_value`` is the strict directive used when the operator has not
  8016. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  8017. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  8018. Settings URL builder's preview). When trusted origins
  8019. are configured, ``'self'`` is always included so same-origin embedding never
  8020. breaks even if an operator forgets to add their own origin to the list.
  8021. """
  8022. if _TRUSTED_FRAME_ORIGINS:
  8023. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  8024. return f"frame-ancestors {default_value};"
  8025. @app.middleware("http")
  8026. async def security_headers_middleware(request, call_next):
  8027. """Add standard HTTP security headers to every response."""
  8028. # Per-request nonce stamped into `script-src` (#1460). On its own this
  8029. # changes nothing for Bambuddy's own pages — index.html has no inline
  8030. # scripts since the SW registration moved to /sw-register.js. The reason
  8031. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  8032. # script injected into the HTML on the edge, with a fresh hash on every
  8033. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  8034. # it clones the same nonce onto its injected <script>, and the inline
  8035. # script passes the policy without us needing 'unsafe-inline'. See
  8036. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  8037. csp_nonce = secrets.token_urlsafe(16)
  8038. response = await call_next(request)
  8039. response.headers["X-Content-Type-Options"] = "nosniff"
  8040. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  8041. # browsers honour CSP frame-ancestors instead, and the legacy
  8042. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  8043. # When operators have explicitly allowlisted trusted frame origins (#1191
  8044. # — typically Home Assistant on a different port), drop X-Frame-Options
  8045. # and let the CSP-side frame-ancestors directive govern embedding.
  8046. if not _TRUSTED_FRAME_ORIGINS:
  8047. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  8048. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  8049. # Content-Security-Policy for the React SPA.
  8050. # Notes:
  8051. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  8052. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  8053. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  8054. # - media-src blob:: timelapse video player uses Blob URLs.
  8055. # - font-src data:: some icon fonts are embedded as data URIs.
  8056. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  8057. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  8058. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  8059. # default CSP would render a blank page.
  8060. response.headers["Content-Security-Policy"] = (
  8061. "default-src 'self'; "
  8062. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  8063. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  8064. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  8065. "connect-src 'self'; "
  8066. "font-src 'self' data: https://fonts.gstatic.com; "
  8067. "worker-src 'self' blob:; "
  8068. "object-src 'none'; "
  8069. "base-uri 'self'; " + _frame_ancestors("'none'")
  8070. )
  8071. else:
  8072. # The streaming overlay is embedded same-origin by the URL builder's
  8073. # preview in Settings (#1422), so this branch allows 'self'.
  8074. # Embedding from anywhere else is still refused: 'self'
  8075. # only permits a framer on this origin, which is Bambuddy's own UI, so
  8076. # a clickjacking page on another host is blocked exactly as before.
  8077. # (The overlay draws status over a camera feed and its only interactive
  8078. # element is the logo link, so there is nothing to bait a click into
  8079. # even from a same-origin framer.) Cross-origin embedding of the
  8080. # overlay — Home Assistant on another port — remains what
  8081. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  8082. # allowlist in.
  8083. embeddable_same_origin = request.url.path.startswith("/overlay/")
  8084. response.headers["Content-Security-Policy"] = (
  8085. "default-src 'self'; "
  8086. f"script-src 'self' 'nonce-{csp_nonce}'; "
  8087. "style-src 'self' 'unsafe-inline'; "
  8088. "img-src 'self' data: blob:; "
  8089. "media-src 'self' blob:; "
  8090. "connect-src 'self' ws: wss:; "
  8091. "font-src 'self' data:; "
  8092. "object-src 'none'; "
  8093. "base-uri 'self'; "
  8094. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  8095. )
  8096. if request.url.scheme == "https":
  8097. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  8098. return response
  8099. @app.middleware("http")
  8100. async def auth_middleware(request, call_next):
  8101. """Enforce authentication on all API routes when auth is enabled.
  8102. This middleware provides defense-in-depth by checking auth at the API gateway level,
  8103. regardless of whether individual routes have auth dependencies.
  8104. """
  8105. from starlette.responses import JSONResponse
  8106. path = request.url.path
  8107. # Only apply to API routes
  8108. if not path.startswith("/api/"):
  8109. return await call_next(request)
  8110. # Allow public routes
  8111. if path in PUBLIC_API_ROUTES:
  8112. return await call_next(request)
  8113. # Allow public prefixes
  8114. for prefix in PUBLIC_API_PREFIXES:
  8115. if path.startswith(prefix):
  8116. return await call_next(request)
  8117. # Allow public patterns (read-only display data like thumbnails)
  8118. for pattern in PUBLIC_API_PATTERNS:
  8119. if pattern in path:
  8120. return await call_next(request)
  8121. # Check if auth is enabled. Fail CLOSED on any exception during the
  8122. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  8123. # an attacker who could force a DB exception (e.g. file-descriptor
  8124. # exhaustion via login flood) bypass auth on every protected endpoint.
  8125. try:
  8126. async with async_session() as db:
  8127. from backend.app.core.auth import is_auth_enabled
  8128. auth_enabled = await is_auth_enabled(db)
  8129. if not auth_enabled:
  8130. # Auth disabled, allow all requests
  8131. return await call_next(request)
  8132. except Exception:
  8133. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  8134. return JSONResponse(
  8135. status_code=503,
  8136. content={"detail": "Authentication service temporarily unavailable"},
  8137. )
  8138. # Auth is enabled - require valid token
  8139. auth_header = request.headers.get("Authorization")
  8140. x_api_key = request.headers.get("X-API-Key")
  8141. # Check for API key auth first
  8142. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  8143. # API key authentication - let the request through to be validated by route handler
  8144. # API keys are validated per-route since they have different permission levels
  8145. return await call_next(request)
  8146. # Check for JWT auth
  8147. if not auth_header or not auth_header.startswith("Bearer "):
  8148. return JSONResponse(
  8149. status_code=401,
  8150. content={"detail": "Authentication required"},
  8151. headers={"WWW-Authenticate": "Bearer"},
  8152. )
  8153. # Validate JWT token
  8154. import jwt
  8155. try:
  8156. from backend.app.core.auth import (
  8157. ALGORITHM,
  8158. SECRET_KEY,
  8159. _is_token_fresh,
  8160. get_user_by_username,
  8161. is_jti_revoked,
  8162. )
  8163. token = auth_header.replace("Bearer ", "")
  8164. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  8165. username = payload.get("sub")
  8166. if not username:
  8167. raise ValueError("No username in token")
  8168. jti = payload.get("jti")
  8169. if not jti:
  8170. raise ValueError("No jti in token")
  8171. iat = payload.get("iat")
  8172. # Verify user exists, is active, and token is still fresh (L-R8-A).
  8173. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  8174. # this session so the gateway adds a single pooled checkout, not two (#2572).
  8175. async with async_session() as db:
  8176. if await is_jti_revoked(jti, db):
  8177. return JSONResponse(
  8178. status_code=401,
  8179. content={"detail": "Token has been revoked"},
  8180. headers={"WWW-Authenticate": "Bearer"},
  8181. )
  8182. user = await get_user_by_username(db, username)
  8183. if not user or not user.is_active:
  8184. return JSONResponse(
  8185. status_code=401,
  8186. content={"detail": "User not found or inactive"},
  8187. headers={"WWW-Authenticate": "Bearer"},
  8188. )
  8189. if not _is_token_fresh(iat, user):
  8190. return JSONResponse(
  8191. status_code=401,
  8192. content={"detail": "Token no longer valid"},
  8193. headers={"WWW-Authenticate": "Bearer"},
  8194. )
  8195. except jwt.ExpiredSignatureError:
  8196. return JSONResponse(
  8197. status_code=401,
  8198. content={"detail": "Token has expired"},
  8199. headers={"WWW-Authenticate": "Bearer"},
  8200. )
  8201. except (jwt.InvalidTokenError, ValueError, Exception):
  8202. return JSONResponse(
  8203. status_code=401,
  8204. content={"detail": "Invalid token"},
  8205. headers={"WWW-Authenticate": "Bearer"},
  8206. )
  8207. return await call_next(request)
  8208. @app.middleware("http")
  8209. async def trace_id_middleware(request, call_next):
  8210. """Stamp every HTTP request with a trace ID and echo it back.
  8211. Decorated AFTER auth_middleware on purpose: Starlette stacks
  8212. @app.middleware decorators LIFO, so the last-decorated runs first
  8213. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  8214. which means auth-middleware log lines (and every line emitted on the
  8215. way down to and back from the route handler) all carry the same
  8216. trace ID. If we put it before auth, auth's logs would be stamped
  8217. with the *previous* request's ID — useless for correlation.
  8218. Honours an inbound ``X-Trace-Id`` header so callers running their
  8219. own tracing can correlate their span IDs with our log lines, but
  8220. only if the value passes the whitelist gate in
  8221. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  8222. rejected (too long, contains control chars, etc.) silently triggers
  8223. a freshly minted server-side ID rather than failing the request.
  8224. The minted (or echoed) ID is set on a ContextVar so that every log
  8225. record emitted during the request — application logs *and* uvicorn's
  8226. access log — carries it via TraceIDFilter, and is also written to
  8227. the ``X-Trace-Id`` response header so clients can pin a server-side
  8228. log search to the exact request they made.
  8229. """
  8230. from backend.app.core.trace import (
  8231. generate_trace_id,
  8232. normalise_inbound_trace_id,
  8233. trace_id_var,
  8234. )
  8235. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  8236. trace_id = inbound if inbound is not None else generate_trace_id()
  8237. token = trace_id_var.set(trace_id)
  8238. try:
  8239. response = await call_next(request)
  8240. finally:
  8241. # Reset the ContextVar so a record emitted in a totally
  8242. # unrelated background task that just happens to inherit this
  8243. # context doesn't keep referencing this request's ID forever.
  8244. # In practice ContextVar.reset is best-effort under asyncio
  8245. # task-spawn semantics, but the cost is one attribute write so
  8246. # we may as well do it.
  8247. trace_id_var.reset(token)
  8248. response.headers["X-Trace-Id"] = trace_id
  8249. return response
  8250. # API routes
  8251. app.include_router(auth.router, prefix=app_settings.api_prefix)
  8252. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  8253. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  8254. app.include_router(users.router, prefix=app_settings.api_prefix)
  8255. app.include_router(groups.router, prefix=app_settings.api_prefix)
  8256. app.include_router(printers.router, prefix=app_settings.api_prefix)
  8257. app.include_router(archives.router, prefix=app_settings.api_prefix)
  8258. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  8259. app.include_router(finance.router, prefix=app_settings.api_prefix)
  8260. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  8261. app.include_router(labels.router, prefix=app_settings.api_prefix)
  8262. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  8263. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  8264. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  8265. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  8266. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  8267. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  8268. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  8269. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  8270. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  8271. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  8272. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  8273. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  8274. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  8275. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  8276. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  8277. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  8278. app.include_router(updates.router, prefix=app_settings.api_prefix)
  8279. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  8280. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  8281. app.include_router(camera.router, prefix=app_settings.api_prefix)
  8282. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  8283. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  8284. app.include_router(projects.router, prefix=app_settings.api_prefix)
  8285. app.include_router(library.router, prefix=app_settings.api_prefix)
  8286. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  8287. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  8288. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  8289. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  8290. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  8291. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  8292. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  8293. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  8294. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  8295. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  8296. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  8297. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  8298. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  8299. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  8300. app.include_router(system.router, prefix=app_settings.api_prefix)
  8301. app.include_router(support.router, prefix=app_settings.api_prefix)
  8302. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  8303. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  8304. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  8305. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  8306. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  8307. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  8308. app.include_router(obico.router, prefix=app_settings.api_prefix)
  8309. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  8310. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  8311. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  8312. # Serve static files (React build)
  8313. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  8314. app.mount(
  8315. "/assets",
  8316. StaticFiles(directory=app_settings.static_dir / "assets"),
  8317. name="assets",
  8318. )
  8319. if (app_settings.static_dir / "img").exists():
  8320. app.mount(
  8321. "/img",
  8322. StaticFiles(directory=app_settings.static_dir / "img"),
  8323. name="img",
  8324. )
  8325. if (app_settings.static_dir / "icons").exists():
  8326. app.mount(
  8327. "/icons",
  8328. StaticFiles(directory=app_settings.static_dir / "icons"),
  8329. name="icons",
  8330. )
  8331. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  8332. # falls through to the SPA catch-all and returns index.html, which the
  8333. # browser's font sanitizer rejects ("downloadable font: rejected by
  8334. # sanitizer").
  8335. if (app_settings.static_dir / "fonts").exists():
  8336. app.mount(
  8337. "/fonts",
  8338. StaticFiles(directory=app_settings.static_dir / "fonts"),
  8339. name="fonts",
  8340. )
  8341. @app.get("/")
  8342. async def serve_frontend():
  8343. """Serve the React frontend."""
  8344. index_file = app_settings.static_dir / "index.html"
  8345. if index_file.exists():
  8346. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  8347. return {
  8348. "message": "Bambuddy API",
  8349. "docs": "/docs",
  8350. "frontend": "Build and place React app in /static directory",
  8351. }
  8352. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  8353. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  8354. # forever, but the HTML wrapping it is the only file that knows which hash
  8355. # is current. Without explicit cache-control headers Chromium decides
  8356. # heuristically (typically 10% of the time since Last-Modified) and on
  8357. # long-running kiosks happily serves stale HTML across browser restarts.
  8358. # That stale HTML references an old bundle hash, the old bundle is also
  8359. # in the disk cache, and the user ends up running pre-update JS forever
  8360. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  8361. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  8362. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  8363. @app.get("/health")
  8364. async def health_check():
  8365. """Health check endpoint."""
  8366. return {"status": "healthy"}
  8367. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  8368. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  8369. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  8370. # in deployment debugging.
  8371. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  8372. async def serve_manifest():
  8373. """Serve PWA manifest."""
  8374. manifest_file = app_settings.static_dir / "manifest.json"
  8375. if manifest_file.exists():
  8376. return FileResponse(manifest_file, media_type="application/manifest+json")
  8377. return {"error": "Manifest not found"}
  8378. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  8379. async def serve_service_worker():
  8380. """Serve service worker."""
  8381. sw_file = app_settings.static_dir / "sw.js"
  8382. if sw_file.exists():
  8383. return FileResponse(
  8384. sw_file,
  8385. media_type="application/javascript",
  8386. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  8387. )
  8388. return {"error": "Service worker not found"}
  8389. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  8390. async def serve_sw_register():
  8391. """Serve the service-worker registration bootstrap script.
  8392. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  8393. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  8394. """
  8395. reg_file = app_settings.static_dir / "sw-register.js"
  8396. if reg_file.exists():
  8397. return FileResponse(reg_file, media_type="application/javascript")
  8398. return {"error": "sw-register.js not found"}
  8399. # ── GCode viewer static files ────────────────────────────────────────────────
  8400. # Catch-all route for React Router (must be last)
  8401. @app.get("/{full_path:path}")
  8402. async def serve_spa(full_path: str):
  8403. """Serve React app for client-side routing."""
  8404. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  8405. if full_path.startswith("api/"):
  8406. from fastapi import HTTPException
  8407. raise HTTPException(status_code=404, detail="Not found")
  8408. index_file = app_settings.static_dir / "index.html"
  8409. if index_file.exists():
  8410. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  8411. return {"error": "Frontend not built"}