main.py 629 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import re
  8. import secrets
  9. import shutil
  10. import time
  11. from contextlib import asynccontextmanager
  12. from datetime import datetime, timedelta, timezone
  13. from logging.handlers import RotatingFileHandler
  14. from pathlib import Path, PurePosixPath
  15. from typing import cast
  16. from urllib.parse import urlparse
  17. from fastapi import FastAPI
  18. from fastapi.encoders import jsonable_encoder
  19. from fastapi.exceptions import RequestValidationError
  20. from fastapi.responses import FileResponse, JSONResponse
  21. from fastapi.staticfiles import StaticFiles
  22. from sqlalchemy import delete, func, inspect as sa_inspect, or_, select, text, update
  23. from sqlalchemy.engine import CursorResult
  24. from sqlalchemy.exc import IntegrityError
  25. from sqlalchemy.orm.exc import StaleDataError
  26. from backend.app.api.routes import (
  27. ams_history,
  28. announcements,
  29. api_keys,
  30. archive_purge,
  31. archives,
  32. auth,
  33. bug_report,
  34. bulk,
  35. camera,
  36. camwall,
  37. cloud,
  38. connected_apps,
  39. discovery,
  40. external_links,
  41. filaments,
  42. finance,
  43. firmware,
  44. github_backup,
  45. groups,
  46. ha_sensors,
  47. inventory,
  48. kprofiles,
  49. labels,
  50. library,
  51. library_tags,
  52. library_trash,
  53. library_variants,
  54. local_backup,
  55. local_presets,
  56. location_ha_sensors,
  57. maintenance,
  58. makerworld,
  59. manyfold,
  60. metrics,
  61. mfa,
  62. notification_templates,
  63. notifications,
  64. obico,
  65. orca_cloud,
  66. overlay_branding,
  67. pending_uploads,
  68. pipeline_runs,
  69. print_log,
  70. print_queue,
  71. printer_locations,
  72. printer_sensor_history,
  73. printers,
  74. projects,
  75. scheduled_dryings,
  76. settings as settings_routes,
  77. slice_jobs,
  78. slicer_pipelines,
  79. slicer_presets,
  80. smart_plugs,
  81. sponsor_prompt,
  82. spoolbuddy,
  83. spoolman,
  84. spoolman_inventory,
  85. support,
  86. system,
  87. updates,
  88. user_notifications,
  89. users,
  90. virtual_printers,
  91. webhook,
  92. websocket,
  93. )
  94. from backend.app.api.routes.maintenance import (
  95. _get_printer_maintenance_internal,
  96. ensure_default_types,
  97. maintenance_alert_values,
  98. )
  99. from backend.app.api.routes.support import init_debug_logging
  100. from backend.app.core.config import APP_VERSION, settings as app_settings
  101. from backend.app.core.database import async_session, engine, init_db
  102. from backend.app.core.static_assets import AssetStaticFiles
  103. from backend.app.core.tasks import spawn_background_task
  104. from backend.app.core.websocket import ws_manager
  105. from backend.app.services import kprofile_drift, pause_eta, print_dispatch_context, slot_unlink_grace
  106. from backend.app.services.ams_assignment_lock import get_ams_assignment_lock
  107. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  108. from backend.app.services.archive_cost_estimate import (
  109. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  110. settle_archive_cost_estimate as _settle_archive_cost_estimate,
  111. )
  112. from backend.app.services.archive_purge import archive_purge_service
  113. from backend.app.services.bambu_ftp import (
  114. RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  115. FileNotOnPrinterError,
  116. cache_3mf_download,
  117. clear_3mf_cache,
  118. download_file_async,
  119. download_file_try_paths_async,
  120. ftps_handshake_blocked,
  121. get_cached_3mf,
  122. get_ftp_retry_settings,
  123. normalize_3mf_name,
  124. with_ftp_retry,
  125. )
  126. from backend.app.services.bambu_mqtt import PrinterState
  127. from backend.app.services.camera_light import camera_light
  128. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  129. from backend.app.services.github_backup import github_backup_service
  130. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  131. from backend.app.services.library_trash import library_trash_service
  132. from backend.app.services.local_backup import local_backup_service
  133. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  134. from backend.app.services.mqtt_relay import mqtt_relay
  135. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  136. from backend.app.services.notification_service import notification_service
  137. from backend.app.services.notify_live_activities import notify_live_activities
  138. from backend.app.services.notify_widgets import notify_widgets
  139. from backend.app.services.obico_detection import obico_detection_service
  140. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  141. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  142. from backend.app.services.print_scheduler import scheduler as print_scheduler
  143. from backend.app.services.print_storage import (
  144. REASON_FTP_TRANSFER_FAILED,
  145. REASON_FTPS_COOLOFF,
  146. external_storage_present,
  147. ftp_probe_paths,
  148. print_file_reachable_over_ftp,
  149. )
  150. from backend.app.services.printer_manager import (
  151. init_printer_connections,
  152. parse_plate_id,
  153. printer_manager,
  154. printer_state_to_dict,
  155. resolve_plate_id,
  156. )
  157. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  158. from backend.app.services.slot_nozzle import (
  159. nozzle_diameter_for_extruder,
  160. nozzle_flow_for_extruder,
  161. )
  162. from backend.app.services.smart_plug_manager import smart_plug_manager
  163. from backend.app.services.spool_assignment_notifications import (
  164. notify_missing_spool_assignments_on_print_start,
  165. )
  166. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  167. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  168. from backend.app.services.spoolman_tracking import (
  169. cleanup_tracking as _cleanup_spoolman_tracking,
  170. release_archived_slot_rows as _release_archived_spoolman_slots,
  171. report_usage as _report_spoolman_usage,
  172. store_print_data as _store_spoolman_print_data,
  173. )
  174. from backend.app.services.telegram_reactions import telegram_reaction_poller
  175. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  176. from backend.app.utils.ams_humidity import ams_humidity_percent
  177. from backend.app.utils.filament_types import printer_filament_type
  178. from backend.app.utils.fts_routing import extruder_for_inlet
  179. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  180. from backend.app.utils.print_jobs import is_internal_printer_job
  181. # =============================================================================
  182. # Dependency Check - runs before other imports to give helpful error messages
  183. # =============================================================================
  184. def _start_error_server(missing_packages: list):
  185. """Start a minimal HTTP server to display dependency errors in browser."""
  186. import os
  187. import signal
  188. from http.server import BaseHTTPRequestHandler, HTTPServer
  189. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  190. html = f"""<!DOCTYPE html>
  191. <html>
  192. <head>
  193. <title>Bambuddy - Setup Required</title>
  194. <style>
  195. body {{
  196. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  197. background: #0f172a; color: #e2e8f0;
  198. display: flex; justify-content: center; align-items: center;
  199. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  200. }}
  201. .container {{
  202. background: #1e293b; border-radius: 12px; padding: 40px;
  203. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  204. }}
  205. h1 {{ color: #f87171; margin-bottom: 10px; }}
  206. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  207. .packages {{
  208. background: #0f172a; border-radius: 8px; padding: 20px;
  209. margin: 20px 0; text-align: left;
  210. }}
  211. .packages ul {{ margin: 0; padding-left: 20px; }}
  212. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  213. .command {{
  214. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  215. margin: 15px 0; font-family: monospace; color: #4ade80;
  216. text-align: left; overflow-x: auto;
  217. }}
  218. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  219. </style>
  220. </head>
  221. <body>
  222. <div class="container">
  223. <h1>Setup Required</h1>
  224. <h2>Missing Python packages</h2>
  225. <div class="packages"><ul>{packages_html}</ul></div>
  226. <p>To fix, run this command on your server:</p>
  227. <div class="command">pip install -r requirements.lock</div>
  228. <p>Or if using a virtual environment:</p>
  229. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  230. <p class="note">After installing, restart Bambuddy:<br>
  231. <code>sudo systemctl restart bambuddy</code></p>
  232. </div>
  233. </body>
  234. </html>"""
  235. class ErrorHandler(BaseHTTPRequestHandler):
  236. def do_GET(self):
  237. self.send_response(503)
  238. self.send_header("Content-type", "text/html")
  239. self.end_headers()
  240. self.wfile.write(html.encode())
  241. def log_message(self, format, *args):
  242. print(f"[Error Server] {args[0]}")
  243. port = int(os.environ.get("PORT", 8000))
  244. print(f"\nStarting error server on http://0.0.0.0:{port}")
  245. print("Visit this URL in your browser to see the error details.\n")
  246. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  247. def shutdown(signum, frame):
  248. print("\nShutting down error server...")
  249. raise SystemExit(0)
  250. signal.signal(signal.SIGTERM, shutdown)
  251. signal.signal(signal.SIGINT, shutdown)
  252. server.serve_forever()
  253. def check_dependencies():
  254. """Check that all required packages are installed."""
  255. missing = []
  256. # Map of import name -> package name (for pip install)
  257. required = {
  258. "jwt": "PyJWT",
  259. "fastapi": "fastapi",
  260. "uvicorn": "uvicorn",
  261. "sqlalchemy": "sqlalchemy",
  262. "aiosqlite": "aiosqlite",
  263. "pydantic": "pydantic",
  264. "paho.mqtt": "paho-mqtt",
  265. }
  266. for module, package in required.items():
  267. try:
  268. __import__(module)
  269. except ImportError:
  270. missing.append(package)
  271. if missing:
  272. print("\n" + "=" * 60)
  273. print("ERROR: Missing required Python packages!")
  274. print("=" * 60)
  275. print(f"\nMissing packages: {', '.join(missing)}")
  276. print("\nTo fix, run:")
  277. print(" pip install -r requirements.lock")
  278. print("\nOr if using a virtual environment:")
  279. print(" ./venv/bin/pip install -r requirements.lock")
  280. print("=" * 60 + "\n")
  281. _start_error_server(missing)
  282. check_dependencies()
  283. # =============================================================================
  284. # Import settings first for logging configuration
  285. # Configure logging based on settings
  286. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  287. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  288. log_level = getattr(logging, log_level_str, logging.INFO)
  289. # Trace ID column ([-] when no request scope is active — startup, MQTT
  290. # callbacks, scheduled tasks not chained from a request — so the column
  291. # stays visually aligned and missing values are obvious in grep). See
  292. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  293. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  294. # Create root logger
  295. root_logger = logging.getLogger()
  296. root_logger.setLevel(log_level)
  297. # Trace-ID injection: this filter populates record.trace_id from the
  298. # per-request ContextVar so the format string above can reference it.
  299. # Attached to each HANDLER (not the root logger) because Python's
  300. # logging semantics only invoke a logger's filters on records that
  301. # *originated* at that logger — records propagated up from child
  302. # loggers (every named logger in the app) never trigger root's filter.
  303. # Putting it on the handlers means every record any handler emits gets
  304. # trace_id injected just before the formatter runs, regardless of which
  305. # logger created the record. Without this, the formatter raises
  306. # KeyError on every child-logger record and the record is silently
  307. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  308. # partially" bug we hit. See backend/app/core/trace.py for the
  309. # ContextVar the filter reads.
  310. from backend.app.core.logging_filters import RefusedHeaderRedactFilter
  311. from backend.app.core.response_redaction import RefusedHeaderResponseMask
  312. from backend.app.core.trace import TraceIDFilter
  313. _trace_id_filter = TraceIDFilter()
  314. # Console handler - always enabled
  315. console_handler = logging.StreamHandler()
  316. console_handler.setLevel(log_level)
  317. console_handler.setFormatter(logging.Formatter(log_format))
  318. console_handler.addFilter(_trace_id_filter)
  319. # A refused header's value (often a token) masked before the line is written.
  320. _refused_header_filter = RefusedHeaderRedactFilter()
  321. console_handler.addFilter(_refused_header_filter)
  322. root_logger.addHandler(console_handler)
  323. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  324. """Send uvicorn's own loggers to bambuddy.log as well.
  325. Neither reaches the root handler: uvicorn.access has propagate=False, and
  326. uvicorn.error propagates only to "uvicorn", which has propagate=False.
  327. uvicorn.access is the record of which endpoint changed server state;
  328. uvicorn.error is where an unhandled route error is logged with its
  329. traceback ("Exception in ASGI application").
  330. """
  331. for name in ("uvicorn.access", "uvicorn.error"):
  332. logging.getLogger(name).addHandler(handler)
  333. # File handler - only in production or if explicitly enabled
  334. if app_settings.log_to_file:
  335. log_file = app_settings.log_dir / "bambuddy.log"
  336. file_handler = RotatingFileHandler(
  337. log_file,
  338. maxBytes=app_settings.log_max_bytes,
  339. backupCount=app_settings.log_backup_count,
  340. encoding="utf-8",
  341. )
  342. file_handler.setLevel(log_level)
  343. file_handler.setFormatter(logging.Formatter(log_format))
  344. file_handler.addFilter(_trace_id_filter)
  345. file_handler.addFilter(_refused_header_filter)
  346. root_logger.addHandler(file_handler)
  347. logging.info("Logging to file: %s", log_file)
  348. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  349. # access logger with propagate=False by default, so without this attach
  350. # there is no on-disk record of which endpoint triggered a server-state
  351. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  352. # for exactly this reason. Filtered to write methods only
  353. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  354. # frontend don't churn the rotation window faster than it's useful.
  355. from backend.app.core.logging_filters import (
  356. CancelledPoolNoiseFilter,
  357. WriteRequestsOnlyFilter,
  358. )
  359. _attach_file_handler_to_uvicorn(file_handler)
  360. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  361. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  362. # Uvicorn's access logger has propagate=False (its own default), so the
  363. # root-attached TraceIDFilter never sees these records. Attach a
  364. # second instance directly so HTTP access lines carry the same trace
  365. # ID column as the application logs they correlate with.
  366. uvicorn_access_logger.addFilter(TraceIDFilter())
  367. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  368. # BaseHTTPMiddleware cancelling the inner task scope on client
  369. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  370. # underlying transaction leak; this filter only suppresses the residual
  371. # log records that pre-existing pools still emit during their cleanup.
  372. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  373. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  374. # handler (console included), whether or not file logging is on.
  375. from backend.app.core.logging_filters import ( # noqa: E402
  376. QueryTokenRedactFilter,
  377. ShutdownCancelledRequestFilter,
  378. )
  379. # First, so the traceback of a stream cancelled at shutdown is dropped before
  380. # the filters below render it.
  381. logging.getLogger("uvicorn.error").addFilter(ShutdownCancelledRequestFilter())
  382. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  383. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  384. logging.getLogger(_uvicorn_logger).addFilter(_refused_header_filter)
  385. # These stay at WARNING even in debug mode: at INFO/DEBUG httpx/httpcore log
  386. # full request URLs, and some carry credentials (bot tokens, webhook URLs, API
  387. # keys in the query). Same as the runtime log-level toggle in support.py.
  388. logging.getLogger("httpcore").setLevel(logging.WARNING)
  389. logging.getLogger("httpx").setLevel(logging.WARNING)
  390. # aiosqlite logs every statement with its parameters at DEBUG.
  391. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  392. # Reduce noise from third-party libraries in production
  393. if not app_settings.debug:
  394. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  395. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  396. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  397. # Track active prints: {(printer_id, filename): archive_id}
  398. _active_prints: dict[tuple[int, str], int] = {}
  399. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  400. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  401. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  402. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  403. # instead of running its own grab-now chain when present, so the finish photo
  404. # captures the better-framed pre-bed-drop moment without us having to force
  405. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  406. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  407. #
  408. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  409. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  410. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  411. # bank and the others are not — so the consumer can't tell them apart and
  412. # must not rotate again.
  413. _stage22_finish_frames: dict[int, bytes] = {}
  414. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  415. # `finally` block (whether it captured a frame or not). The consumer in
  416. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  417. # so the FINISH-state fallback path — where moment and completion are dispatched
  418. # back-to-back — doesn't race past the producer with an empty pop, and the
  419. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  420. # grab (Bambu printers allow only one RTSP client at a time).
  421. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  422. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  423. # layer-change and on print-progress advances (#2547) while the model is still
  424. # printing, then consumed by the FINISH-state finish-photo path when the
  425. # dispatcher recorded that it injected End G-code into this print. Bambu
  426. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  427. # plate-swap) has run, so a live grab there would capture the swapped/empty
  428. # plate.
  429. #
  430. # The load-bearing property: both drivers are print telemetry that stops before
  431. # the End G-code executes — no further layer_num increases, and mc_percent
  432. # freezes — so the last banked frame is always the finished print before the
  433. # swap. Anything added as a third driver must hold that same property.
  434. _inprint_frame_bank: dict[int, bytes] = {}
  435. # Monotonic timestamp of the last banked frame per printer — throttles banking
  436. # so tall prints don't add a camera grab on every layer.
  437. _inprint_frame_bank_ts: dict[int, float] = {}
  438. # Minimum seconds between banked frames, except the final object layer which
  439. # always refreshes for the best framing.
  440. _INPRINT_BANK_MIN_INTERVAL = 25.0
  441. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  442. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  443. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  444. # the first connected status update for that connection; transitions back
  445. # to False whenever we observe `state.connected = False` so the next
  446. # reconnect re-arms reconciliation. Keyed by printer_id.
  447. _printer_reconciled_since_connect: dict[int, bool] = {}
  448. # Same edge, same keying, for priming the printer's calibration table exactly
  449. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  450. # is otherwise filled only when someone opens the Profiles page or Configure
  451. # Slot, when a GitHub backup runs, or when the printer happens to answer
  452. # somebody else's query on the report topic. Until then the AMS slot card has
  453. # no K value to show on the printers whose trays carry none of their own
  454. # (#2854 — H2-series report cali_idx and nothing more).
  455. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  456. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  457. # {(printer_id, filename): archive_id}
  458. _expected_prints: dict[tuple[int, str], int] = {}
  459. # Archives of the running prints Bambuddy dispatched itself: adopted from an
  460. # expected print, or found with Bambuddy's dispatch marker. _active_prints holds
  461. # every print on_print_start archived, those started from Bambu Studio, Handy or
  462. # the printer's screen included, so it is no proof of ownership on its own.
  463. _owned_print_archive_ids: set[int] = set()
  464. # What a dispatch registered for its print, keyed (printer_id, archive_id):
  465. # plates of one archive print on two printers at once, each with its own.
  466. # Track AMS mapping for prints: {(printer_id, archive_id): [global_tray_id_per_slot]}
  467. # Used by usage tracker to map 3MF slots to physical AMS trays
  468. _print_ams_mappings: dict[tuple[int, int], list[int]] = {}
  469. # Track cost center selection for the current print run: {(printer_id, archive_id): cost_center_id}
  470. _print_cost_center_ids: dict[tuple[int, int], int] = {}
  471. # Track plate_id for prints from multi-plate 3MFs: {(printer_id, archive_id): plate_id}
  472. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  473. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  474. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  475. # for the queue path. Cleared on print completion or TTL eviction.
  476. _print_plate_ids: dict[tuple[int, int], int] = {}
  477. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  478. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  479. _last_progress_milestone: dict[int, int] = {}
  480. # Track whether first layer complete notification has been sent for current print
  481. _first_layer_notified: dict[int, bool] = {}
  482. # Track whether we already sent a kill-switch stop for the current unauthorized print
  483. _unauthorized_print_kill_sent: set[int] = set()
  484. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  485. # lookup briefly so an unknown active print does not query the database on
  486. # every status frame. A short TTL keeps settings changes responsive.
  487. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  488. _kill_switch_setting_cache: tuple[bool, float] | None = None
  489. # Provider notification started when the kill switch stops a print. The later
  490. # MQTT print-complete callback awaits this task and only sends its regular
  491. # provider notification when the immediate attempt failed.
  492. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  493. # HMS faults already notified, with when each was last seen:
  494. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  495. # fault that flickers beside a held notice was forgotten on every gap and
  496. # notified on every return (#3226). The window is long because the measured
  497. # gaps reach 64 s.
  498. _notified_hms_errors: dict[int, dict[str, float]] = {}
  499. _HMS_CLEAR_GRACE_SECONDS = 600.0
  500. # The print state each printer was last seen in, and the faults recorded before
  501. # it last changed, which are forgotten as soon as they are gone (see
  502. # _take_new_hms_faults).
  503. _hms_print_state: dict[int, str] = {}
  504. _hms_forget_when_gone: dict[int, set[str]] = {}
  505. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  506. # Used for snapshot-diff detection at print completion
  507. _timelapse_baselines: dict[int, set[str]] = {}
  508. # Printers whose baseline above was taken off a card that could not be read,
  509. # so it is empty without the card being empty (#3412).
  510. _timelapse_baselines_unread: set[int] = set()
  511. # Archives whose last run still has work after it completed: the timelapse
  512. # scan and the layer timelapse stitch. Both tell their run from a later one by
  513. # the archive's start time, so a queue dispatch of the same file must not start
  514. # a new run on the archive until they end (_claim_reusable_archive in the
  515. # scheduler). archive_id -> number of such tasks.
  516. _archive_runs_finishing: dict[int, int] = {}
  517. async def _while_run_finishes(archive_id: int, work):
  518. """Run ``work`` with the archive marked as still finishing its last run.
  519. Marked by the caller's spawn already: see ``_mark_run_finishing``."""
  520. try:
  521. return await work
  522. finally:
  523. left = _archive_runs_finishing.get(archive_id, 0) - 1
  524. if left > 0:
  525. _archive_runs_finishing[archive_id] = left
  526. else:
  527. _archive_runs_finishing.pop(archive_id, None)
  528. def _mark_run_finishing(archive_id: int, work):
  529. """``work`` wrapped to keep the archive marked until it ends. Marked now,
  530. before the task starts, so no dispatch between the spawn and its first
  531. step can take the archive."""
  532. _archive_runs_finishing[archive_id] = _archive_runs_finishing.get(archive_id, 0) + 1
  533. return _while_run_finishes(archive_id, work)
  534. # Track printers waiting for bed to cool after print completion.
  535. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  536. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  537. _bed_cool_waiters: dict[int, dict] = {}
  538. # Track printers where the user explicitly stopped the print from the queue UI.
  539. # When on_print_complete fires with status "failed" for these printers we treat it
  540. # as "cancelled" (stopped by user) so the correct notification email is sent.
  541. _user_stopped_printers: set[int] = set()
  542. # Printers whose running print the kill switch stopped. Their completion is a
  543. # cancel with the reason "killSwitch", not the "failed" the printer reports.
  544. _kill_switch_stopped: set[int] = set()
  545. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  546. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  547. # holds the previous observation so we only fire on the True → False edge (a
  548. # False → False repeat doesn't notify; an initial False at startup doesn't
  549. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  550. # holds the per-printer pending asyncio task that fires the notification
  551. # after a debounce window — cancelled if the printer reconnects before the
  552. # window elapses, so transient MQTT blips don't flood the user.
  553. _printer_last_connected: dict[int, bool] = {}
  554. # Printers whose relay offline event went out, so the reconnect publishes the
  555. # matching online event and a blip shorter than the debounce publishes neither.
  556. _printer_offline_published: set[int] = set()
  557. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  558. # Debounce: a printer must stay offline this long before we notify. Sized
  559. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  560. # so a single stale-trigger cooldown isn't enough to fire — only a real
  561. # offline that survives one reconnect attempt notifies.
  562. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  563. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  564. # when status="failed" to label the print's failure_reason in archives.
  565. #
  566. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  567. # which is wrong on two counts:
  568. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  569. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  570. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  571. # the public wiki) as part of its user-cancel sequence. Matching on the module
  572. # alone caused user-cancellations to be archived as "Layer shift" failures.
  573. # We now match by full short code only — anything not in this map leaves
  574. # failure_reason=None rather than guessing.
  575. # Values are the canonical camelCase failure-reason keys, NOT display labels
  576. # (issue #2974). The vocabulary is enforced on writes by
  577. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  578. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  579. # Statistics breakdown. Storing a label here instead put a second spelling of
  580. # the same cause into one column: the Failure Analysis widget groups on the raw
  581. # value, so a print the backend classified and an identical one a user
  582. # classified counted as two different reasons, and the label form could never
  583. # be translated because there was no key for ``t()`` to resolve.
  584. _HMS_FAILURE_REASONS: dict[str, str] = {
  585. # Layer shift / step loss
  586. "0300_4057": "layerShift",
  587. "0300_4068": "layerShift",
  588. "0300_800C": "layerShift",
  589. # Filament runout (printer-side & per-AMS-slot)
  590. "0300_8004": "filamentRunout",
  591. "0700_8011": "filamentRunout",
  592. "0701_8011": "filamentRunout",
  593. "0702_8011": "filamentRunout",
  594. "0703_8011": "filamentRunout",
  595. "0704_8011": "filamentRunout",
  596. "0705_8011": "filamentRunout",
  597. "0706_8011": "filamentRunout",
  598. "0707_8011": "filamentRunout",
  599. "07FF_8011": "filamentRunout",
  600. # Clogged nozzle / extruder
  601. "0300_4006": "cloggedNozzle",
  602. "0300_8016": "cloggedNozzle",
  603. "0300_801C": "cloggedNozzle",
  604. "0700_8003": "cloggedNozzle",
  605. "0700_8007": "cloggedNozzle",
  606. "0700_8013": "cloggedNozzle",
  607. "0701_8003": "cloggedNozzle",
  608. "0701_8007": "cloggedNozzle",
  609. "0701_8013": "cloggedNozzle",
  610. "0702_8003": "cloggedNozzle",
  611. # AI print monitoring — spaghetti / the model coming off the plate.
  612. # `spaghettiDetached` is a key the archive editor already offers for this
  613. # failure mode, not a new one, so a derived reason opens the dropdown on
  614. # that option rather than blank — and survives the next save, which clears
  615. # any value the editor does not recognise.
  616. #
  617. # A module-0x0C row is safe here despite the warning above: that warning is
  618. # about matching on the module alone, and 0C00_8042 is a full short code
  619. # with a documented meaning ("The AI print monitor has detected a spaghetti
  620. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  621. # cannot collide.
  622. #
  623. # 0300_8003's own text ends "before continuing your print", but on an X2D
  624. # it arrives with the print already paused, offering only
  625. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  626. #
  627. # Two neighbours are left out on purpose, so this does not get re-derived:
  628. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  629. # reads as a warning about a print that is still running, not a halt.
  630. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  631. # the waste chute. That is not the print failing.
  632. #
  633. # That line is drawn from the text, not from `severity`, because severity
  634. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  635. # module/error word with no level in it, and bambu_mqtt.py gives every
  636. # print_error entry a flat severity=3. Matching on the short code alone is
  637. # the right shape for derive_failure_reason, not an omission.
  638. "0300_8003": "spaghettiDetached",
  639. "0C00_8042": "spaghettiDetached",
  640. }
  641. def _hms_short_code(attr: int, code: int | str) -> str:
  642. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  643. if isinstance(code, str):
  644. code_int = int(code.replace("0x", ""), 16) if code else 0
  645. else:
  646. code_int = int(code or 0)
  647. attr_int = int(attr or 0)
  648. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  649. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  650. """Derive the failure_reason key for an archived print.
  651. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  652. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  653. no HMS code matches (don't guess — null is honest). The keys are the
  654. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  655. translated at render time.
  656. """
  657. if status in ("aborted", "cancelled"):
  658. return "userCancelled"
  659. if status != "failed":
  660. return None
  661. for err in hms_errors or []:
  662. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  663. if short_code in _HMS_FAILURE_REASONS:
  664. return _HMS_FAILURE_REASONS[short_code]
  665. return None
  666. # Track created_by_id for expected prints so the user email can be sent even when
  667. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  668. # {(printer_id, filename): created_by_id}
  669. _expected_print_creators: dict[tuple[int, str], int] = {}
  670. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  671. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  672. # tag tuple changes for the slot. Cleared when the slot is reported empty
  673. # so remove + reinsert reliably re-prompts the UI.
  674. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  675. async def _broadcast_unknown_tag(
  676. *,
  677. printer_id: int,
  678. ams_id: int,
  679. tray_id: int,
  680. tag_uid: str,
  681. tray_uuid: str,
  682. tray_type: str | None = None,
  683. tray_color: str | None = None,
  684. tray_sub_brands: str | None = None,
  685. tray_count: int | None = None,
  686. ) -> None:
  687. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  688. _logger = logging.getLogger(__name__)
  689. slot_key = (ams_id, tray_id)
  690. tag_key = (tag_uid or "", tray_uuid or "")
  691. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  692. if per_printer.get(slot_key) == tag_key:
  693. _logger.debug(
  694. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  695. printer_id,
  696. ams_id,
  697. tray_id,
  698. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  699. )
  700. return
  701. _logger.info(
  702. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  703. printer_id,
  704. ams_id,
  705. tray_id,
  706. tray_type,
  707. tray_color,
  708. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  709. )
  710. # Broadcast first; only commit the dedup if the WS write succeeds.
  711. # If broadcast raises, the next MQTT push retries instead of being
  712. # permanently silenced by a poisoned dedup entry.
  713. await ws_manager.broadcast(
  714. {
  715. "type": "unknown_tag",
  716. "printer_id": printer_id,
  717. "ams_id": ams_id,
  718. "tray_id": tray_id,
  719. "tag_uid": tag_uid,
  720. "tray_uuid": tray_uuid,
  721. "tray_type": tray_type,
  722. "tray_color": tray_color,
  723. "tray_sub_brands": tray_sub_brands,
  724. "tray_count": tray_count,
  725. }
  726. )
  727. per_printer[slot_key] = tag_key
  728. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  729. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  730. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  731. if per_printer is None:
  732. return
  733. per_printer.pop((ams_id, tray_id), None)
  734. # TTL for expected-print entries: evict registrations older than this to prevent
  735. # unbounded growth when a print is registered but never starts (e.g. printer
  736. # disconnect, app restart, print started from the printer panel).
  737. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  738. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  739. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  740. # Cleanup loop interval
  741. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  742. _expected_prints_cleanup_task: asyncio.Task | None = None
  743. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  744. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  745. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  746. possible_keys: list[tuple[int, str]] = []
  747. filename = (state.gcode_file or state.current_print or "").strip()
  748. subtask_name = (state.subtask_name or "").strip()
  749. if subtask_name:
  750. possible_keys.append((printer_id, subtask_name))
  751. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  752. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  753. if filename:
  754. base_name = filename.rsplit("/", 1)[-1]
  755. if base_name.endswith(".gcode.3mf"):
  756. root_name = base_name[: -len(".gcode.3mf")]
  757. possible_keys.append((printer_id, root_name))
  758. possible_keys.append((printer_id, base_name))
  759. possible_keys.append((printer_id, f"{root_name}.gcode"))
  760. possible_keys.append((printer_id, f"{root_name}.3mf"))
  761. elif base_name.endswith(".3mf"):
  762. root_name = base_name[: -len(".3mf")]
  763. possible_keys.append((printer_id, root_name))
  764. possible_keys.append((printer_id, base_name))
  765. elif base_name.endswith(".gcode"):
  766. root_name = base_name[: -len(".gcode")]
  767. possible_keys.append((printer_id, root_name))
  768. possible_keys.append((printer_id, f"{root_name}.3mf"))
  769. possible_keys.append((printer_id, base_name))
  770. else:
  771. possible_keys.append((printer_id, base_name))
  772. possible_keys.append((printer_id, f"{base_name}.3mf"))
  773. return possible_keys
  774. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  775. """The id of who started the print, unless that user has been deleted since.
  776. Deleting a user forgets them in printer_manager, but a print that ended a
  777. moment before still holds them.
  778. """
  779. if not print_user or print_user.get("user_id") is None:
  780. return None
  781. from backend.app.models.user import User
  782. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  783. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  784. """Check the cheap, process-local print ownership signals."""
  785. if printer_manager.get_current_print_user(printer_id):
  786. return True
  787. return any(
  788. key in _expected_prints or _active_prints.get(key) in _owned_print_archive_ids
  789. for key in _build_status_print_keys(printer_id, state)
  790. )
  791. def _reported_print_names(printer_id: int, state: PrinterState) -> set[str]:
  792. """The names the printer reports for its print, as it echoes them (spaces become underscores)."""
  793. return {_normalise_subtask_name(name) for _pid, name in _build_status_print_keys(printer_id, state)} - {""}
  794. async def _printing_archive_without_job_id(
  795. db, printer_id: int, reported: set[str], *, dispatched_only: bool, live_only: bool = False
  796. ):
  797. """The newest printing archive on ``printer_id`` of a print that reported no job id, under a reported name.
  798. An archive with a real id of its own is a print that reported one: a "0"
  799. print is not it, even under the same name (one whose completion was missed
  800. would otherwise cover it). ``dispatched_only`` keeps to archives carrying
  801. Bambuddy's dispatch marker; ``live_only`` leaves out deleted ones.
  802. """
  803. from backend.app.models.archive import PrintArchive
  804. query = select(PrintArchive).where(
  805. PrintArchive.printer_id == printer_id,
  806. PrintArchive.status == "printing",
  807. or_(PrintArchive.subtask_id.is_(None), PrintArchive.subtask_id.in_(("", "0"))),
  808. )
  809. if dispatched_only:
  810. query = query.where(or_(PrintArchive.billing_run_id.is_not(None), PrintArchive.created_by_id.is_not(None)))
  811. if live_only:
  812. query = query.where(PrintArchive.deleted_at.is_(None))
  813. archives = await db.execute(query.order_by(PrintArchive.created_at.desc()))
  814. return next((a for a in archives.scalars() if _archive_name_forms(a) & reported), None)
  815. async def running_print_archive(db, printer_id: int, state: PrinterState, *, printing_only: bool, by_name: bool):
  816. """The archive of the print running on ``printer_id``, or None (#3327).
  817. By the print's subtask_id first, which the firmware mints per print; with
  818. ``printing_only`` only an archive that is still printing (a leftover row of
  819. a completion never seen must not stand in for another job). A print
  820. started outside the cloud (Bambu Studio over LAN, Handy, the printer's
  821. screen) reports subtask_id "0", which links it to nothing: the archive
  822. Bambuddy bound to the running print comes next, the one completion charges
  823. and photographs. A restart forgets that binding and rebinds only Bambuddy's
  824. own prints, so with ``by_name`` a "0" print last falls back to its printing
  825. archive under the name the printer reports. That can be an earlier run of
  826. the same name whose completion was missed while Bambuddy was down: good
  827. enough for a plate label or a cover, not for which objects skip-objects
  828. offers, so those callers leave it off. None until the archive exists, and
  829. never a deleted one.
  830. """
  831. from backend.app.models.archive import PrintArchive
  832. from backend.app.services.print_log import open_run_on_printer
  833. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  834. if subtask_id not in ("", "0"):
  835. # The run open on the printer for this job: the archive row is shared
  836. # by every plate of it, its printer and job id the latest start's.
  837. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  838. if run is not None and run.archive_id is not None:
  839. archive = await db.scalar(
  840. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  841. )
  842. if archive is not None:
  843. return archive
  844. query = select(PrintArchive).where(
  845. PrintArchive.printer_id == printer_id,
  846. PrintArchive.subtask_id == subtask_id,
  847. PrintArchive.deleted_at.is_(None),
  848. )
  849. if printing_only:
  850. query = query.where(PrintArchive.status == "printing")
  851. archive = await db.scalar(query.order_by(PrintArchive.created_at.desc()).limit(1))
  852. if archive is not None:
  853. return archive
  854. bound = next(
  855. (_active_prints[key] for key in _build_status_print_keys(printer_id, state) if key in _active_prints),
  856. None,
  857. )
  858. if bound is not None:
  859. return await db.scalar(select(PrintArchive).where(PrintArchive.id == bound, PrintArchive.deleted_at.is_(None)))
  860. if not by_name or subtask_id != "0":
  861. return None
  862. reported = _reported_print_names(printer_id, state)
  863. if not reported:
  864. return None
  865. return await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=False, live_only=True)
  866. def _bind_active_print(
  867. printer_id: int,
  868. archive_id: int,
  869. archive_filename: str | None,
  870. filename: str | None = None,
  871. subtask_name: str | None = None,
  872. ) -> None:
  873. """Track a running print under every name its completion may report.
  874. One set for every path that binds a print (new archive, expected print,
  875. restart resume, fallback): the archive's file name, the name the printer
  876. reported, and the subtask with and without ``.3mf``. Paths that registered
  877. fewer names lost the bound archive at completion, and with it the plate
  878. restore's height (#3240), whenever MQTT reported a name they had left out.
  879. """
  880. for name in {archive_filename, filename, f"{subtask_name}.3mf" if subtask_name else None, subtask_name}:
  881. if name:
  882. _active_prints[(printer_id, name)] = archive_id
  883. async def _archive_of_open_run(printer_id: int, subtask_id: str | None = None) -> int | None:
  884. """The archive of the run open on the printer, if it is still there.
  885. With ``subtask_id``, only a run of that job."""
  886. try:
  887. from backend.app.models.archive import PrintArchive
  888. from backend.app.services.print_log import open_run_on_printer
  889. async with async_session() as db:
  890. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  891. if run is None or run.archive_id is None:
  892. return None
  893. return await db.scalar(
  894. select(PrintArchive.id).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  895. )
  896. except Exception as e:
  897. logging.getLogger(__name__).warning("[RUN] Could not read the open run of printer %s: %s", printer_id, e)
  898. return None
  899. async def _open_run_for(archive_id: int, printer_id: int, subtask_id: str | None = None) -> None:
  900. """Write the run of the print that just started on the archive (archive
  901. redesign). In a session of its own and never in the way of the print
  902. start: until its readers move over, the archive still carries the print.
  903. The archive's start must be committed before. ``subtask_id`` is the
  904. printer's job, which finds the run again at a resume."""
  905. try:
  906. from backend.app.models.archive import PrintArchive
  907. from backend.app.models.printer import Printer
  908. from backend.app.services.print_log import open_run
  909. async with async_session() as db:
  910. archive = await db.get(PrintArchive, archive_id)
  911. if archive is None:
  912. return
  913. printer_name = await db.scalar(select(Printer.name).where(Printer.id == printer_id))
  914. await open_run(
  915. db,
  916. archive,
  917. printer_id=printer_id,
  918. printer_name=printer_name,
  919. plate_id=_print_plate_ids.get((printer_id, archive_id)),
  920. subtask_id=subtask_id,
  921. )
  922. await db.commit()
  923. except Exception as e:
  924. logging.getLogger(__name__).warning("[RUN] Could not open the run of archive %s: %s", archive_id, e)
  925. async def _drop_replaced_plate_videos(
  926. db, archive_id: int, plate_id: int | None, stale_relpath: str | None, logger: logging.Logger
  927. ) -> None:
  928. """Delete the videos a reprint of a plate replaces: ``stale_relpath``, the
  929. one the archive showed (when print start judged it this plate's), and
  930. those of the archive's earlier runs of the same plate. A plate keeps one
  931. video, as when the archive held the only one; another plate's stays. The
  932. runs that held them lose them. Commits."""
  933. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, PrintLogEntry
  934. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  935. runs = select(PrintLogEntry).where(
  936. PrintLogEntry.archive_id == archive_id, PrintLogEntry.timelapse_path.is_not(None)
  937. )
  938. with_video = list(await db.scalars(runs.execution_options(**{INCLUDE_OPEN_RUNS: True})))
  939. paths = {stale_relpath} if stale_relpath else set()
  940. if plate_id is not None:
  941. paths |= {r.timelapse_path for r in with_video if r.plate_id == plate_id}
  942. # A video another plate's run holds is that plate's.
  943. paths -= {r.timelapse_path for r in with_video if r.plate_id is not None and r.plate_id != plate_id}
  944. if not paths:
  945. return
  946. for run in with_video:
  947. if run.timelapse_path in paths:
  948. run.timelapse_path = None
  949. await db.commit()
  950. for relpath in sorted(p for p in paths if p):
  951. try:
  952. stale_path = safe_join_under(app_settings.base_dir, relpath, http=False)
  953. if stale_path.is_file():
  954. stale_path.unlink()
  955. logger.info("Deleted stale timelapse %s on reprint of archive %s", relpath, archive_id)
  956. except (OSError, PathTraversalError) as e:
  957. logger.warning("Failed to delete stale timelapse %s on reprint: %s", relpath, e)
  958. def _mark_owned_if_dispatched(archive) -> None:
  959. """Remember a running print's archive as Bambuddy's when it carries a
  960. dispatch marker Bambuddy writes itself: ``billing_run_id`` (minted per
  961. dispatch in the scheduler) or ``created_by_id`` (from the queue item)."""
  962. if archive.billing_run_id is not None or archive.created_by_id is not None:
  963. _owned_print_archive_ids.add(archive.id)
  964. async def _is_printer_kill_switch_enabled_cached() -> bool:
  965. """Return the kill-switch setting without querying on every MQTT frame."""
  966. global _kill_switch_setting_cache
  967. now = time.monotonic()
  968. if _kill_switch_setting_cache is not None:
  969. enabled, expires_at = _kill_switch_setting_cache
  970. if now < expires_at:
  971. return enabled
  972. async with async_session() as db:
  973. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  974. enabled = await is_printer_kill_switch_enabled(db)
  975. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  976. return enabled
  977. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  978. """Resolve whether the current print was started by Bambuddy.
  979. ``None`` means identity is not yet safe to decide. The kill switch must
  980. defer in that case: stopping a print is irreversible, and the first status
  981. frames after a restart may arrive before all subtask fields are populated.
  982. """
  983. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  984. return True
  985. # The printer's built-in calibration runs (Bambuddy's Calibrate, the
  986. # printer's screen) play gcode from its read-only system partition, where no
  987. # user file can be. Only that path counts: a calibration *name* proves
  988. # nothing, since Bambu Studio's pressure-advance print reports a user-style
  989. # path, and any print can be given that name.
  990. if str(getattr(state, "gcode_file", "") or "").startswith("/usr/"):
  991. return True
  992. # A1, A1 Mini, P1 and A2L report the same calibration as a bare file name,
  993. # which nothing distinguishes from a user's file given that name, so it is
  994. # not exempt: with the kill switch on, calibrate on those printers with the
  995. # switch off.
  996. possible_keys = _build_status_print_keys(printer_id, state)
  997. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  998. # is on disk. subtask_id is minted per print and pins the answer to the job
  999. # actually running, rather than to an unrelated one that reuses a filename.
  1000. raw_subtask_id = getattr(state, "subtask_id", None)
  1001. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  1002. if subtask_id == "":
  1003. # Not reported yet: the first frames after a restart can lack it.
  1004. return None
  1005. from backend.app.models.archive import PrintArchive
  1006. if subtask_id == "0":
  1007. # A print started outside the cloud from Bambu Studio, Handy or the
  1008. # printer's screen reports "0", so there is no id to match: one of
  1009. # Bambuddy's printing archives on this printer under the name the
  1010. # printer reports, compared as the printer echoes names (spaces become
  1011. # underscores). Nothing reported to compare yet: wait.
  1012. reported = _reported_print_names(printer_id, state)
  1013. if not reported:
  1014. return None
  1015. archive = await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=True)
  1016. else:
  1017. from backend.app.services.print_log import open_run_on_printer
  1018. # This job's run open on the printer: the archive is shared by every
  1019. # plate of it, and its status, printer and job id are the latest
  1020. # start's, which may be another printer's.
  1021. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  1022. archive = await db.get(PrintArchive, run.archive_id) if run is not None and run.archive_id else None
  1023. if archive is None:
  1024. result = await db.execute(
  1025. select(PrintArchive)
  1026. .where(
  1027. PrintArchive.printer_id == printer_id,
  1028. PrintArchive.status == "printing",
  1029. PrintArchive.subtask_id == subtask_id,
  1030. )
  1031. .order_by(PrintArchive.created_at.desc())
  1032. .limit(1)
  1033. )
  1034. archive = result.scalar_one_or_none()
  1035. # An archive row on its own proves nothing: `on_print_start` archives every
  1036. # print it observes, including ones started from Bambu Studio or Handy, and
  1037. # stamps them with the same status and subtask_id. Authorizing on its mere
  1038. # existence would disable the kill switch the moment the 3MF finishes
  1039. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  1040. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  1041. # (carried over from the queue item that started it).
  1042. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  1043. # Rehydrate the fast in-memory path for subsequent status frames. Include
  1044. # both the archive filename and every normalized key reported by MQTT.
  1045. _owned_print_archive_ids.add(archive.id)
  1046. _active_prints[(printer_id, archive.filename)] = archive.id
  1047. for key in possible_keys:
  1048. _active_prints[key] = archive.id
  1049. return True
  1050. # No dispatch marker. Before calling this someone else's print, check whether
  1051. # Bambuddy has a job of its own running on this printer: a library-file
  1052. # dispatch has no archive at send time, and an archive created seconds later
  1053. # by `on_print_start` carries neither marker. The queue row, which the
  1054. # scheduler commits to status="printing" before the MQTT send, is the one
  1055. # durable record every Bambuddy print has. It cannot be tied to this
  1056. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  1057. # print is irreversible, and refusing to act costs nothing but a log line.
  1058. from backend.app.models.print_queue import PrintQueueItem
  1059. dispatched_here = await db.scalar(
  1060. select(PrintQueueItem.id)
  1061. .where(
  1062. PrintQueueItem.printer_id == printer_id,
  1063. PrintQueueItem.status == "printing",
  1064. )
  1065. .limit(1)
  1066. )
  1067. if dispatched_here is not None:
  1068. return None
  1069. return False
  1070. async def _send_kill_switch_provider_notification(
  1071. printer_id: int,
  1072. printer_name: str,
  1073. data: dict,
  1074. ) -> bool:
  1075. """Send the immediate print-stopped provider notification.
  1076. Returning a success flag lets the normal MQTT completion path retry when
  1077. this early notification could not be delivered.
  1078. """
  1079. logger = logging.getLogger(__name__)
  1080. try:
  1081. async with async_session() as db:
  1082. await notification_service.on_print_complete(
  1083. printer_id,
  1084. printer_name,
  1085. "stopped",
  1086. data,
  1087. db,
  1088. )
  1089. return True
  1090. except Exception as e:
  1091. logger.warning(
  1092. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  1093. printer_id,
  1094. e,
  1095. )
  1096. return False
  1097. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  1098. """Wait for an immediate kill-switch notification, if one was scheduled."""
  1099. if task is None:
  1100. return False
  1101. try:
  1102. return await task
  1103. except Exception as e:
  1104. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  1105. return False
  1106. async def _run_needs_energy_start(archive, printer_id: int, db) -> bool:
  1107. """At a resume: whether the print's run still lacks its energy start
  1108. reading. The archive's may be an earlier print's. Commits a reading
  1109. found on the archive for this run onto it."""
  1110. try:
  1111. from backend.app.services.print_log import run_needs_energy_start
  1112. needs = await run_needs_energy_start(db, archive, printer_id=printer_id)
  1113. await db.commit()
  1114. return needs
  1115. except Exception as e:
  1116. logging.getLogger(__name__).warning("[RUN] Energy start of archive %s's run not checked: %s", archive.id, e)
  1117. return archive.energy_start_kwh is None
  1118. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  1119. """Capture the smart plug lifetime counter on the archive at print start.
  1120. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  1121. tracking survives a backend restart mid-print. The print-end handler reads
  1122. this value back from the DB and computes the delta against the current
  1123. plug counter.
  1124. """
  1125. _logger = logging.getLogger(__name__)
  1126. try:
  1127. candidates = await energy_plug_candidates(db, printer_id)
  1128. if not candidates:
  1129. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  1130. return False
  1131. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  1132. if selected is None:
  1133. # Naming the plugs matters here: with several linked to one printer
  1134. # this is the difference between "the meter is offline" and "you
  1135. # linked only accessories" (#2859).
  1136. _logger.warning(
  1137. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  1138. printer_id,
  1139. archive.id,
  1140. ", ".join(plug.name for plug in candidates),
  1141. )
  1142. return False
  1143. plug, energy = selected
  1144. archive.energy_start_kwh = float(energy["total"])
  1145. # With the plug's snapshots, what lets the cost follow the price over
  1146. # the print rather than take the price at its end (#1251). A price that
  1147. # can't be had must not cost the print its energy reading.
  1148. archive.energy_start_at = utcnow_naive()
  1149. archive.energy_start_plug_id = plug.id
  1150. try:
  1151. from backend.app.services.energy_price import current_price
  1152. archive.energy_start_price = await current_price(db)
  1153. except Exception as e:
  1154. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  1155. archive.energy_start_price = None
  1156. try:
  1157. from backend.app.services.print_log import mirror_energy_start
  1158. await mirror_energy_start(db, archive, printer_id=printer_id)
  1159. except Exception as e:
  1160. _logger.warning("[RUN] Energy start not copied onto the run of archive %s: %s", archive.id, e)
  1161. await db.commit()
  1162. _logger.info(
  1163. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  1164. f" ({context})" if context else "",
  1165. archive.id,
  1166. plug.name,
  1167. energy["total"],
  1168. )
  1169. return True
  1170. except Exception as e:
  1171. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  1172. return False
  1173. def forget_print_creator(user_id: int) -> None:
  1174. """The print-start emails of a deleted user's jobs go to nobody, not to
  1175. whoever is given the id next (SQLite reuses it)."""
  1176. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  1177. del _expected_print_creators[key]
  1178. async def forget_printer(printer_id: int) -> None:
  1179. """Drop what is kept for a deleted printer's id, here and in the services.
  1180. SQLite used to give the id to the next printer created, which inherited it
  1181. all: the running print's owner (its prints passed the kill switch and were
  1182. billed to that user), the plate-clear gate, pending and suppressed
  1183. notifications, the camera feed, the plate references. Ids are no longer
  1184. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  1185. stay. Called after the delete is committed, and again by work that was in
  1186. flight and wrote state back.
  1187. Every printer-keyed map of this module is listed here or, with the reason,
  1188. in tests/unit/test_forget_printer.py.
  1189. """
  1190. from backend.app.api.routes import camera
  1191. from backend.app.services import (
  1192. bambu_ftp,
  1193. kprofile_drift,
  1194. layer_timelapse,
  1195. plate_detection,
  1196. print_dispatch_context,
  1197. usage_tracker,
  1198. )
  1199. from backend.app.services.notify_live_activities import notify_live_activities
  1200. from backend.app.services.obico_detection import obico_detection_service
  1201. from backend.app.services.printer_file_cache import printer_file_cache
  1202. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  1203. archive_ids = set()
  1204. for tracked in (_active_prints, _expected_prints):
  1205. for key in [key for key in tracked if key[0] == printer_id]:
  1206. archive_ids.add(tracked.pop(key))
  1207. for archive_id in archive_ids:
  1208. _owned_print_archive_ids.discard(archive_id)
  1209. for registered in (_print_ams_mappings, _print_cost_center_ids, _print_plate_ids):
  1210. for key in [key for key in registered if key[0] == printer_id]:
  1211. del registered[key]
  1212. for tracked in (_expected_print_creators, _expected_print_registered_at):
  1213. for key in [key for key in tracked if key[0] == printer_id]:
  1214. del tracked[key]
  1215. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  1216. _ams_index_only_logged.discard(key)
  1217. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  1218. del _ams_alarm_cooldown[key]
  1219. # Pending work that would act on the id: an offline notice, a 3MF retry.
  1220. # A kill-switch notice is about a stop that happened and is left to finish.
  1221. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  1222. task = tasks.pop(printer_id, None)
  1223. if task is not None:
  1224. task.cancel()
  1225. for keyed in (
  1226. _stage22_finish_frames,
  1227. _stage22_finish_in_flight,
  1228. _inprint_frame_bank,
  1229. _inprint_frame_bank_ts,
  1230. _printer_reconciled_since_connect,
  1231. _printer_kprofiles_primed_since_connect,
  1232. _last_progress_milestone,
  1233. _first_layer_notified,
  1234. _kill_switch_notification_tasks,
  1235. _notified_hms_errors,
  1236. _hms_print_state,
  1237. _hms_forget_when_gone,
  1238. _timelapse_baselines,
  1239. _bed_cool_waiters,
  1240. _printer_last_connected,
  1241. _unknown_tag_last_broadcast,
  1242. _last_status_broadcast,
  1243. _connection_watchdog_last_attempt,
  1244. ):
  1245. keyed.pop(printer_id, None)
  1246. for marked in (
  1247. _unauthorized_print_kill_sent,
  1248. _user_stopped_printers,
  1249. _kill_switch_stopped,
  1250. _printer_offline_published,
  1251. _nozzle_count_updated,
  1252. _runtime_seen_connected,
  1253. _timelapse_baselines_unread,
  1254. ):
  1255. marked.discard(printer_id)
  1256. printer_manager.forget_printer(printer_id)
  1257. printer_file_cache.forget_printer(printer_id)
  1258. print_dispatch_context.clear(printer_id)
  1259. kprofile_drift.forget_printer(printer_id, deleted=True)
  1260. layer_timelapse.cancel_session(printer_id)
  1261. usage_tracker.forget_printer(printer_id)
  1262. obico_detection_service.forget_printer(printer_id)
  1263. bambu_ftp.clear_3mf_cache(printer_id)
  1264. await camera.forget_printer(printer_id)
  1265. printers.clear_cover_cache(printer_id)
  1266. print_scheduler.forget_printer(printer_id)
  1267. notify_live_activities.forget_printer(printer_id)
  1268. plate_detection.remove_printer_references(printer_id)
  1269. def register_expected_print(
  1270. printer_id: int,
  1271. filename: str,
  1272. archive_id: int,
  1273. ams_mapping: list[int] | None = None,
  1274. created_by_id: int | None = None,
  1275. cost_center_id: int | None = None,
  1276. plate_id: int | None = None,
  1277. ):
  1278. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1279. # Store with multiple filename variations to catch different naming patterns
  1280. _expected_prints[(printer_id, filename)] = archive_id
  1281. # Also store without .3mf extension if present
  1282. if filename.endswith(".3mf"):
  1283. base = filename[:-4]
  1284. _expected_prints[(printer_id, base)] = archive_id
  1285. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1286. # Store AMS mapping for usage tracking at print completion, and plate_id for
  1287. # a single-plate dispatch from a multi-plate 3MF — without it, the direct-Print
  1288. # path attributes the whole file's filament total to the spool instead of just
  1289. # the printed plate (#1697). They describe this dispatch: one that has none
  1290. # drops what an earlier dispatch of the archive left (sent, never started),
  1291. # unless a plate of the archive is printing now and still needs them.
  1292. dispatch = (printer_id, archive_id)
  1293. archive_printing = _printing_here(printer_id, archive_id)
  1294. if ams_mapping is not None:
  1295. _print_ams_mappings[dispatch] = ams_mapping
  1296. elif not archive_printing:
  1297. _print_ams_mappings.pop(dispatch, None)
  1298. if cost_center_id is not None:
  1299. _print_cost_center_ids[dispatch] = cost_center_id
  1300. elif not archive_printing:
  1301. _print_cost_center_ids.pop(dispatch, None)
  1302. if plate_id is not None:
  1303. _print_plate_ids[dispatch] = plate_id
  1304. elif not archive_printing:
  1305. _print_plate_ids.pop(dispatch, None)
  1306. # Store created_by_id so the user start email can be sent even when the archive
  1307. # itself has no created_by_id (e.g. library-file-based queue prints)
  1308. if created_by_id is not None:
  1309. _expected_print_creators[(printer_id, filename)] = created_by_id
  1310. if filename.endswith(".3mf"):
  1311. base = filename[:-4]
  1312. _expected_print_creators[(printer_id, base)] = created_by_id
  1313. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1314. # Record registration time for TTL-based eviction
  1315. _registered_at = time.monotonic()
  1316. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1317. if filename.endswith(".3mf"):
  1318. base = filename[:-4]
  1319. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1320. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1321. logging.getLogger(__name__).info(
  1322. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1323. )
  1324. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1325. """Undo :func:`register_expected_print` when the print never went out.
  1326. Registration has to happen *before* the MQTT print command, because the
  1327. printer can report the print before the line after the send executes. So
  1328. every path that registers and then fails to send — a cancel winning the
  1329. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1330. between — leaves an expectation for a print that will never arrive.
  1331. The TTL sweep evicts those after two hours, which is far longer than it
  1332. takes a user to react to a failed dispatch by pressing print again: that
  1333. reprint would be folded into the *old* archive and take the stale
  1334. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1335. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1336. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1337. are keyed by printer and archive, not by file, so they may only be dropped
  1338. once no live key of the printer still points at that archive.
  1339. """
  1340. keys = [(printer_id, filename)]
  1341. if filename.endswith(".3mf"):
  1342. base = filename[:-4]
  1343. keys.append((printer_id, base))
  1344. keys.append((printer_id, f"{base}.gcode"))
  1345. removed = False
  1346. for key in keys:
  1347. if _expected_prints.pop(key, None) is not None:
  1348. removed = True
  1349. _expected_print_creators.pop(key, None)
  1350. _expected_print_registered_at.pop(key, None)
  1351. # Still needed by another expected print of the archive on the printer,
  1352. # or a plate of it printing there, as in the sweep.
  1353. if not _expected_or_printing_here(printer_id, archive_id):
  1354. _drop_dispatch(printer_id, archive_id)
  1355. if removed:
  1356. logging.getLogger(__name__).info(
  1357. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1358. printer_id,
  1359. filename,
  1360. archive_id,
  1361. )
  1362. def _compute_run_filament_grams(
  1363. status: str,
  1364. archive_filament_used_grams: float | None,
  1365. progress: float | int | None,
  1366. usage_results: list[dict] | None,
  1367. ) -> float | None:
  1368. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1369. Priority for every status:
  1370. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1371. weight delta — same source that drives "Total Consumed" on the
  1372. Inventory page, so Stats and Inventory totals stay aligned).
  1373. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1374. back to the canonical "this print used X" value).
  1375. 3. For partial statuses: ``estimate * progress%``.
  1376. 4. ``None`` if nothing is known.
  1377. """
  1378. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1379. if tracked_grams > 0:
  1380. return round(tracked_grams, 1)
  1381. if status == "completed":
  1382. return archive_filament_used_grams
  1383. if archive_filament_used_grams:
  1384. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1385. if scale > 0:
  1386. return round(archive_filament_used_grams * scale, 1)
  1387. return None
  1388. def _printing_here(printer_id: int, archive_id: int) -> bool:
  1389. """Whether a plate of the archive is printing on the printer."""
  1390. return any(key[0] == printer_id and bound == archive_id for key, bound in _active_prints.items())
  1391. def _expected_or_printing_here(printer_id: int, archive_id: int) -> bool:
  1392. """Whether a print of the archive is expected or printing on the printer."""
  1393. return _printing_here(printer_id, archive_id) or any(
  1394. key[0] == printer_id and expected == archive_id for key, expected in _expected_prints.items()
  1395. )
  1396. def _drop_dispatch(printer_id: int, archive_id: int) -> None:
  1397. """Forget what the dispatch of the archive to the printer registered."""
  1398. dispatch = (printer_id, archive_id)
  1399. _print_ams_mappings.pop(dispatch, None)
  1400. _print_cost_center_ids.pop(dispatch, None)
  1401. _print_plate_ids.pop(dispatch, None)
  1402. def _get_start_ams_mapping(data: dict, printer_id: int, archive_id: int | None) -> list[int] | None:
  1403. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1404. stored_ams_mapping = data.get("ams_mapping")
  1405. if not stored_ams_mapping and archive_id:
  1406. stored_ams_mapping = _print_ams_mappings.get((printer_id, archive_id))
  1407. return stored_ams_mapping
  1408. def _get_start_plate_id(printer_id: int, archive_id: int | None) -> int | None:
  1409. """Resolve plate_id for print start without consuming stored direct-Print state.
  1410. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1411. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1412. read it back at print-start without popping (the entry is popped on print
  1413. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1414. """
  1415. if archive_id is None:
  1416. return None
  1417. return _print_plate_ids.get((printer_id, archive_id))
  1418. def _partial_progress_scale(progress: int | float | None) -> float:
  1419. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1420. Used by every site that multiplies a "would-have-used" slicer estimate
  1421. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1422. so the three sites in ``_background_notifications`` (and the per-plate
  1423. override helper) can't drift apart on the coercion shape.
  1424. """
  1425. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1426. def _scope_notification_archive_data_to_plate(
  1427. archive_data: dict,
  1428. archive_file_path: str | None,
  1429. plate_id: int | None,
  1430. print_status: str,
  1431. progress: int | float | None,
  1432. base_dir: Path,
  1433. ) -> dict:
  1434. """Override summed-across-plates totals in ``archive_data`` with the values
  1435. for ``plate_id`` so the completion notification reports what was actually
  1436. printed, not the whole project (#1785).
  1437. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1438. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1439. the archive card's "whole project" headline, wrong for the completion
  1440. notification of a single-plate print. The queue UI already re-reads the
  1441. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1442. notification payload (filament grams, time estimate, per-slot breakdown).
  1443. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1444. no per-plate values — in every fail case the original ``archive_data`` is
  1445. returned unchanged so the notification still sends.
  1446. """
  1447. if plate_id is None or not archive_file_path:
  1448. return archive_data
  1449. from backend.app.utils.threemf_tools import (
  1450. extract_filament_usage_from_3mf,
  1451. extract_print_time_from_3mf,
  1452. )
  1453. archive_path = base_dir / archive_file_path
  1454. if not archive_path.exists():
  1455. return archive_data
  1456. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1457. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1458. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1459. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1460. if plate_time:
  1461. archive_data["print_time_seconds"] = plate_time
  1462. # Gate both the grams headline AND the per-slot breakdown on the same
  1463. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1464. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1465. # to the project-level grams the archive columns already provide rather
  1466. # than ship a project-level headline next to an all-zero per-plate
  1467. # breakdown.
  1468. if plate_grams > 0:
  1469. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1470. archive_data["filament_slots"] = [
  1471. {
  1472. "slot_id": s.get("slot_id"),
  1473. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1474. "type": s.get("type", ""),
  1475. "color": s.get("color", ""),
  1476. }
  1477. for s in plate_slots
  1478. ]
  1479. return archive_data
  1480. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1481. """Best-effort filament metadata from the MQTT print-start snapshot.
  1482. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1483. file during print, see #1533) so the fallback PrintArchive still has
  1484. enough filament info to support the inventory views and AMS-expansion
  1485. planning the operator opens it for. Returns a dict with optional
  1486. ``filament_type`` and ``filament_color`` keys in the same
  1487. comma-separated format the 3MF extractor produces, so the rest of the
  1488. codebase treats the fallback archive identically to a normal one.
  1489. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1490. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1491. entries). When supplied, only the slots actually consumed by this
  1492. print contribute. Without it the function falls back to every loaded
  1493. AMS slot — less accurate but still useful.
  1494. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1495. that the unit tests pass directly, AND the on_print_start callback
  1496. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1497. bambu_mqtt service hands to main.py at runtime. The original
  1498. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1499. handled the inner shape and silently returned ``{}`` for every real
  1500. print start, leaving fallback archives' filament fields NULL — the
  1501. exact regression the fix was meant to close. Reported with a log
  1502. proving the AMS state was right there at
  1503. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1504. """
  1505. result: dict[str, str] = {}
  1506. # Look at the on_print_start wrapper first, then the inner shape.
  1507. raw_data = (data or {}).get("raw_data")
  1508. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1509. if not isinstance(ams_root, dict):
  1510. ams_root = (data or {}).get("ams") or {}
  1511. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1512. if not isinstance(ams_units, list) or not ams_units:
  1513. return result
  1514. from backend.app.services.print_scheduler import _global_tray_id
  1515. # Map global tray id → (type, color), addressed as the print's ams_mapping
  1516. # is: unit * 4 + tray, or the bare unit id for an AMS-HT (from 128).
  1517. loaded: dict[int, tuple[str, str]] = {}
  1518. for unit in ams_units:
  1519. if not isinstance(unit, dict):
  1520. continue
  1521. try:
  1522. unit_id = int(unit.get("id", 0))
  1523. except (TypeError, ValueError):
  1524. continue
  1525. for tray in unit.get("tray") or []:
  1526. if not isinstance(tray, dict):
  1527. continue
  1528. try:
  1529. tray_id = int(tray.get("id", 0))
  1530. except (TypeError, ValueError):
  1531. continue
  1532. ttype = (tray.get("tray_type") or "").strip()
  1533. # RRGGBBAA from the printer, stored as the 3MF path stores it:
  1534. # "#RRGGBB" (the Archives page's swatches and colour filter).
  1535. hex_color = (tray.get("tray_color") or "").strip().upper()[:6]
  1536. tcolor = f"#{hex_color}" if re.fullmatch(r"[0-9A-F]{6}", hex_color) else ""
  1537. if not ttype:
  1538. continue # Empty / unloaded slot.
  1539. loaded[_global_tray_id(unit_id, tray_id)] = (ttype, tcolor)
  1540. if not loaded:
  1541. return result
  1542. if ams_mapping:
  1543. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1544. filaments = [loaded[g] for g in used_ids if g in loaded]
  1545. if not filaments:
  1546. return result # Mapping points entirely at slots we have no data for.
  1547. else:
  1548. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1549. types_joined = ",".join(f[0] for f in filaments)
  1550. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1551. # Column limits per backend/app/models/archive.py: filament_type=50,
  1552. # filament_color=200.
  1553. if types_joined:
  1554. result["filament_type"] = types_joined[:50]
  1555. if colors_joined:
  1556. result["filament_color"] = colors_joined[:200]
  1557. return result
  1558. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1559. """Start a layer-timelapse session for *archive_id* when the printer has
  1560. an external camera configured. Returns True if a session was started.
  1561. Three call sites in on_print_start (expected-archive promotion, fallback
  1562. archive creation, fresh-archive creation) used to inline this same
  1563. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1564. on the first pass). Centralising the conditional + call here makes the
  1565. contract testable in isolation and keeps the three sites locked in step.
  1566. """
  1567. if not (printer.external_camera_enabled and printer.external_camera_url):
  1568. return False
  1569. from backend.app.services.layer_timelapse import start_session
  1570. start_session(
  1571. printer_id,
  1572. archive_id,
  1573. printer.external_camera_url,
  1574. printer.external_camera_type or "mjpeg",
  1575. snapshot_url=printer.external_camera_snapshot_url,
  1576. rotation=getattr(printer, "camera_rotation", 0),
  1577. )
  1578. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1579. return True
  1580. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1581. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1582. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1583. — since #2926 — the description the parser already resolved, which is preferred
  1584. when present so the queue's failure reason reads the same as the status
  1585. response. The short code still produces the bracketed label, and still
  1586. resolves the sentence for a caller whose entries predate the field. An entry
  1587. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1588. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1589. label when no description is on file. Returns None for an empty list so
  1590. callers can leave error_message unset.
  1591. """
  1592. if not hms_errors:
  1593. return None
  1594. from backend.app.services.hms_errors import get_error_description
  1595. parts: list[str] = []
  1596. for err in hms_errors:
  1597. try:
  1598. # `_hms_short_code` rather than a local derivation: this one used to
  1599. # format the error without masking it to 16 bits, so an `hms[]` entry
  1600. # whose code carries an alert-level group produced a five-digit label
  1601. # like "0500_3000A" — not a code the user can look up, and never a
  1602. # catalogue key, so the sentence was lost with it.
  1603. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1604. except (TypeError, ValueError):
  1605. continue
  1606. description = err.get("description") or get_error_description(short_code)
  1607. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1608. # groups and is not a code anyone can look up; its full code in the
  1609. # printer screen's four groups is (#2728).
  1610. full_code = str(err.get("full_code") or "")
  1611. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1612. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1613. return "; ".join(parts) if parts else None
  1614. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1615. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1616. print completes successfully. Gated to status=='completed': failed, cancelled
  1617. and aborted prints do not count as usage. Caller is responsible for committing
  1618. the session. No-op when the queue item has no linked library file (e.g. reprints
  1619. from an archive). See #1008."""
  1620. if queue_status != "completed" or item.library_file_id is None:
  1621. return
  1622. from backend.app.models.library import LibraryFile
  1623. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1624. if lib_file is None:
  1625. return
  1626. lib_file.print_count = (lib_file.print_count or 0) + 1
  1627. lib_file.last_printed_at = datetime.now(timezone.utc)
  1628. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1629. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1630. When on_print_complete fires with status 'failed' for a printer in this set we
  1631. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1632. rather than a 'print failed' notification.
  1633. """
  1634. _user_stopped_printers.add(printer_id)
  1635. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1636. _last_status_broadcast: dict[int, str] = {}
  1637. # Track printers where we've updated nozzle_count
  1638. _nozzle_count_updated: set[int] = set()
  1639. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1640. """Wait the debounce window then fire `on_printer_offline` if the printer
  1641. is still offline.
  1642. Scheduled by `on_printer_status_change` on the connected → disconnected
  1643. edge (#1752). Cancelled by the same handler if the printer reconnects
  1644. before the window elapses, so a single MQTT blip + recovery doesn't
  1645. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1646. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1647. route through the same status-change callback, so this covers both.
  1648. """
  1649. logger = logging.getLogger(__name__)
  1650. try:
  1651. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1652. still_offline = not printer_manager.is_connected(printer_id)
  1653. logger.info(
  1654. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1655. printer_id,
  1656. still_offline,
  1657. )
  1658. if not still_offline:
  1659. return
  1660. async with async_session() as db:
  1661. from backend.app.models.printer import Printer
  1662. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1663. printer = result.scalar_one_or_none()
  1664. if not printer:
  1665. logger.warning(
  1666. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1667. printer_id,
  1668. )
  1669. return
  1670. # Recorded only when the relay can publish it, so the reconnect's
  1671. # online event always has an offline before it.
  1672. if mqtt_relay.enabled and mqtt_relay.connected:
  1673. _printer_offline_published.add(printer_id)
  1674. try:
  1675. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1676. except Exception as e:
  1677. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1678. logger.info(
  1679. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1680. printer_id,
  1681. printer.name,
  1682. )
  1683. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1684. except asyncio.CancelledError:
  1685. raise
  1686. except Exception as e:
  1687. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1688. finally:
  1689. _printer_offline_notify_tasks.pop(printer_id, None)
  1690. def _hms_notify_key(error) -> str:
  1691. """What identifies a fault for notification de-duplication.
  1692. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1693. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1694. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1695. and -0006 together) shared a key and only the first was ever notified. An
  1696. entry without a full code falls back to attr and code together.
  1697. """
  1698. full_code = getattr(error, "full_code", "") or ""
  1699. if full_code:
  1700. return full_code.upper()
  1701. return f"{error.attr:08X}:{error.code}"
  1702. def _hms_fault_counts(error) -> bool:
  1703. """Whether a fault counts as a problem: the same rule the frontend's
  1704. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1705. It counts when Bambu publishes text for it or it offers action buttons, and
  1706. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1707. no actions does not count: those are things like "the top cover is open" or
  1708. "the chamber is hot, fan speed increased", which a printer can hold through
  1709. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1710. it always has; those are prompts such as "unable to start drying" (#2728).
  1711. """
  1712. if error.severity < 1:
  1713. return False
  1714. has_actions = bool(getattr(error, "actions", None))
  1715. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1716. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1717. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1718. """The new faults that count (see ``_hms_fault_counts``).
  1719. These go to the MQTT relay; the caller also needs a description before it
  1720. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1721. used to read ``severity >= 2`` when severity held the part byte; on the real
  1722. level that would drop the task-stopping errors (#2728).
  1723. """
  1724. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1725. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1726. """The faults on this printer not notified yet, and record them as notified.
  1727. Tracking is updated before anything is sent, so concurrent status callbacks
  1728. cannot notify the same fault twice. A notified fault is forgotten once it
  1729. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1730. and on is notified once (#3226), while one that clears and comes back much
  1731. later is notified again.
  1732. When ``print_state`` changes (a print resumed, started or finished), every
  1733. fault recorded so far is forgotten the first time it is gone, without the
  1734. wait: a runout fixed before resuming must be notified if it happens again a
  1735. few minutes later, while the printer sits paused. Not only the faults gone
  1736. at the change itself, because the update that flips the state can still
  1737. carry the old fault (a ``print_error`` entry stays until a payload brings
  1738. ``hms``).
  1739. """
  1740. now = time.time()
  1741. current = {_hms_notify_key(e) for e in errors}
  1742. seen = _notified_hms_errors.setdefault(printer_id, {})
  1743. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1744. if print_state is not None:
  1745. print_state = print_state.upper()
  1746. if _hms_print_state.get(printer_id, print_state) != print_state:
  1747. forget_when_gone.update(seen)
  1748. _hms_print_state[printer_id] = print_state
  1749. for key, last_seen in list(seen.items()):
  1750. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1751. del seen[key]
  1752. forget_when_gone.discard(key)
  1753. new = current - seen.keys()
  1754. for key in current:
  1755. seen[key] = now
  1756. if not seen:
  1757. _notified_hms_errors.pop(printer_id, None)
  1758. if not forget_when_gone:
  1759. _hms_forget_when_gone.pop(printer_id, None)
  1760. return _hms_errors_to_notify(errors, new)
  1761. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1762. # "Printing", -1 and 255 are "no stage" (#3211).
  1763. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1764. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1765. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1766. Records it as notified. Called only for a printing state with progress above 0.
  1767. Progress before the first layer is not progress through the print (#3211).
  1768. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1769. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1770. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1771. 75% notification together with Print Started, and since 75 was then on
  1772. record, 25 and 50 could never fire. So nothing counts while the printer
  1773. reports a layer count but has not started layer 1.
  1774. Without a layer count -- a print whose first frame carried no
  1775. ``total_layer_num``, until the pushall that asks for it is answered
  1776. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1777. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1778. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1779. reports neither keeps the old behaviour rather than never notifying.
  1780. """
  1781. if (state.layer_num or 0) < 1:
  1782. if (state.total_layers or 0) > 0:
  1783. return None
  1784. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1785. return None
  1786. progress = state.progress or 0
  1787. current_milestone = 0
  1788. if progress >= 75:
  1789. current_milestone = 75
  1790. elif progress >= 50:
  1791. current_milestone = 50
  1792. elif progress >= 25:
  1793. current_milestone = 25
  1794. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1795. _last_progress_milestone[printer_id] = current_milestone
  1796. return current_milestone
  1797. return None
  1798. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1799. """Handle printer status changes - broadcast via WebSocket."""
  1800. try:
  1801. notify_live_activities.observe(printer_id, state)
  1802. except Exception:
  1803. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1804. try:
  1805. pause_eta.observe(printer_id, state)
  1806. except Exception:
  1807. logging.getLogger(__name__).exception("Pause heads-up check failed for printer %s", printer_id)
  1808. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1809. # transitions disconnected → connected — which covers both Bambuddy
  1810. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1811. # `reconcile_stale_active_prints` exactly once for this connection so
  1812. # any archive still in `status="printing"` that can't actually be
  1813. # running anymore (printer IDLE / different subtask / empty subtask)
  1814. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1815. # finished during a disconnect window + a smart-plug power cycle
  1816. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1817. # next boot. Reconciliation runs concurrently — it must not block the
  1818. # WebSocket dedup / broadcast logic below, and the connected edge is
  1819. # marked True BEFORE the await so concurrent status updates inside
  1820. # the same connection don't re-trigger reconciliation.
  1821. #
  1822. # Wait for a real push_status before reconciling (#1679): MQTT
  1823. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1824. # the connection, BEFORE `_request_push_all` round-trips. At that
  1825. # instant the `PrinterState` is still on construction defaults — most
  1826. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1827. # If reconcile spawns here, every in-flight archive falls through to
  1828. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1829. # creates a duplicate archive on the real PRINT COMPLETE and
  1830. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1831. # keeps the #1542 mechanism intact: once the first real push_status
  1832. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1833. # fires again with the flag still False — reconcile then runs against
  1834. # actual evidence.
  1835. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1836. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1837. _printer_reconciled_since_connect[printer_id] = True
  1838. spawn_background_task(
  1839. reconcile_stale_active_prints(printer_id),
  1840. name=f"reconcile-stale-prints-{printer_id}",
  1841. )
  1842. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1843. # Re-arm so the next reconnect triggers reconciliation again.
  1844. _printer_reconciled_since_connect[printer_id] = False
  1845. # Same edge, for the calibration table the AMS card reads its K values from.
  1846. #
  1847. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1848. # tables to ask for. A `state_known` gate alone is not enough: the first
  1849. # real push_status is what makes the state known, and the nozzle fields do
  1850. # not always arrive in it. Latching there would spend this connection's one
  1851. # attempt on a printer that could not yet say what was fitted.
  1852. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1853. if (
  1854. state.connected
  1855. and state_known
  1856. and nozzle_known
  1857. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1858. ):
  1859. _printer_kprofiles_primed_since_connect[printer_id] = True
  1860. spawn_background_task(
  1861. prime_kprofile_table(printer_id),
  1862. name=f"prime-kprofiles-{printer_id}",
  1863. )
  1864. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1865. _printer_kprofiles_primed_since_connect[printer_id] = False
  1866. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1867. # else in the AMS report changing -- a power cycle does it to every slot --
  1868. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1869. # while the printer is idle; needs_check is cheap and throttled per slot.
  1870. # Guarded: nothing here may stop the status broadcast below.
  1871. try:
  1872. if not state.connected:
  1873. kprofile_drift.forget_printer(printer_id)
  1874. elif kprofile_drift.needs_check(printer_id, state):
  1875. spawn_background_task(
  1876. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1877. name=f"reapply-kprofiles-{printer_id}",
  1878. )
  1879. except Exception:
  1880. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1881. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1882. # connected → disconnected. The "back online" channel is already covered
  1883. # by the print-failure notification (firmware reports gcode_state=FAILED
  1884. # on reconnect of an interrupted print), so there is no online
  1885. # notification. The MQTT relay gets both: offline after the debounce, and
  1886. # online on the reconnect that follows a published offline.
  1887. prev_connected = _printer_last_connected.get(printer_id)
  1888. _printer_last_connected[printer_id] = state.connected
  1889. if prev_connected is True and not state.connected:
  1890. existing = _printer_offline_notify_tasks.get(printer_id)
  1891. if existing is None or existing.done():
  1892. logging.getLogger(__name__).info(
  1893. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1894. printer_id,
  1895. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1896. )
  1897. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1898. _maybe_notify_printer_offline(printer_id),
  1899. name=f"printer-offline-notify-{printer_id}",
  1900. )
  1901. elif state.connected:
  1902. # Kept until the relay can actually send online: with its broker down
  1903. # now, the next status update after the reconnect sends it.
  1904. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1905. _printer_offline_published.discard(printer_id)
  1906. printer_info = printer_manager.get_printer(printer_id)
  1907. if printer_info:
  1908. try:
  1909. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1910. except Exception as e:
  1911. logging.getLogger(__name__).warning(
  1912. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1913. )
  1914. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1915. if pending is not None and not pending.done():
  1916. logging.getLogger(__name__).info(
  1917. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1918. printer_id,
  1919. )
  1920. pending.cancel()
  1921. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1922. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1923. temps = state.temperatures or {}
  1924. nozzle_temp = round(temps.get("nozzle", 0))
  1925. bed_temp = round(temps.get("bed", 0))
  1926. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1927. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1928. # Auto-detect dual-nozzle printers from MQTT temperature data
  1929. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1930. _nozzle_count_updated.add(printer_id)
  1931. # Update nozzle_count in database
  1932. async with async_session() as db:
  1933. from backend.app.models.printer import Printer
  1934. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1935. printer = result.scalar_one_or_none()
  1936. if printer and printer.nozzle_count != 2:
  1937. printer.nozzle_count = 2
  1938. await db.commit()
  1939. logging.getLogger(__name__).info(
  1940. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1941. )
  1942. # Include target temps for heating phase detection
  1943. bed_target = round(temps.get("bed_target", 0))
  1944. nozzle_target = round(temps.get("nozzle_target", 0))
  1945. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1946. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1947. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1948. #
  1949. # dry_countdown_stalled rides along because it is the one drying signal the
  1950. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1951. # dry_time stopped moving, so on the frame that flips it every other member
  1952. # of this key is identical and the push would be deduplicated away. Mid-print
  1953. # a temperature would eventually break the tie, but a parked command on an
  1954. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1955. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1956. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1957. ams_dry_key = (
  1958. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1959. if state.raw_data
  1960. else ()
  1961. )
  1962. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1963. #
  1964. # The filament identity fields are here because Configure Slot writes
  1965. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1966. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1967. # matched, this function returned before broadcasting, and the card kept
  1968. # showing the old filament until the 30s fallback poll or a page reload —
  1969. # even though the configure route asks the printer for a fresh pushall and
  1970. # that push does carry the new values. Reset always worked, because it
  1971. # clears tray_type.
  1972. #
  1973. # These fields only change when someone configures a slot or swaps a spool,
  1974. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1975. ams_tray_key = (
  1976. tuple(
  1977. (
  1978. t.get("id"),
  1979. t.get("tray_type", ""),
  1980. t.get("state"),
  1981. t.get("tray_color", ""),
  1982. t.get("tray_info_idx", ""),
  1983. t.get("tray_sub_brands", ""),
  1984. t.get("cali_idx"),
  1985. )
  1986. for a in (state.raw_data.get("ams") or [])
  1987. for t in a.get("tray", [])
  1988. )
  1989. if state.raw_data
  1990. else ()
  1991. )
  1992. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1993. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1994. # in the AMS change-hash (tray fields only, and widening that would fire
  1995. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1996. # screen changed no key at all and the card's inlet badges sat stale until a
  1997. # reload. Like the filament-backup flag, these only move when someone
  1998. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1999. fts_key = (
  2000. state.fila_switch.installed if state.fila_switch else False,
  2001. tuple(sorted(state.ams_switch_inlet.items())),
  2002. # Which hotend holds which slot. Unlike the two above this does move
  2003. # mid-print, on every filament change — but only between discrete slots,
  2004. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  2005. # it live: it decides which hotend the Load dialog may offer and whether
  2006. # Unload has anything to act on.
  2007. tuple(
  2008. sorted(
  2009. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  2010. # Sort on the extruder id alone: the other members are nullable
  2011. # and comparing None with an int raises.
  2012. key=lambda entry: entry[0],
  2013. )
  2014. ),
  2015. )
  2016. status_key = (
  2017. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  2018. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  2019. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  2020. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  2021. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  2022. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  2023. )
  2024. # Fields that change only when the machine does (a nozzle swap, a firmware
  2025. # update, developer mode) or once per print (its AMS mapping): no traffic,
  2026. # but on an idle printer nothing else moves the key when they change.
  2027. machine_key = (
  2028. tuple((n.nozzle_type, n.nozzle_diameter) for n in (state.nozzles or [])),
  2029. state.firmware_version,
  2030. state.developer_mode,
  2031. tuple(state.print_ams_mapping) if isinstance(state.print_ams_mapping, list) else None,
  2032. # Cooling/heating, switched on the printer's screen too: on an idle
  2033. # printer nothing else moves the key (PSF-4).
  2034. state.airduct_mode,
  2035. )
  2036. status_key = f"{status_key}:{machine_key}"
  2037. is_active_print = state.state in _ACTIVE_PRINT_STATES
  2038. if not is_active_print:
  2039. _unauthorized_print_kill_sent.discard(printer_id)
  2040. elif printer_id in _unauthorized_print_kill_sent:
  2041. # stop_print() was already sent for this print; avoid all further
  2042. # ownership and settings work until the printer leaves an active state.
  2043. pass
  2044. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  2045. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  2046. _unauthorized_print_kill_sent.discard(printer_id)
  2047. else:
  2048. kill_switch_enabled = False
  2049. authorization: bool | None = None
  2050. status_logger = logging.getLogger(__name__)
  2051. try:
  2052. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  2053. if kill_switch_enabled:
  2054. async with async_session() as db:
  2055. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  2056. except Exception as e:
  2057. # Fail safe: a database/reconciliation error must never turn into an
  2058. # irreversible stop of a print whose ownership is still unknown.
  2059. authorization = None
  2060. status_logger.warning(
  2061. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  2062. )
  2063. if not kill_switch_enabled or authorization is True:
  2064. _unauthorized_print_kill_sent.discard(printer_id)
  2065. elif authorization is None:
  2066. _unauthorized_print_kill_sent.discard(printer_id)
  2067. status_logger.debug(
  2068. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  2069. printer_id,
  2070. )
  2071. else:
  2072. try:
  2073. stopped = printer_manager.stop_print(printer_id)
  2074. if stopped:
  2075. _unauthorized_print_kill_sent.add(printer_id)
  2076. _kill_switch_stopped.add(printer_id)
  2077. printer_info = printer_manager.get_printer(printer_id)
  2078. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  2079. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  2080. notification_data = {
  2081. "status": "stopped",
  2082. "filename": state.gcode_file or state.current_print or "",
  2083. "subtask_name": state.subtask_name or "",
  2084. "progress": state.progress,
  2085. "reason": "unauthorized_print",
  2086. }
  2087. status_logger.warning(
  2088. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  2089. printer_id,
  2090. state.state,
  2091. )
  2092. try:
  2093. await ws_manager.broadcast(
  2094. {
  2095. "type": "kill_switch_triggered",
  2096. "printer_id": printer_id,
  2097. "printer_name": printer_name,
  2098. "filename": filename,
  2099. "reason": "unauthorized_print",
  2100. }
  2101. )
  2102. except Exception as e:
  2103. status_logger.warning(
  2104. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  2105. )
  2106. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  2107. if previous_task is not None and not previous_task.done():
  2108. previous_task.cancel()
  2109. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  2110. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  2111. name=f"kill-switch-notification-{printer_id}",
  2112. )
  2113. else:
  2114. status_logger.warning(
  2115. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  2116. printer_id,
  2117. state.state,
  2118. )
  2119. except Exception as e:
  2120. status_logger.warning(
  2121. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  2122. )
  2123. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  2124. try:
  2125. printer_info = printer_manager.get_printer(printer_id)
  2126. if printer_info:
  2127. await mqtt_relay.on_printer_status(
  2128. printer_id,
  2129. state,
  2130. printer_info.name,
  2131. printer_info.serial_number,
  2132. printer_manager.is_awaiting_plate_clear(printer_id),
  2133. )
  2134. except Exception:
  2135. pass # Don't fail status callback if MQTT fails
  2136. if _last_status_broadcast.get(printer_id) == status_key:
  2137. return # No change, skip WebSocket broadcast
  2138. _last_status_broadcast[printer_id] = status_key
  2139. # Check for progress milestone notifications (25%, 50%, 75%)
  2140. progress = state.progress or 0
  2141. is_printing = state.state in ("RUNNING", "PRINTING")
  2142. if is_printing and progress > 0:
  2143. current_milestone = _progress_milestone_to_notify(printer_id, state)
  2144. if current_milestone is not None:
  2145. try:
  2146. from backend.app.models.printer import Printer
  2147. # Read the printer in a short session and release the connection
  2148. # BEFORE the ~15s camera snapshot below — holding it across the grab
  2149. # pinned a pooled connection per milestone, per printer (issue #2572).
  2150. async with async_session() as db:
  2151. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2152. printer = result.scalar_one_or_none()
  2153. printer_name = printer.name if printer else f"Printer {printer_id}"
  2154. filename = state.subtask_name or state.gcode_file or "Unknown"
  2155. # remaining_time is in minutes, convert to seconds for notification
  2156. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  2157. # Capture camera snapshot for notification image attachment (no DB held).
  2158. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  2159. # Notification send needs a session (provider/template lookups).
  2160. async with async_session() as db:
  2161. await notification_service.on_print_progress(
  2162. printer_id,
  2163. printer_name,
  2164. filename,
  2165. current_milestone,
  2166. db,
  2167. remaining_time_seconds,
  2168. image_data=image_data,
  2169. )
  2170. except Exception as e:
  2171. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  2172. elif progress < 5:
  2173. # Reset milestone tracking when print restarts or new print begins
  2174. _last_progress_milestone[printer_id] = 0
  2175. _first_layer_notified[printer_id] = False
  2176. # HMS error codes that should not trigger notifications even though they
  2177. # have known descriptions (e.g. user-initiated actions, not real errors).
  2178. _HMS_NOTIFICATION_SUPPRESS = {
  2179. "0500_400E", # Printing was cancelled (user action, not an error)
  2180. }
  2181. # Check for new HMS errors and send notifications
  2182. current_hms_errors = getattr(state, "hms_errors", []) or []
  2183. if current_hms_errors:
  2184. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  2185. if new_errors:
  2186. try:
  2187. from backend.app.models.printer import Printer
  2188. # Read the printer in a short session and release the connection
  2189. # BEFORE the ~15s camera snapshot below (issue #2572).
  2190. async with async_session() as db:
  2191. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2192. printer = result.scalar_one_or_none()
  2193. printer_name = printer.name if printer else f"Printer {printer_id}"
  2194. # Format error details for notification
  2195. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  2196. module_names = {
  2197. 0x03: "Print/Task",
  2198. 0x05: "Nozzle/Extruder",
  2199. 0x07: "AMS/Filament",
  2200. 0x0C: "Motion Controller",
  2201. 0x12: "Chamber",
  2202. }
  2203. # Capture camera snapshot once for all error notifications (no DB held).
  2204. error_image_data = await _capture_snapshot_for_notification(
  2205. printer_id, printer, logging.getLogger(__name__)
  2206. )
  2207. # Notification sends need a session (provider/template lookups).
  2208. async with async_session() as db:
  2209. sent_count = 0
  2210. for error in new_errors:
  2211. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  2212. # Build short code like "0700_8010"
  2213. # Mask to 16 bits to handle printers that send larger values
  2214. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  2215. error_code_masked = error_code_int & 0xFFFF
  2216. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  2217. # Only notify for errors Bambu publishes text for — printers
  2218. # send undocumented codes that aren't real errors, and Bambu
  2219. # lists some with empty text. Resolved at parse time (#2926);
  2220. # short_code is still needed for the suppression set below.
  2221. description = error.description
  2222. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  2223. continue
  2224. error_type = f"{module_name} Error"
  2225. error_detail = description
  2226. await notification_service.on_printer_error(
  2227. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  2228. )
  2229. sent_count += 1
  2230. if sent_count:
  2231. logging.getLogger(__name__).info(
  2232. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  2233. )
  2234. # Also publish to MQTT relay (no DB): every new fault that
  2235. # counts, with or without text, the same set the UI counts.
  2236. printer_info = printer_manager.get_printer(printer_id)
  2237. if printer_info:
  2238. errors_data = [
  2239. {
  2240. "code": e.code,
  2241. "attr": e.attr,
  2242. "module": e.module,
  2243. "severity": e.severity,
  2244. }
  2245. for e in new_errors
  2246. ]
  2247. await mqtt_relay.on_printer_error(
  2248. printer_id, printer_info.name, printer_info.serial_number, errors_data
  2249. )
  2250. except Exception as e:
  2251. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  2252. else:
  2253. # No HMS errors: nothing to send, but faults gone long enough (or gone
  2254. # across a print state change) are forgotten. Some codes, e.g. chamber
  2255. # temperature regulation during PETG prints, toggle every few seconds.
  2256. _take_new_hms_faults(printer_id, [], state.state)
  2257. await ws_manager.send_printer_status(
  2258. printer_id,
  2259. printer_state_to_dict(
  2260. state,
  2261. printer_id,
  2262. printer_manager.get_model(printer_id),
  2263. printer_manager.get_drying_targets(printer_id),
  2264. ),
  2265. )
  2266. def _is_bambu_uuid(tray_uuid: str) -> bool:
  2267. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  2268. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  2269. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  2270. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  2271. K-profiles are per-nozzle and the printer's calibration table is numbered
  2272. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  2273. switch's other inlet therefore silently invalidates every configured slot in
  2274. it: the index stays put and now resolves against the other nozzle's table.
  2275. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  2276. and 0.020 on the right kept the left profile after the move, and a manual
  2277. RFID re-read only re-asserted the same wrong one.
  2278. Configuring a slot is a deliberate preparation step, so this re-selects
  2279. rather than re-configures: only the calibration binding moves, and only for
  2280. slots whose spool already has a stored profile for the new nozzle. A slot
  2281. Bambuddy knows nothing about is left exactly as the operator left it.
  2282. """
  2283. logger = logging.getLogger(__name__)
  2284. target_extruder = extruder_for_inlet(inlet)
  2285. if target_extruder is None:
  2286. return
  2287. client = printer_manager.get_client(printer_id)
  2288. state = printer_manager.get_status(printer_id)
  2289. if not client or not state or not state.raw_data:
  2290. return
  2291. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  2292. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  2293. # the nozzle width, which changes both the K profile to select and the
  2294. # preset the slot should carry.
  2295. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  2296. ams_raw = state.raw_data.get("ams")
  2297. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2298. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  2299. if not unit:
  2300. return
  2301. try:
  2302. async with async_session() as db:
  2303. for tray in unit.get("tray", []):
  2304. tray_id = int(tray.get("id", -1))
  2305. if tray_id < 0 or not tray.get("tray_type"):
  2306. continue
  2307. current_idx = tray.get("cali_idx")
  2308. profile = await find_slot_kprofile_for_extruder(
  2309. db,
  2310. printer_id,
  2311. ams_id,
  2312. tray_id,
  2313. target_extruder,
  2314. nozzle_diameter,
  2315. printer_manager.get_model(printer_id),
  2316. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2317. )
  2318. if profile is None or profile.cali_idx is None:
  2319. continue
  2320. if current_idx == profile.cali_idx:
  2321. continue # Already on the right one.
  2322. logger.info(
  2323. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2324. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2325. printer_id,
  2326. ams_id,
  2327. tray_id,
  2328. inlet,
  2329. target_extruder,
  2330. profile.name,
  2331. current_idx,
  2332. profile.cali_idx,
  2333. profile.k_value,
  2334. )
  2335. client.extrusion_cali_sel(
  2336. ams_id=ams_id,
  2337. tray_id=tray_id,
  2338. cali_idx=profile.cali_idx,
  2339. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2340. nozzle_diameter=nozzle_diameter,
  2341. )
  2342. except Exception as e:
  2343. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2344. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2345. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2346. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2347. from the delayed re-check -- which is why it takes the AMS data and print
  2348. state as arguments instead of reading them from the push (#3186).
  2349. """
  2350. logger = logging.getLogger(__name__)
  2351. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2352. # Auto-unlink spool assignments with stale fingerprints. Under the
  2353. # per-printer assignment lock since #3186: the held-removal re-check runs
  2354. # this outside any MQTT push, so it can now overlap one.
  2355. try:
  2356. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2357. from sqlalchemy.orm import selectinload
  2358. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2359. from backend.app.models.spool import Spool as _Spool
  2360. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2361. from backend.app.services.ams_slot_presence import spool_present
  2362. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2363. # Built-in assignments only. Since #2812 they survive a switch to
  2364. # Spoolman mode rather than being deleted by it, and this pass ends
  2365. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2366. # time as the AMS contents changed under the other mode, undoing the
  2367. # preservation more slowly but just as completely.
  2368. assignments = []
  2369. if not await spoolman_owns_assignments(db):
  2370. result = await db.execute(
  2371. select(SA)
  2372. .where(SA.printer_id == printer_id)
  2373. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2374. )
  2375. assignments = result.scalars().all()
  2376. # ``printing_now`` (top of this function) keeps a runout from
  2377. # unlinking the spool that fed the print — the next idle-time pass
  2378. # unlinks it if the user really did take it out.
  2379. stale = []
  2380. # Removals this pass is holding rather than unlinking (#3186).
  2381. held: set[tuple] = set()
  2382. for assignment in assignments:
  2383. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2384. if assignment.ams_id == 255:
  2385. ps = printer_manager.get_status(printer_id)
  2386. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2387. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2388. current_tray = None
  2389. for vt in vt_tray_raw:
  2390. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2391. current_tray = vt
  2392. break
  2393. if not current_tray:
  2394. # vt_tray data may not have arrived yet — keep assignment
  2395. continue
  2396. else:
  2397. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2398. if not current_tray:
  2399. if printing_now:
  2400. logger.info(
  2401. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2402. assignment.spool_id,
  2403. assignment.ams_id,
  2404. assignment.tray_id,
  2405. )
  2406. continue
  2407. # A whole AMS unit can drop out of one push and come back in
  2408. # the next; only a slot that stays gone is a removal (#3186).
  2409. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2410. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2411. held.add(hold_key)
  2412. logger.info(
  2413. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2414. "unlinking if it is still gone in %ds",
  2415. assignment.spool_id,
  2416. assignment.ams_id,
  2417. assignment.tray_id,
  2418. int(slot_unlink_grace.GRACE_SECONDS),
  2419. )
  2420. continue
  2421. logger.info(
  2422. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2423. assignment.spool_id,
  2424. assignment.ams_id,
  2425. assignment.tray_id,
  2426. )
  2427. stale.append(assignment) # Slot empty
  2428. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2429. # A Bambu Lab spool is in this slot — check if it's the same spool
  2430. # that's currently assigned. If yes, keep the assignment (avoids
  2431. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2432. # the printer's filament preset on every startup).
  2433. tray_uuid = current_tray.get("tray_uuid", "")
  2434. tag_uid = current_tray.get("tag_uid", "")
  2435. spool = assignment.spool
  2436. spool_matches = False
  2437. if spool:
  2438. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2439. spool.tag_uid
  2440. and tag_uid
  2441. and tag_uid != "0000000000000000"
  2442. and spool.tag_uid.upper() == tag_uid.upper()
  2443. ):
  2444. spool_matches = True
  2445. if spool_matches:
  2446. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2447. cur_color = current_tray.get("tray_color", "")
  2448. cur_type = current_tray.get("tray_type", "")
  2449. fp_color = assignment.fingerprint_color or ""
  2450. fp_type = assignment.fingerprint_type or ""
  2451. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2452. assignment.fingerprint_color = cur_color
  2453. assignment.fingerprint_type = cur_type
  2454. logger.debug(
  2455. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2456. assignment.spool_id,
  2457. assignment.ams_id,
  2458. assignment.tray_id,
  2459. )
  2460. continue
  2461. # Different BL spool or unrecognized — unlink so auto-assign can match
  2462. logger.info(
  2463. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2464. assignment.spool_id,
  2465. assignment.ams_id,
  2466. assignment.tray_id,
  2467. tray_uuid,
  2468. )
  2469. stale.append(assignment)
  2470. else:
  2471. cur_color = current_tray.get("tray_color", "")
  2472. cur_type = current_tray.get("tray_type", "")
  2473. cur_state = current_tray.get("state")
  2474. fp_color = assignment.fingerprint_color or ""
  2475. fp_type = assignment.fingerprint_type or ""
  2476. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2477. # the slot was empty when the user pre-assigned via SpoolBuddy
  2478. # (the firmware drops ams_filament_setting on empty slots, so
  2479. # MQTT was deferred). The moment any filament gets inserted
  2480. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2481. # reconfigured spool — fire the deferred configuration.
  2482. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2483. # extruder" code) OR, on firmwares that don't use the state
  2484. # enum meaningfully, a non-empty tray_type when state is
  2485. # NOT one of the firmware's explicit empty signals (9, 10).
  2486. # state-only was wrong for firmwares that never set 11 — A1
  2487. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2488. # always report state=3 — so the replay never fired for them
  2489. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2490. # explicit "empty" signals authoritative over any stale
  2491. # tray_type that might survive the relay's auto-clearing.
  2492. #
  2493. # tray_exist_bits comes first because that guard cannot tell
  2494. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2495. # writes state=9 when the bit is 0 and leaves it there when the
  2496. # bit returns. A non-RFID spool inserted into a pre-assigned
  2497. # slot brings no tray_type with it, so the stale 9 made this
  2498. # expression false forever and the deferred config never fired
  2499. # — the deadlock #1322 removed from the assign path, still in
  2500. # place here (#3084, #3100).
  2501. loaded = spool_present(current_tray) is True or (
  2502. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2503. )
  2504. if not fp_type.strip() and loaded and assignment.spool:
  2505. # The fingerprint ends this replay. Not recorded when nothing
  2506. # could be sent (no MQTT client while the printer reconnects),
  2507. # so the next AMS change tries again. An attempt that raised is
  2508. # recorded as before: it may have sent part of the commands and
  2509. # would raise again on every change, remain% steps included.
  2510. configured: bool | None = False
  2511. try:
  2512. from backend.app.api.routes.inventory import (
  2513. apply_spool_to_slot_via_mqtt,
  2514. )
  2515. configured = await apply_spool_to_slot_via_mqtt(
  2516. db=db,
  2517. current_user=None,
  2518. spool=assignment.spool,
  2519. printer_id=printer_id,
  2520. ams_id=assignment.ams_id,
  2521. tray_id=assignment.tray_id,
  2522. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2523. current_tray_type=cur_type,
  2524. current_tray_sub_brands=current_tray.get("tray_sub_brands", ""),
  2525. )
  2526. except Exception:
  2527. logger.exception(
  2528. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2529. assignment.spool_id,
  2530. printer_id,
  2531. assignment.ams_id,
  2532. assignment.tray_id,
  2533. )
  2534. configured = None
  2535. if configured is False:
  2536. logger.warning(
  2537. "Pre-config not sent for spool %d on printer %d AMS%d-T%d (no MQTT client); "
  2538. "retrying on the next AMS change",
  2539. assignment.spool_id,
  2540. printer_id,
  2541. assignment.ams_id,
  2542. assignment.tray_id,
  2543. )
  2544. else:
  2545. if configured:
  2546. logger.info(
  2547. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2548. assignment.spool_id,
  2549. printer_id,
  2550. assignment.ams_id,
  2551. assignment.tray_id,
  2552. )
  2553. assignment.fingerprint_color = cur_color
  2554. assignment.fingerprint_type = cur_type
  2555. continue
  2556. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2557. # Blank tray data mid-print is a runout, not a swap: the
  2558. # firmware clears colour and type when it unloads a spool
  2559. # it just emptied. Unlinking here would erase the record
  2560. # of which spool fed the print so far.
  2561. if printing_now and not cur_color.strip() and not cur_type.strip():
  2562. logger.info(
  2563. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2564. "(runout?)",
  2565. assignment.spool_id,
  2566. assignment.ams_id,
  2567. assignment.tray_id,
  2568. )
  2569. continue
  2570. # Same reasoning off the print, on firmware's own say-so:
  2571. # a blank tray report from a slot whose tray_exist_bits
  2572. # bit is set describes a spool the AMS cannot identify —
  2573. # a non-RFID one, or one whose slot was reset — not a
  2574. # spool that was taken out. Deleting the assignment there
  2575. # threw away the identity the user had supplied, which is
  2576. # the only place it existed (#3100). A slot the bit calls
  2577. # empty, or one that carries no bit at all, still unlinks.
  2578. #
  2579. # Unless the slot was reported empty first: a removal
  2580. # already held means a spool came out and another went
  2581. # in, so the blank report keeps the hold running below
  2582. # rather than cancelling it (#3186).
  2583. if (
  2584. spool_present(current_tray) is True
  2585. and not cur_color.strip()
  2586. and not cur_type.strip()
  2587. and not slot_unlink_grace.is_held(
  2588. printer_id,
  2589. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2590. )
  2591. ):
  2592. logger.info(
  2593. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2594. "tray reports no filament data yet",
  2595. assignment.spool_id,
  2596. assignment.ams_id,
  2597. assignment.tray_id,
  2598. )
  2599. continue
  2600. # A blank report the presence bit does not vouch for is
  2601. # still only one push. An idle X1C cleared a whole AMS
  2602. # unit's bits, colour and type for a moment and lost
  2603. # four saved assignments that way (#3186); unlink only
  2604. # if the slot is still blank after the grace period.
  2605. if not cur_color.strip() and not cur_type.strip():
  2606. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2607. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2608. held.add(hold_key)
  2609. logger.info(
  2610. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2611. "unlinking if it is still blank in %ds",
  2612. assignment.spool_id,
  2613. assignment.ams_id,
  2614. assignment.tray_id,
  2615. int(slot_unlink_grace.GRACE_SECONDS),
  2616. )
  2617. continue
  2618. # Fingerprint mismatch — but check if tray now matches the
  2619. # assigned spool (e.g. auto-configure changed the tray).
  2620. # Both sides are reduced to the type the slot can carry
  2621. # before comparing: the assign path writes that rather
  2622. # than the spool's raw material (#2902), so a spool whose
  2623. # material is a product line — "PLA+", "HTPLA" — reports
  2624. # back as "PLA" and would otherwise fail this check and
  2625. # be auto-unlinked from the slot it was just assigned to.
  2626. # Reducing the printer's side too keeps slots configured
  2627. # by an older Bambuddy, still reporting "PLA+", matching.
  2628. spool = assignment.spool
  2629. if spool:
  2630. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2631. # Two ways the assign path can have arrived at the
  2632. # slot's type, so both count as "we wrote this".
  2633. # The material column is one; the spool's preset is
  2634. # the other, and it outranks the material when the
  2635. # spool has one -- a spool whose material says PLA
  2636. # and whose preset is "Bambu PLA Aero" puts
  2637. # PLA-AERO in the slot (#2902). Read from the stored
  2638. # preset name rather than resolving the preset,
  2639. # because this runs on every AMS push and a cloud
  2640. # lookup here would be both slow and unavailable on
  2641. # the unauthenticated replay path.
  2642. spool_types = {printer_filament_type(spool.material).upper()}
  2643. if spool.slicer_filament_name:
  2644. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2645. # An imported local preset stores its type outright,
  2646. # which is what the assign path used -- and the name
  2647. # above may be unset. One keyed read, and only on a
  2648. # mismatch, which is rare.
  2649. #
  2650. # slicer_filament is free text up to fifty characters,
  2651. # so the digits have to be checked against the range
  2652. # of the integer primary key they are about to be
  2653. # compared with. Postgres raises on an out-of-range
  2654. # integer rather than simply not matching, and that
  2655. # would poison this session and abandon the rest of
  2656. # the cleanup pass.
  2657. lp_ref = (spool.slicer_filament or "").strip()
  2658. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2659. from backend.app.models.local_preset import LocalPreset as _LP
  2660. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2661. if lp_type:
  2662. spool_types.add(printer_filament_type(lp_type).upper())
  2663. if (
  2664. _colors_similar(cur_color, spool_color)
  2665. and printer_filament_type(cur_type).upper() in spool_types
  2666. ):
  2667. logger.info(
  2668. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2669. assignment.spool_id,
  2670. assignment.ams_id,
  2671. assignment.tray_id,
  2672. )
  2673. assignment.fingerprint_color = cur_color
  2674. assignment.fingerprint_type = cur_type
  2675. continue
  2676. logger.info(
  2677. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2678. assignment.spool_id,
  2679. assignment.ams_id,
  2680. assignment.tray_id,
  2681. cur_color,
  2682. cur_type,
  2683. fp_color,
  2684. fp_type,
  2685. spool.rgba if spool else "?",
  2686. spool.material if spool else "?",
  2687. )
  2688. stale.append(assignment) # Spool changed
  2689. slot_unlink_grace.settle(printer_id, "inventory", held)
  2690. # Snapshot slots before delete — ORM attribute access after the
  2691. # commit would refresh against a deleted row.
  2692. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2693. for a in stale:
  2694. await db.delete(a)
  2695. if stale:
  2696. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2697. # Commit any changes (stale deletions and/or fingerprint updates)
  2698. await db.commit()
  2699. # Tell open browsers the assignment is gone (#2575). Only the manual
  2700. # REST assign/unassign endpoints broadcast this event; without it the
  2701. # frontend's spool-assignments cache keeps rendering the unlinked
  2702. # spool on the slot until an unrelated refetch — which reads exactly
  2703. # like "the fix didn't work" (reporter verified: a browser refresh
  2704. # after the swap showed the correct state all along).
  2705. for ams_id, tray_id in unlinked_slots:
  2706. await ws_manager.broadcast(
  2707. {
  2708. "type": "spool_assignment_changed",
  2709. "printer_id": printer_id,
  2710. "ams_id": ams_id,
  2711. "tray_id": tray_id,
  2712. }
  2713. )
  2714. except Exception as e:
  2715. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2716. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2717. """Delete Spoolman slot rows whose held removal has run its grace period.
  2718. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2719. talks to Spoolman for every tray; this only needs the local rows, so it
  2720. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2721. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2722. not in a slot the presence bit calls occupied -- and nothing else.
  2723. """
  2724. logger = logging.getLogger(__name__)
  2725. try:
  2726. async with async_session() as db:
  2727. from backend.app.api.routes.settings import get_setting
  2728. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2729. from backend.app.services.ams_slot_presence import spool_present
  2730. enabled = await get_setting(db, "spoolman_enabled")
  2731. if not enabled or enabled.lower() != "true":
  2732. return
  2733. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2734. if sync_mode and sync_mode != "auto":
  2735. return
  2736. trays: dict[tuple[int, int], dict] = {}
  2737. for ams_unit in ams_data or []:
  2738. if not isinstance(ams_unit, dict):
  2739. continue
  2740. for tray in ams_unit.get("tray", []):
  2741. if isinstance(tray, dict):
  2742. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2743. rows = (
  2744. (
  2745. await db.execute(
  2746. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2747. )
  2748. )
  2749. .scalars()
  2750. .all()
  2751. )
  2752. held: set[tuple] = set()
  2753. expired: list[tuple[int, int]] = []
  2754. for row in rows:
  2755. tray = trays.get((row.ams_id, row.tray_id))
  2756. if tray is None or printing_now:
  2757. continue
  2758. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2759. continue
  2760. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2761. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2762. continue
  2763. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2764. expired.append((row.ams_id, row.tray_id))
  2765. else:
  2766. held.add(hold_key)
  2767. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2768. if not expired:
  2769. return
  2770. # A statement rather than ORM deletes, like the sync pass: the two
  2771. # can overlap, and a row the other already removed must not fail
  2772. # this commit.
  2773. for ams_id, tray_id in expired:
  2774. await db.execute(
  2775. delete(SpoolmanSlotAssignment).where(
  2776. SpoolmanSlotAssignment.printer_id == printer_id,
  2777. SpoolmanSlotAssignment.ams_id == ams_id,
  2778. SpoolmanSlotAssignment.tray_id == tray_id,
  2779. )
  2780. )
  2781. await db.commit()
  2782. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2783. for ams_id, tray_id in expired:
  2784. await ws_manager.broadcast(
  2785. {
  2786. "type": "spool_assignment_changed",
  2787. "printer_id": printer_id,
  2788. "ams_id": ams_id,
  2789. "tray_id": tray_id,
  2790. }
  2791. )
  2792. except Exception as e:
  2793. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2794. async def _recheck_held_unlinks(printer_id: int) -> None:
  2795. """Re-run just the slot cleanup against the printer's current AMS state.
  2796. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2797. passes otherwise run only when the AMS hash changes, and a slot that went
  2798. empty and stayed empty may never change it again.
  2799. """
  2800. status = printer_manager.get_status(printer_id)
  2801. # A disconnected printer's state is its last report, not a new one: acting
  2802. # on it would "confirm" a removal nobody has seen for the whole grace
  2803. # period. Leave the holds; the first push after reconnecting decides.
  2804. if status is None or not status.connected:
  2805. return
  2806. ams_raw = status.raw_data.get("ams")
  2807. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2808. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2809. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2810. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2811. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2812. async def on_ams_change(printer_id: int, ams_data: list):
  2813. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2814. logger = logging.getLogger(__name__)
  2815. # Snapshot BEFORE any await: if a print is active, or a finished one is
  2816. # still being charged, skip weight sync later. on_print_complete may pop
  2817. # _active_sessions during our awaits (#880).
  2818. from backend.app.services.usage_tracker import printer_is_charging
  2819. _print_active = printer_is_charging(printer_id)
  2820. # A slot that reports empty while a print is running is a filament runout,
  2821. # not a spool swap: the spool is still physically in the AMS, just
  2822. # consumed. Dropping either inventory backend's slot link there loses the
  2823. # only record of which spool fed the print, so the completion path can't
  2824. # charge the runout segment to anything. Both cleanup passes below consult
  2825. # this; computed once, up front, so neither depends on the other having run.
  2826. _unlink_state = printer_manager.get_status(printer_id)
  2827. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2828. # The session alone is not enough: a restart that finds a stale persisted
  2829. # session registers none for the print that is running.
  2830. _print_active = _print_active or printing_now
  2831. # MQTT relay - publish AMS change
  2832. try:
  2833. printer_info = printer_manager.get_printer(printer_id)
  2834. if printer_info:
  2835. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2836. except Exception:
  2837. pass # Don't fail AMS callback if MQTT fails
  2838. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2839. # This ensures frontend gets immediate updates when AMS slots are configured
  2840. try:
  2841. state = printer_manager.get_status(printer_id)
  2842. if state:
  2843. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2844. await ws_manager.send_printer_status(
  2845. printer_id,
  2846. printer_state_to_dict(
  2847. state,
  2848. printer_id,
  2849. printer_manager.get_model(printer_id),
  2850. printer_manager.get_drying_targets(printer_id),
  2851. ),
  2852. )
  2853. except Exception as e:
  2854. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2855. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2856. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2857. # Serialised per-printer via services/ams_assignment_lock: MQTT bursts can deliver
  2858. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2859. # "no existing assignment" for the same (printer, ams, tray) and race to
  2860. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2861. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2862. # bug stayed latent there. See services/ams_assignment_lock for details.
  2863. try:
  2864. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2865. from sqlalchemy.orm import selectinload
  2866. from backend.app.api.routes.settings import get_setting
  2867. from backend.app.models.spool import Spool
  2868. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2869. from backend.app.services.spool_tag_matcher import (
  2870. auto_assign_spool,
  2871. create_spool_from_tray,
  2872. find_matching_untagged_spool,
  2873. get_spool_by_tag,
  2874. is_bambu_tag,
  2875. is_valid_tag,
  2876. link_tag_to_inventory_spool,
  2877. tag_belongs_to_archived_spool,
  2878. )
  2879. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2880. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2881. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2882. if not _spoolman_on or _spoolman_on.lower() != "true":
  2883. for ams_unit in ams_data:
  2884. if not isinstance(ams_unit, dict):
  2885. continue
  2886. ams_id = int(ams_unit.get("id", 0))
  2887. for tray in ams_unit.get("tray", []):
  2888. if not isinstance(tray, dict):
  2889. continue
  2890. tray_id = int(tray.get("id", 0))
  2891. tag_uid = tray.get("tag_uid", "")
  2892. tray_uuid = tray.get("tray_uuid", "")
  2893. tray_info_idx = tray.get("tray_info_idx", "")
  2894. if not tray.get("tray_type"):
  2895. # Slot reported empty — drop any cached unknown-tag
  2896. # broadcast so reinserting the same spool re-prompts.
  2897. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2898. continue # Empty slot
  2899. # Check if assignment already exists for this slot
  2900. existing = await db.execute(
  2901. select(SA)
  2902. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2903. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2904. )
  2905. existing_assignment = existing.scalar_one_or_none()
  2906. if existing_assignment:
  2907. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2908. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2909. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2910. # Skip during active prints: the usage tracker handles deduction
  2911. # precisely via 3MF data on print completion. Without this guard the
  2912. # AMS remain% SET and the usage tracker ADD both fire from the same
  2913. # MQTT message, doubling the deduction (#880).
  2914. if _print_active:
  2915. continue
  2916. remain_raw = tray.get("remain")
  2917. if (
  2918. remain_raw is not None
  2919. and existing_assignment.spool
  2920. and not existing_assignment.spool.weight_locked
  2921. ):
  2922. try:
  2923. remain_val = int(remain_raw)
  2924. except (TypeError, ValueError):
  2925. remain_val = -1
  2926. if 1 <= remain_val <= 100:
  2927. lw = existing_assignment.spool.label_weight or 1000
  2928. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2929. current_used = existing_assignment.spool.weight_used or 0
  2930. if new_used > current_used + 1:
  2931. # Rechecked in the statement: the spool was loaded
  2932. # before this, and a weight set by hand (or weighed)
  2933. # and locked since then must stay (WL-6).
  2934. result = cast(
  2935. CursorResult,
  2936. await db.execute(
  2937. update(Spool)
  2938. .where(
  2939. Spool.id == existing_assignment.spool_id,
  2940. Spool.weight_locked.is_not(True),
  2941. func.coalesce(Spool.weight_used, 0) < new_used - 1,
  2942. )
  2943. .values(weight_used=new_used)
  2944. ),
  2945. )
  2946. await db.commit()
  2947. if result.rowcount:
  2948. logger.info(
  2949. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2950. existing_assignment.spool_id,
  2951. current_used,
  2952. new_used,
  2953. remain_val,
  2954. )
  2955. await ws_manager.broadcast({"type": "inventory_changed"})
  2956. # A K-profile the slot lost (the default K after a reset or
  2957. # power cycle) is put back by kprofile_drift on the next idle
  2958. # push; a different real profile was picked on purpose and
  2959. # stays (#3219, item 44).
  2960. continue
  2961. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2962. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2963. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2964. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  2965. # An archived spool still in the AMS: the slot
  2966. # stays free rather than adopting its tag.
  2967. continue
  2968. if not spool:
  2969. # Try matching an untagged inventory spool (same material/color)
  2970. spool = await find_matching_untagged_spool(db, tray)
  2971. if spool:
  2972. await link_tag_to_inventory_spool(db, spool, tray)
  2973. elif _auto_add_unknown:
  2974. spool = await create_spool_from_tray(db, tray)
  2975. else:
  2976. # Auto-add disabled: surface the slot so the
  2977. # user can add it manually via the UI.
  2978. await _broadcast_unknown_tag(
  2979. printer_id=printer_id,
  2980. ams_id=ams_id,
  2981. tray_id=tray_id,
  2982. tag_uid=tag_uid,
  2983. tray_uuid=tray_uuid,
  2984. tray_type=tray.get("tray_type"),
  2985. tray_color=tray.get("tray_color"),
  2986. tray_sub_brands=tray.get("tray_sub_brands"),
  2987. tray_count=len(ams_unit.get("tray", [])),
  2988. )
  2989. continue
  2990. # Slot matched (existing tag, untagged inventory
  2991. # match, or freshly auto-created spool) — drop any
  2992. # stale dedup so a future tag swap re-prompts.
  2993. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2994. await auto_assign_spool(
  2995. printer_id,
  2996. ams_id,
  2997. tray_id,
  2998. spool,
  2999. printer_manager,
  3000. db,
  3001. tray_info_idx=tray_info_idx,
  3002. )
  3003. await db.commit()
  3004. await ws_manager.broadcast(
  3005. {
  3006. "type": "spool_auto_assigned",
  3007. "printer_id": printer_id,
  3008. "ams_id": ams_id,
  3009. "tray_id": tray_id,
  3010. "spool_id": spool.id,
  3011. }
  3012. )
  3013. logger.info(
  3014. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  3015. spool.id,
  3016. printer_id,
  3017. ams_id,
  3018. tray_id,
  3019. )
  3020. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  3021. db, tag_uid, tray_uuid
  3022. ):
  3023. # Non-BL spool with some tag — let user choose (not
  3024. # an archived one's, whose slot stays free)
  3025. await _broadcast_unknown_tag(
  3026. printer_id=printer_id,
  3027. ams_id=ams_id,
  3028. tray_id=tray_id,
  3029. tag_uid=tag_uid,
  3030. tray_uuid=tray_uuid,
  3031. tray_type=tray.get("tray_type"),
  3032. tray_color=tray.get("tray_color"),
  3033. tray_sub_brands=tray.get("tray_sub_brands"),
  3034. tray_count=len(ams_unit.get("tray", [])),
  3035. )
  3036. # No-tag slots (generic non-RFID filament) are left alone:
  3037. # nothing to identify, prompting "+ Add" would just create
  3038. # ghost spools with empty tags on every confirm.
  3039. except Exception as e:
  3040. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  3041. try:
  3042. async with async_session() as db:
  3043. from backend.app.api.routes.settings import get_setting
  3044. from backend.app.models.printer import Printer
  3045. # Check if Spoolman is enabled
  3046. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  3047. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  3048. return
  3049. # Check sync mode
  3050. sync_mode = await get_setting(db, "spoolman_sync_mode")
  3051. if sync_mode and sync_mode != "auto":
  3052. return # Only sync on auto mode
  3053. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  3054. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  3055. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  3056. # always owned by per-print tracking, never by AMS auto-sync. The
  3057. # setting is still read by the settings UI for backwards compat but
  3058. # has no effect on the sync path here.
  3059. # Get Spoolman URL
  3060. spoolman_url = await get_setting(db, "spoolman_url")
  3061. if not spoolman_url:
  3062. return
  3063. # Get or create Spoolman client
  3064. client = await get_spoolman_client()
  3065. if not client:
  3066. try:
  3067. client = await init_spoolman_client(spoolman_url)
  3068. except ValueError as exc:
  3069. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  3070. return
  3071. # Check if Spoolman is reachable
  3072. if not await client.health_check():
  3073. logger.warning("Spoolman not reachable at %s", spoolman_url)
  3074. return
  3075. # Get printer name for location
  3076. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3077. printer = result.scalar_one_or_none()
  3078. printer_name = printer.name if printer else f"Printer {printer_id}"
  3079. # OPTIMIZATION: Fetch all spools once before processing trays
  3080. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  3081. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  3082. try:
  3083. cached_spools = await client.get_spools()
  3084. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  3085. except Exception as e:
  3086. logger.error(
  3087. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  3088. printer_id,
  3089. e,
  3090. )
  3091. return
  3092. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  3093. from sqlalchemy.orm import selectinload
  3094. from backend.app.models.spool_assignment import SpoolAssignment
  3095. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  3096. from backend.app.services.ams_slot_presence import spool_present
  3097. from backend.app.services.inventory_mode import spoolman_owns_assignments
  3098. # Built-in remaining weight, used by sync_ams_tray only when the
  3099. # firmware reports an unusable remain%/tray_weight for a slot.
  3100. #
  3101. # Left empty since #2812. This block runs in Spoolman mode only,
  3102. # and until then the built-in table was emptied on the switch, so
  3103. # there was never anything here to read and the fallback was inert.
  3104. # Preserving those rows makes it live again, and it is keyed by slot
  3105. # rather than by spool: after a mode switch the tray may well hold
  3106. # different filament, and ``create_spool`` writes ``remaining_weight``
  3107. # unconditionally, so a stale figure would be seeded into a brand new
  3108. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  3109. # intent survives for whoever revisits the cross-mode fallback.
  3110. inventory_weights: dict[tuple[int, int], float] = {}
  3111. if not await spoolman_owns_assignments(db):
  3112. try:
  3113. assign_result = await db.execute(
  3114. select(SpoolAssignment)
  3115. .options(selectinload(SpoolAssignment.spool))
  3116. .where(SpoolAssignment.printer_id == printer_id)
  3117. )
  3118. for assignment in assign_result.scalars().all():
  3119. spool = assignment.spool
  3120. if spool and spool.label_weight > 0:
  3121. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  3122. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  3123. except Exception as e:
  3124. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  3125. # Load existing Spoolman slot assignments for the no-RFID fallback path
  3126. spoolman_slot_map: dict[tuple[int, int], int] = {}
  3127. slot_map_read = False
  3128. try:
  3129. slot_result = await db.execute(
  3130. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  3131. )
  3132. for slot in slot_result.scalars().all():
  3133. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  3134. slot_map_read = True
  3135. except Exception as e:
  3136. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  3137. # Sync each AMS tray and collect slot changes for DB persistence
  3138. synced = 0
  3139. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  3140. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  3141. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  3142. for ams_unit in ams_data:
  3143. if not isinstance(ams_unit, dict):
  3144. continue
  3145. ams_id = int(ams_unit.get("id", 0))
  3146. trays = ams_unit.get("tray", [])
  3147. for tray_data in trays:
  3148. if not isinstance(tray_data, dict):
  3149. continue
  3150. tray_id_raw = int(tray_data.get("id", 0))
  3151. tray = client.parse_ams_tray(ams_id, tray_data)
  3152. if not tray:
  3153. # Empty tray slot — record for local assignment cleanup
  3154. # and drop any cached unknown-tag broadcast so a
  3155. # reinserted spool re-prompts.
  3156. #
  3157. # Not during a running print: a slot that empties there
  3158. # is a filament runout, and the spool is still in the
  3159. # AMS. `spoolman_slot_assignments` is how a tag-less
  3160. # spool assigned through the Bambuddy UI is resolved at
  3161. # completion (#1459), so deleting the row mid-print
  3162. # loses the runout segment's usage — the same failure
  3163. # the internal inventory's auto-unlink had.
  3164. #
  3165. # Nor when firmware's presence bit says the slot is
  3166. # occupied. parse_ams_tray calls a tray with no type or
  3167. # no colour empty, and a spool the AMS cannot read has
  3168. # neither until something configures it — so a tag-less
  3169. # spool assigned through the UI had its row deleted by
  3170. # the first idle push after it was inserted. Same
  3171. # deletion as the internal inventory's in #3100, same
  3172. # answer, so the two modes stay in step.
  3173. #
  3174. # And only once the slot has stayed empty for the grace
  3175. # period -- the internal inventory's #3186 answer, for
  3176. # the same one-push blank.
  3177. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  3178. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  3179. if not printing_now and (
  3180. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  3181. ):
  3182. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  3183. empty_slots.append((ams_id, tray_id_raw))
  3184. else:
  3185. spoolman_held.add(hold_key)
  3186. logger.info(
  3187. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  3188. "unlinking if it is still empty in %ds",
  3189. ams_id,
  3190. tray_id_raw,
  3191. linked_spool,
  3192. int(slot_unlink_grace.GRACE_SECONDS),
  3193. )
  3194. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  3195. continue
  3196. spool_tag = (
  3197. tray.tray_uuid
  3198. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  3199. else tray.tag_uid
  3200. )
  3201. # Provide the hint only when no RFID is available
  3202. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  3203. try:
  3204. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  3205. result = await client.sync_ams_tray(
  3206. tray,
  3207. printer_name,
  3208. db,
  3209. # Per-print tracking is the only weight writer (#1119).
  3210. # AMS auto-sync still maintains spool metadata / slot
  3211. # assignments but no longer touches remaining_weight.
  3212. disable_weight_sync=True,
  3213. cached_spools=cached_spools,
  3214. inventory_remaining=inv_remaining,
  3215. spoolman_spool_id_hint=hint,
  3216. auto_add_unknown_rfid=auto_add_unknown_rfid,
  3217. )
  3218. if result is None and spool_tag and not auto_add_unknown_rfid:
  3219. # Spoolman skipped auto-create per user setting — surface
  3220. # the slot so the UI can offer "+ Add to inventory".
  3221. await _broadcast_unknown_tag(
  3222. printer_id=printer_id,
  3223. ams_id=ams_id,
  3224. tray_id=tray.tray_id,
  3225. tag_uid=tray.tag_uid or "",
  3226. tray_uuid=tray.tray_uuid or "",
  3227. tray_type=tray.tray_type,
  3228. tray_color=tray.tray_color,
  3229. tray_sub_brands=tray.tray_sub_brands,
  3230. tray_count=len(trays),
  3231. )
  3232. elif result:
  3233. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  3234. if result:
  3235. synced += 1
  3236. if result.get("id"):
  3237. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  3238. # If a new spool was created, add it to the cache
  3239. # so subsequent trays can find it if they reference the same tag
  3240. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  3241. if not spool_exists:
  3242. cached_spools.append(result)
  3243. logger.debug(
  3244. "[Printer %s] Added newly created spool %s to cache",
  3245. printer_id,
  3246. result["id"],
  3247. )
  3248. # Reconcile slot_preset_mappings (the same row internal
  3249. # mode keeps in sync via inventory + spool_tag_matcher).
  3250. # Without this the slot card surfaces the previous spool's
  3251. # preset name — same bug shape, different inventory mode.
  3252. from backend.app.services.slot_preset_writer import (
  3253. upsert_slot_preset_for_spoolman_spool,
  3254. )
  3255. await upsert_slot_preset_for_spoolman_spool(
  3256. db=db,
  3257. spoolman_spool=result,
  3258. tray_info_idx=tray.tray_info_idx or "",
  3259. tray_sub_brands=tray.tray_sub_brands or "",
  3260. tray_type=tray.tray_type or "",
  3261. printer_id=printer_id,
  3262. ams_id=ams_id,
  3263. tray_id=tray.tray_id,
  3264. )
  3265. except Exception as e:
  3266. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3267. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3268. if synced > 0:
  3269. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3270. # Persist slot assignment changes to the local table: only slots
  3271. # whose spool this pass changed, and only while they still hold what
  3272. # it read before awaiting Spoolman, so a spool assigned by hand in
  3273. # between stays (SSA-3). The changed slots are announced: the slot
  3274. # card reads slot_preset_mappings (rewritten above) ahead of the live
  3275. # tray, so with no event it kept the previous spool's preset name.
  3276. if slot_changes or empty_slots:
  3277. from backend.app.services.spoolman_slot_sync import write_slot_results
  3278. try:
  3279. await write_slot_results(
  3280. db,
  3281. {(printer_id, a_id, t_id): spool_id for (a_id, t_id), spool_id in spoolman_slot_map.items()}
  3282. if slot_map_read
  3283. else None,
  3284. [(printer_id, a_id, t_id, spool_id) for a_id, t_id, spool_id in slot_changes],
  3285. [(printer_id, a_id, t_id) for a_id, t_id in empty_slots],
  3286. )
  3287. except Exception as e:
  3288. await db.rollback()
  3289. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3290. except Exception as e:
  3291. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3292. # Largest finish photo attached to a notification; a bigger one is still linked.
  3293. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3294. async def _finish_photo_for_notification(
  3295. db, archive, archive_id: int, filename: str
  3296. ) -> tuple[str | None, bytes | None]:
  3297. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3298. With authentication off the link is the archive's own photo route, as it
  3299. always was: it opens without a login and doesn't expire. With
  3300. authentication on that route needs a media token, which nothing tapping a
  3301. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3302. link only ever answered 401. The photo is then saved as a notification
  3303. photo as well (utils/notification_photos.py) and the link points there: an
  3304. unguessable name that opens this one photo and nothing else, for 3 days.
  3305. The link is relative when no External URL is set. Bytes over
  3306. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3307. ``(None, None)`` when the photo can't be found.
  3308. """
  3309. from backend.app.api.routes.settings import get_setting
  3310. from backend.app.core.auth import is_auth_enabled
  3311. from backend.app.utils.archive_paths import find_archive_photo
  3312. from backend.app.utils.notification_photos import save_notification_photo
  3313. log = logging.getLogger(__name__)
  3314. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3315. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3316. photo_bytes: bytes | None = None
  3317. try:
  3318. photo_path = find_archive_photo(archive, filename)
  3319. if photo_path is not None:
  3320. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3321. except Exception as e:
  3322. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3323. try:
  3324. auth_on = await is_auth_enabled(db)
  3325. except Exception:
  3326. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3327. if auth_on:
  3328. url = None
  3329. if photo_bytes:
  3330. try:
  3331. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3332. url = f"{base}/api/v1/notifications/photos/{name}"
  3333. except Exception as e:
  3334. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3335. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3336. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3337. return url, None
  3338. if photo_bytes:
  3339. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3340. return url, photo_bytes
  3341. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3342. """Capture a camera snapshot for notification image attachment.
  3343. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3344. Uses: external camera > buffered frame > fresh capture.
  3345. Turns the chamber light on for the picture when the printer asks for it
  3346. (#1655). ``light=False`` is for callers that capture all through a print,
  3347. where the light would flash with every frame.
  3348. """
  3349. if not printer:
  3350. return None
  3351. async with camera_light(printer if light else None):
  3352. return await _capture_snapshot_frame(printer_id, printer, logger)
  3353. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3354. """The capture behind ``_capture_snapshot_for_notification``."""
  3355. try:
  3356. from backend.app.api.routes.settings import get_setting
  3357. async with async_session() as db:
  3358. capture_enabled = await get_setting(db, "capture_finish_photo")
  3359. if capture_enabled is not None and capture_enabled.lower() != "true":
  3360. return None
  3361. # Try external camera first
  3362. if printer.external_camera_enabled and printer.external_camera_url:
  3363. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3364. from backend.app.api.routes.camera import live_frame_for_capture
  3365. from backend.app.services.external_camera import capture_frame
  3366. # An external camera allows one reader, so capturing while a viewer
  3367. # is attached fails (#2707). A None here falls through to the paths
  3368. # below exactly as a failed capture did.
  3369. defer, buffered = live_frame_for_capture(printer_id)
  3370. if defer:
  3371. frame_data = buffered
  3372. else:
  3373. frame_data = await capture_frame(
  3374. printer.external_camera_url,
  3375. printer.external_camera_type or "mjpeg",
  3376. snapshot_url=printer.external_camera_snapshot_url,
  3377. )
  3378. if frame_data and len(frame_data) <= 2_500_000:
  3379. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3380. return _apply_camera_rotation(frame_data, printer, logger)
  3381. # Try buffered frame from active stream
  3382. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3383. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3384. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3385. buffered_frame = get_buffered_frame(printer_id)
  3386. if (active_for_printer or active_chamber) and buffered_frame:
  3387. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3388. if len(buffered_frame) <= 2_500_000:
  3389. return _apply_camera_rotation(buffered_frame, printer, logger)
  3390. # Fresh capture from printer camera
  3391. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3392. from backend.app.services.camera import capture_camera_frame_bytes
  3393. frame_data = await capture_camera_frame_bytes(
  3394. printer.ip_address, printer.access_code, printer.model, timeout=15
  3395. )
  3396. if frame_data and len(frame_data) <= 2_500_000:
  3397. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3398. return _apply_camera_rotation(frame_data, printer, logger)
  3399. except Exception as e:
  3400. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3401. return None
  3402. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3403. """#1867: bank a recent in-print camera frame for the finish photo.
  3404. Called on every layer change and (#2547) on every print-progress advance.
  3405. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3406. path has a pre-End-G-code image for prints that end with a plate swap.
  3407. Both drivers are print telemetry that stops the instant printing ends: no
  3408. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3409. plate swap) executes. So the last banked frame is always the finished print,
  3410. never the swapped plate — that property is what the #1867 path relies on and
  3411. it must survive any change to the throttle below.
  3412. Layer changes alone were not enough: they stop when the *final* layer
  3413. begins, which on a three-minute last layer left the bank stale by the whole
  3414. length of that layer (#2547). Progress keeps ticking through it.
  3415. Best-effort: any failure just leaves the previous banked frame.
  3416. """
  3417. logger = logging.getLogger(__name__)
  3418. client = printer_manager.get_client(printer_id)
  3419. state = client.state if client else None
  3420. if not state or state.state != "RUNNING":
  3421. return
  3422. # Only during actual extrusion — firmware ticks layer_num during the
  3423. # pre-print calibration sequence, whose sub-stages are non-zero.
  3424. if state.mc_print_sub_stage not in (None, 0):
  3425. return
  3426. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3427. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3428. # now that progress advances also drive banking, that exemption would fire a
  3429. # camera grab on every percent tick of the last layer. Bambu printers accept
  3430. # one RTSP client at a time, so each grab contends with the live view.
  3431. now = time.monotonic()
  3432. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3433. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3434. return
  3435. total = state.total_layers or 0
  3436. try:
  3437. async with async_session() as db:
  3438. from backend.app.models.printer import Printer
  3439. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3440. printer = result.scalar_one_or_none()
  3441. if not printer:
  3442. return
  3443. # Reuses the notification snapshot path, which honours the
  3444. # `capture_finish_photo` setting (returns None when disabled) so we
  3445. # don't bank frames the user never asked for. Without the chamber light
  3446. # (#1655): this runs every 25 seconds for the whole print.
  3447. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3448. if frame:
  3449. _inprint_frame_bank[printer_id] = frame
  3450. _inprint_frame_bank_ts[printer_id] = now
  3451. logger.debug(
  3452. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3453. printer_id,
  3454. layer_num,
  3455. total,
  3456. len(frame),
  3457. )
  3458. except Exception as e:
  3459. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3460. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3461. """Apply camera rotation to snapshot image if configured."""
  3462. from backend.app.services.camera import apply_camera_rotation
  3463. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3464. async def _send_print_start_notification(
  3465. printer_id: int,
  3466. data: dict,
  3467. archive_data: dict | None = None,
  3468. logger=None,
  3469. ):
  3470. """Helper to send print start notification with optional archive data."""
  3471. if logger is None:
  3472. logger = logging.getLogger(__name__)
  3473. try:
  3474. async with async_session() as db:
  3475. from backend.app.models.printer import Printer
  3476. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3477. printer = result.scalar_one_or_none()
  3478. printer_name = printer.name if printer else f"Printer {printer_id}"
  3479. # Capture camera snapshot for notification image attachment
  3480. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3481. if image_data:
  3482. if archive_data is None:
  3483. archive_data = {}
  3484. archive_data["image_data"] = image_data
  3485. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3486. # Send user-specific email notification for print start
  3487. if archive_data and archive_data.get("created_by_id"):
  3488. await notification_service.send_user_print_email(
  3489. event_type="user_print_start",
  3490. created_by_id=archive_data["created_by_id"],
  3491. printer_name=printer_name,
  3492. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3493. db=db,
  3494. )
  3495. except Exception as e:
  3496. logger.warning("Notification on_print_start failed: %s", e)
  3497. async def _dispatch_user_print_email(
  3498. status: str,
  3499. created_by_id: int | None,
  3500. printer_name: str,
  3501. filename: str,
  3502. db,
  3503. image_data: bytes | None = None,
  3504. finish_photo_url: str | None = None,
  3505. ) -> None:
  3506. """Send a user-specific print-completion email based on print status.
  3507. Maps the normalised print status to the correct event type and delegates
  3508. to :meth:`NotificationService.send_user_print_email`. A single helper
  3509. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3510. "stopped"`` dispatch block at every call site.
  3511. Does nothing if *created_by_id* is ``None``.
  3512. """
  3513. if created_by_id is None:
  3514. return
  3515. if status == "completed":
  3516. event_type = "user_print_complete"
  3517. elif status == "failed":
  3518. event_type = "user_print_failed"
  3519. elif status in ("stopped", "aborted", "cancelled"):
  3520. event_type = "user_print_stopped"
  3521. else:
  3522. return
  3523. await notification_service.send_user_print_email(
  3524. event_type=event_type,
  3525. created_by_id=created_by_id,
  3526. printer_name=printer_name,
  3527. filename=filename,
  3528. db=db,
  3529. image_data=image_data,
  3530. finish_photo_url=finish_photo_url,
  3531. )
  3532. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3533. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3534. try:
  3535. from backend.app.services.archive import extract_printable_objects_from_archive
  3536. client = printer_manager.get_client(printer_id)
  3537. if not client:
  3538. return
  3539. # Extract with positions for UI overlay, scoped to the plate that
  3540. # is printing — resolve_plate_id is the same resolver /cover uses,
  3541. # so the object list can't disagree with the thumbnail it is drawn
  3542. # over (#2522).
  3543. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3544. app_settings.base_dir / archive.file_path,
  3545. plate_number=resolve_plate_id(client.state),
  3546. )
  3547. if printable_objects:
  3548. client.state.printable_objects = printable_objects
  3549. client.state.printable_objects_bbox_all = bbox_all
  3550. client.state.skipped_objects = []
  3551. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3552. except Exception as e:
  3553. logger.debug("Failed to extract printable objects from archive: %s", e)
  3554. def _load_pauses_from_3mf(threemf_path, printer_id: int, *, warned_layers=(), passed_through_layer: int = 0) -> None:
  3555. """Read the running print's slicer pauses from its 3MF, in the background (#2984).
  3556. In a thread: a plate's G-code runs to tens of MB, and the print-start
  3557. handler must not wait for it. Kept only while the printer is still on
  3558. the print they were read for: a new print replaces the list.
  3559. ``warned_layers``: pauses this print was already warned about, kept on its
  3560. archive, so a restart does not send the heads-up again.
  3561. ``passed_through_layer``: for a print resumed after a restart, the layer it
  3562. is on. Its pauses up to there are behind it, though the printer's layer
  3563. reads 0 until it reports the next one.
  3564. """
  3565. client = printer_manager.get_client(printer_id)
  3566. if not client:
  3567. return
  3568. state = client.state
  3569. read_for = state.pause_points
  3570. try:
  3571. plate_id = resolve_plate_id(state)
  3572. except Exception:
  3573. # Never at the cost of the print-start handler this runs inside.
  3574. logging.getLogger(__name__).warning("[Printer %s] Could not tell the plate to read pauses for", printer_id)
  3575. return
  3576. async def _load() -> None:
  3577. from backend.app.utils.threemf_tools import extract_pause_points_from_3mf
  3578. points = await asyncio.to_thread(extract_pause_points_from_3mf, Path(threemf_path), plate_id)
  3579. if state.pause_points is not read_for:
  3580. return
  3581. state.pause_points = [p for p in points if p.layer > passed_through_layer]
  3582. state.pause_warned_layers = set(state.pause_warned_layers) | set(warned_layers)
  3583. if points:
  3584. logging.getLogger(__name__).info(
  3585. "Loaded %s slicer pause(s) for printer %s at layer(s) %s",
  3586. len(points),
  3587. printer_id,
  3588. [p.layer for p in points],
  3589. )
  3590. spawn_background_task(_load(), name=f"load-pauses-{printer_id}")
  3591. def _load_pauses_from_resumed_archive(archive, printer_id: int) -> None:
  3592. """Pauses for a print start taken as the resumption of a running print.
  3593. A restart while the print was paused makes its resume look like a new
  3594. print (#2984): the pauses warned about and passed are kept from before.
  3595. """
  3596. client = printer_manager.get_client(printer_id)
  3597. state = client.state if client else None
  3598. _load_pauses_from_3mf(
  3599. app_settings.base_dir / archive.file_path,
  3600. printer_id,
  3601. warned_layers=pause_eta.warned_layers_of(archive, state) if state is not None else (),
  3602. passed_through_layer=getattr(client, "layer_before_new_print", 0) if client else 0,
  3603. )
  3604. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3605. """Put the skip-objects list back after a restart mid-print.
  3606. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3607. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3608. which the #1304 guard suppresses on the first RUNNING push after startup.
  3609. Everything else this hook restores (the archive, the usage-tracking session,
  3610. the timelapse baseline) was already handled; the object list was not, so a
  3611. restart mid-print took skip-objects away for the rest of that print.
  3612. Nothing recovered it either: the printer card gates its Skip button on the
  3613. object count, and the one endpoint that can rebuild the list is reachable
  3614. only from the modal that button opens.
  3615. The archive is the running print's as ``running_print_archive`` finds it:
  3616. by subtask_id, or for a print that reports none by the archive bound to it
  3617. (#3327), never by name: a leftover ``status="printing"`` row from a
  3618. completion we never saw must not hand this print someone else's objects.
  3619. After a restart that binding exists only for Bambuddy's own prints, so a
  3620. print that reports no subtask_id loads nothing rather than a guess; the
  3621. reload path on ``GET /print/objects`` covers that case on demand.
  3622. """
  3623. client = printer_manager.get_client(printer_id)
  3624. if client is None or (client.state.printable_objects and client.state.pause_points):
  3625. return
  3626. archive = await running_print_archive(db, printer_id, state, printing_only=True, by_name=False)
  3627. if archive is not None and archive.file_path:
  3628. if not client.state.printable_objects:
  3629. _load_objects_from_archive(archive, printer_id, logger)
  3630. # The slicer's pauses are in-memory only as well (#2984).
  3631. if not client.state.pause_points:
  3632. _load_pauses_from_3mf(
  3633. app_settings.base_dir / archive.file_path,
  3634. printer_id,
  3635. warned_layers=pause_eta.warned_layers_of(archive, state),
  3636. )
  3637. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3638. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3639. # past it; the second covers a handshake that failed again on the way back and
  3640. # armed a fresh one. Module-level so tests can shrink them.
  3641. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3642. # Retry ladder for the other temporary give-up: the file service answered and
  3643. # the transfer still did not finish, which at print start is usually the printer
  3644. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3645. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3646. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3647. # two cover a printer that stays busy well into the print.
  3648. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3649. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3650. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3651. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3652. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3653. # by view, so two views race), the cool-off retry task, and print completion.
  3654. # Without this they each read file_path == "" and each run a full copy, so the row
  3655. # ends up pointing at one timestamped directory while the others sit orphaned.
  3656. #
  3657. # Keyed by printer rather than archive because a printer runs one print at a time,
  3658. # which makes the two equally strong here — and it bounds the dict by printer
  3659. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3660. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3661. # resuming, so "no waiters" is not a question this API can answer.
  3662. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3663. # How many of a printer's newest archives a touchscreen reprint is compared
  3664. # against (#3307). A repeat is usually of a recent job; the bound keeps a
  3665. # print start from reading a long history's extra_data.
  3666. _REPEAT_LOOKBACK = 200
  3667. async def _archived_3mf_for_repeat(
  3668. db, printer_id: int, subtask_name: str | None, gcode_file: str | None, total_layers: int | None
  3669. ):
  3670. """The newest archive of the job this printer is running again, with its 3MF.
  3671. A "Print again" on the printer's screen never names the file on the card:
  3672. it reports its own history copy under a generic name
  3673. (``file:///userdata/project_file.gcode.3mf``), the 3MF's internal title as
  3674. ``subtask_name`` and the plate as ``gcode_file`` -- and the title is often
  3675. not the card file's name, so every lookup built from it misses (#3307).
  3676. An earlier run that was archived recorded that same title and plate in its
  3677. ``_print_data``, and holds the 3MF.
  3678. Same printer, same title, same plate, a 3MF still on disk. A layer count
  3679. known on both sides must agree: the same title and plate re-sliced is
  3680. another job. None when nothing matches.
  3681. """
  3682. from backend.app.models.archive import PrintArchive
  3683. if not subtask_name or not gcode_file:
  3684. return None
  3685. rows = (
  3686. (
  3687. await db.execute(
  3688. select(PrintArchive)
  3689. .where(
  3690. PrintArchive.printer_id == printer_id,
  3691. PrintArchive.deleted_at.is_(None),
  3692. PrintArchive.file_path.isnot(None),
  3693. PrintArchive.file_path != "",
  3694. )
  3695. .order_by(PrintArchive.created_at.desc(), PrintArchive.id.desc())
  3696. .limit(_REPEAT_LOOKBACK)
  3697. )
  3698. )
  3699. .scalars()
  3700. .all()
  3701. )
  3702. for archive in rows:
  3703. extra = archive.extra_data if isinstance(archive.extra_data, dict) else {}
  3704. run = extra.get("_print_data")
  3705. if not isinstance(run, dict):
  3706. continue
  3707. if run.get("subtask_name") != subtask_name or run.get("filename") != gcode_file:
  3708. continue
  3709. if total_layers and archive.total_layers and archive.total_layers != total_layers:
  3710. continue
  3711. if not (app_settings.base_dir / archive.file_path).is_file():
  3712. continue
  3713. return archive
  3714. return None
  3715. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True) -> bool:
  3716. """Fill in a no-3MF archive from a 3MF that turned up later.
  3717. Returns True when the row was upgraded. Safe to call speculatively: it
  3718. verifies the archive still exists, is still a fallback, and that the file
  3719. is a readable 3MF before touching anything.
  3720. Serialised per printer — see ``_fallback_recovery_locks``.
  3721. """
  3722. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3723. async with lock:
  3724. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id, price=price)
  3725. async def _recover_fallback_archive_locked(
  3726. archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True
  3727. ) -> bool:
  3728. """The body of :func:`_recover_fallback_archive`, under its per-printer lock.
  3729. ``price`` is False when the print's end is being handled: the archive
  3730. still reads "printing" then, and its end prices it.
  3731. """
  3732. import zipfile
  3733. from backend.app.models.archive import PrintArchive
  3734. from backend.app.services.archive import ArchiveService
  3735. logger = logging.getLogger(__name__)
  3736. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3737. return False
  3738. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3739. # A truncated or half-written download is worse than no download: it
  3740. # would replace an honest empty archive with wrong metadata.
  3741. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3742. return False
  3743. async with async_session() as db:
  3744. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3745. if archive is None or archive.deleted_at is not None:
  3746. return False
  3747. if archive.file_path:
  3748. # Already recovered, or never was a fallback. Either way there is a
  3749. # real 3MF attached and overwriting it is not this function's job.
  3750. return False
  3751. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3752. service = ArchiveService(db)
  3753. recovered = await service.archive_print(
  3754. printer_id=printer_id,
  3755. source_file=source_3mf,
  3756. print_data={**print_data, "status": archive.status or "printing"},
  3757. subtask_id=archive.subtask_id,
  3758. update_archive_id=archive.id,
  3759. )
  3760. if recovered is None:
  3761. return False
  3762. logger.info(
  3763. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3764. archive_id,
  3765. source_3mf,
  3766. recovered.file_size,
  3767. )
  3768. # Spoolman's tracking stored no 3MF usage at print start and would
  3769. # charge the AMS remain% change; the built-in tracker reads the archive
  3770. # at completion and needs nothing. Also at the print's end (``price``
  3771. # False): that recovery runs inside the close-out, before the charge.
  3772. try:
  3773. from backend.app.services.spoolman_tracking import attach_recovered_3mf
  3774. from backend.app.services.usage_tracker import is_completing
  3775. await attach_recovered_3mf(
  3776. printer_id,
  3777. recovered.id,
  3778. recovered.file_path,
  3779. db,
  3780. printer_manager,
  3781. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3782. may_start=not price or (recovered.status == "printing" and not is_completing(printer_id)),
  3783. )
  3784. except Exception:
  3785. logger.warning(
  3786. "[RECOVER] Archive %s: could not add the 3MF to Spoolman's usage tracking", archive_id, exc_info=True
  3787. )
  3788. if price and recovered.status == "printing" and recovered.file_path:
  3789. # Print start had no 3MF to read the slicer's pauses from (#2984).
  3790. _load_pauses_from_3mf(app_settings.base_dir / recovered.file_path, printer_id)
  3791. if price and recovered.status == "printing":
  3792. # Print start priced it from the default rate, having no 3MF to
  3793. # estimate from; now it has one. An ended print is left alone: its
  3794. # end prices it. A print Bambuddy didn't dispatch has no start
  3795. # plate; the one the archive just read from the 3MF stands in.
  3796. _schedule_archive_cost_estimate(
  3797. printer_id,
  3798. recovered.id,
  3799. printer_manager,
  3800. ams_mapping=_get_start_ams_mapping(print_data, printer_id, recovered.id),
  3801. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3802. session_factory=async_session,
  3803. )
  3804. # `archive_updated`, not `archive_created` — the row was already on the
  3805. # Archives page as an empty card and is now filled in, not new.
  3806. await ws_manager.send_archive_updated(
  3807. {
  3808. "id": recovered.id,
  3809. "printer_id": recovered.printer_id,
  3810. "filename": recovered.filename,
  3811. "print_name": recovered.print_name,
  3812. "status": recovered.status,
  3813. }
  3814. )
  3815. return True
  3816. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path, *, price: bool = True) -> bool:
  3817. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3818. Called from the paths that pull a 3MF for a print that is already under way
  3819. — chiefly the cover endpoint, which downloads the very file the archive flow
  3820. could not get and, before #2957, used it for a thumbnail and nothing else.
  3821. The bytes are already local, so this costs a parse and a row update.
  3822. No-op when the running print has a real archive, which is the common case.
  3823. """
  3824. from backend.app.models.archive import PrintArchive
  3825. logger = logging.getLogger(__name__)
  3826. # `_active_prints` is keyed on the raw names seen at print start — the
  3827. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3828. # Callers here arrive with whichever variant their own path produced, so
  3829. # match on the same normalization the download cache uses rather than on an
  3830. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3831. # endpoint find an archive registered under "Desktop_Goose".
  3832. wanted = normalize_3mf_name(name)
  3833. archive_id = None
  3834. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3835. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3836. archive_id = value
  3837. break
  3838. if archive_id is None:
  3839. return False
  3840. async with async_session() as db:
  3841. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3842. # Cheap pre-check so the common case (a normal archive) does no work.
  3843. if archive is None or archive.file_path or archive.deleted_at is not None:
  3844. return False
  3845. try:
  3846. return await _recover_fallback_archive(archive_id, path, printer_id, price=price)
  3847. except Exception as e:
  3848. # Recovery is opportunistic. A failure here must never take down the
  3849. # caller, which is usually just trying to render a thumbnail.
  3850. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3851. return False
  3852. def _schedule_fallback_3mf_retry(
  3853. printer_id: int,
  3854. archive_id: int,
  3855. filenames: list[str],
  3856. delays: tuple[float, ...] | None = None,
  3857. reason: str = REASON_FTPS_COOLOFF,
  3858. ) -> None:
  3859. """Re-attempt the 3MF download after a temporary give-up.
  3860. ``reason`` says which give-up this is, and picks the default ladder: an
  3861. FTPS cool-off has to be waited out, while a transfer that timed out under
  3862. contention is worth asking about again straight away (#3063). It is only
  3863. read for the ladder and the log line -- the retry itself is identical, since
  3864. in both cases the file is on the printer and the last attempt at it failed
  3865. for a reason that does not last.
  3866. """
  3867. logger = logging.getLogger(__name__)
  3868. if delays is None:
  3869. delays = (
  3870. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3871. if reason == REASON_FTP_TRANSFER_FAILED
  3872. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3873. )
  3874. async def _retry() -> None:
  3875. from backend.app.models.archive import PrintArchive
  3876. from backend.app.models.printer import Printer
  3877. for delay in delays:
  3878. await asyncio.sleep(delay)
  3879. async with async_session() as db:
  3880. archive = (
  3881. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3882. ).scalar_one_or_none()
  3883. if archive is None or archive.deleted_at is not None or archive.file_path:
  3884. return
  3885. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3886. if printer is None:
  3887. return
  3888. # Read the fields while the session is open rather than touching
  3889. # a detached instance minutes later, mid-download.
  3890. printer_ip = printer.ip_address
  3891. printer_code = printer.access_code
  3892. printer_model = printer.model
  3893. # Someone else may have fetched it in the meantime — the cover
  3894. # endpoint routinely does, and its copy is the same bytes.
  3895. for name in filenames:
  3896. cached = get_cached_3mf(printer_id, name)
  3897. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3898. return
  3899. if ftps_handshake_blocked(printer_ip):
  3900. logger.info(
  3901. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3902. printer_id,
  3903. archive_id,
  3904. )
  3905. continue
  3906. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3907. for candidate in filenames:
  3908. # Bare name only. These come from the print-start flow, which
  3909. # already strips the path, but the local temp write must not
  3910. # depend on that holding for every future caller — a name that
  3911. # is absolute or contains ".." would otherwise escape the data
  3912. # volume via the `/` operator.
  3913. name = Path(candidate).name
  3914. if not name or name in (".", ".."):
  3915. continue
  3916. if not name.endswith(".3mf"):
  3917. name = f"{name}.3mf"
  3918. temp_path = app_settings.archive_dir / "temp" / name
  3919. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3920. try:
  3921. hit = await download_file_try_paths_async(
  3922. printer_ip,
  3923. printer_code,
  3924. ftp_probe_paths(name),
  3925. temp_path,
  3926. socket_timeout=ftp_timeout,
  3927. printer_model=printer_model,
  3928. max_total_timeout=RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  3929. )
  3930. except Exception as e:
  3931. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3932. continue
  3933. if not hit:
  3934. continue
  3935. cache_3mf_download(printer_id, name, temp_path)
  3936. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3937. return
  3938. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3939. async def _guarded() -> None:
  3940. try:
  3941. await _retry()
  3942. except asyncio.CancelledError:
  3943. raise
  3944. except Exception as e:
  3945. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3946. finally:
  3947. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3948. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3949. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3950. if existing and not existing.done():
  3951. existing.cancel()
  3952. task = asyncio.create_task(_guarded())
  3953. _fallback_3mf_retry_tasks[printer_id] = task
  3954. logger.info(
  3955. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3956. archive_id,
  3957. reason,
  3958. printer_id,
  3959. ", ".join(f"{d:g}s" for d in delays),
  3960. )
  3961. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3962. """Whether an archive created here should ask for the print's outcome (#1898).
  3963. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3964. branches below: a queued job already has its archive and takes the
  3965. expected-print branch, where the queue item's own ``confirm_outcome``
  3966. decides. The queue is still consulted, because a restart mid-print empties
  3967. ``_expected_prints`` — without the check the setting could override a queue
  3968. item that deliberately has the flag off. Any failure answers "don't ask":
  3969. an unwanted prompt is worse than a missing one, and this must never be the
  3970. reason a print goes unarchived.
  3971. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3972. leaves one behind when a completion cannot be matched to it
  3973. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3974. only takes it back once the printer has sat connected and terminal for
  3975. minutes. Until then every screen-started print on that printer would
  3976. silently lose its prompt, so the row is held against ``observed_name`` by
  3977. the same comparison a completion uses: a positive disagreement means the row
  3978. is about some other run and this print is external after all.
  3979. """
  3980. logger = logging.getLogger(__name__)
  3981. try:
  3982. # A savepoint rather than a rollback of the caller's transaction on
  3983. # failure: a failed statement leaves the transaction unusable, but a
  3984. # full rollback also expires every object the caller has loaded (the
  3985. # printer, the archive it just created), and on an async session the
  3986. # next attribute read then raises instead of reloading. Everything here
  3987. # is a read, so undoing the savepoint loses nothing.
  3988. async with db.begin_nested():
  3989. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3990. except Exception as e:
  3991. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3992. return False
  3993. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3994. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3995. from backend.app.api.routes.settings import get_setting, setting_is_true
  3996. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3997. return False
  3998. from backend.app.models.print_queue import PrintQueueItem
  3999. dispatched_here = await db.scalar(
  4000. select(PrintQueueItem)
  4001. .where(
  4002. PrintQueueItem.printer_id == printer_id,
  4003. PrintQueueItem.status == "printing",
  4004. )
  4005. .limit(1)
  4006. )
  4007. if dispatched_here is None:
  4008. return True
  4009. expected = await _queue_item_dispatched_name(db, dispatched_here)
  4010. observed = (observed_name or "").strip()
  4011. if not expected or not observed or _subtask_names_match(expected, observed):
  4012. logger.info(
  4013. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  4014. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  4015. printer_id,
  4016. dispatched_here.id,
  4017. )
  4018. return False
  4019. logger.info(
  4020. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  4021. "%r; treating this as an externally started print.",
  4022. dispatched_here.id,
  4023. printer_id,
  4024. expected,
  4025. observed,
  4026. )
  4027. return True
  4028. async def _dispatch_outcome_confirmation_safely(
  4029. db,
  4030. printer_id: int,
  4031. printer_name: str,
  4032. data: dict,
  4033. archive_id: int,
  4034. archive_data: dict | None = None,
  4035. run_id: int | None = None,
  4036. ) -> None:
  4037. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  4038. The completion task sends the per-user print email on the same session
  4039. right after the prompt. A failed statement in the prompt leaves that
  4040. session needing a rollback, and without one the email step fails with
  4041. PendingRollbackError; the prompt is the optional part, so it must not be
  4042. the reason the email never goes out.
  4043. """
  4044. try:
  4045. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data, run_id=run_id)
  4046. except Exception as e:
  4047. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  4048. try:
  4049. await db.rollback()
  4050. except Exception:
  4051. pass
  4052. async def _outcome_answerers(db, owner_id: int | None) -> set[int] | None:
  4053. """Who may answer a print's outcome prompt in the app: its owner and anyone
  4054. who may change everyone's archives. None (everyone on the printer) with auth
  4055. off, or for a print nobody owns."""
  4056. from sqlalchemy.orm import selectinload
  4057. from backend.app.core.auth import is_auth_enabled
  4058. from backend.app.core.permissions import Permission
  4059. from backend.app.models.user import User
  4060. if owner_id is None or not await is_auth_enabled(db):
  4061. return None
  4062. users = (await db.execute(select(User).options(selectinload(User.groups)).where(User.is_active))).scalars().all()
  4063. return {owner_id} | {u.id for u in users if u.has_permission(Permission.ARCHIVES_UPDATE_ALL.value)}
  4064. async def dispatch_outcome_confirmation(
  4065. db,
  4066. printer_id: int,
  4067. printer_name: str,
  4068. data: dict,
  4069. archive_id: int,
  4070. archive_data: dict | None = None,
  4071. *,
  4072. run_id: int | None = None,
  4073. ) -> bool:
  4074. """Emit the post-print outcome prompt for a completed print (#1898).
  4075. Gated on the run that ended (``run_id``): ``confirm_requested`` is the
  4076. opt-in (from the queue item, or from ``confirm_outcome_external_prints``
  4077. for a print Bambuddy did not start, copied onto the run at its start) and
  4078. ``user_verdict`` being unset is what makes the question still open. Mints
  4079. the run's capability token the one-tap verdict links carry: plates of one
  4080. archive each have their own question. Without a run, the archive's, as
  4081. before runs.
  4082. Lives here rather than inline in ``on_print_complete``'s notification task
  4083. because that task swallows every exception: extracted, the gate and the two
  4084. emissions can be driven by a test, which is the only thing standing between
  4085. a regression here and a farm that quietly stops asking.
  4086. Returns whether a prompt was sent.
  4087. """
  4088. logger = logging.getLogger(__name__)
  4089. from backend.app.models.archive import PrintArchive
  4090. from backend.app.models.print_log import PrintLogEntry
  4091. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  4092. if confirm_archive is None:
  4093. return False
  4094. run = await db.get(PrintLogEntry, run_id) if run_id is not None else None
  4095. if run is not None and run.archive_id != archive_id:
  4096. run = None
  4097. # The run carries the opt-in from its start; one logged before it did
  4098. # (None) asks as its archive does.
  4099. asks = confirm_archive if run is None or run.confirm_requested is None else run
  4100. holder = run if run is not None else confirm_archive
  4101. if not (asks.confirm_requested and holder.user_verdict is None):
  4102. return False
  4103. import secrets as _secrets
  4104. # A spent token stays on the row so the one-tap route can recognise it, so
  4105. # "has a token" no longer means "answerable". A prompt going out now needs a
  4106. # live one: mint a new token whenever the stored one is already spent, or
  4107. # every button in the new message would land on the already-answered page.
  4108. if not holder.confirm_token or holder.confirm_token_used_at is not None:
  4109. holder.confirm_token = _secrets.token_urlsafe(32)
  4110. holder.confirm_token_used_at = None
  4111. await db.commit()
  4112. from backend.app.api.routes.settings import get_external_base_url, get_setting
  4113. base = await get_external_base_url(db)
  4114. if not await get_setting(db, "external_url"):
  4115. # Both the Telegram inline keyboard and the ntfy action buttons need an
  4116. # absolute URL, so an unconfigured install used to get a message body
  4117. # with two unusable relative paths and no buttons at all. The shared
  4118. # fallback at least produces tappable links; say which setting makes
  4119. # them resolve from a phone.
  4120. logger.warning(
  4121. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  4122. "Set Settings → External URL so they resolve away from this host.",
  4123. base,
  4124. )
  4125. token = holder.confirm_token
  4126. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  4127. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  4128. confirm_url = f"{base}/archives?confirm={archive_id}" + (f"&run={run.id}" if run is not None else "")
  4129. await ws_manager.send_print_confirm_request(
  4130. printer_id,
  4131. {
  4132. "archive_id": archive_id,
  4133. "run_id": run.id if run is not None else None,
  4134. "print_name": confirm_archive.print_name or confirm_archive.filename,
  4135. },
  4136. user_ids=await _outcome_answerers(db, confirm_archive.created_by_id),
  4137. )
  4138. await notification_service.on_print_confirm_request(
  4139. printer_id,
  4140. printer_name,
  4141. data,
  4142. db,
  4143. archive_data=archive_data,
  4144. good_url=good_url,
  4145. reject_url=reject_url,
  4146. confirm_url=confirm_url,
  4147. archive_id=archive_id,
  4148. run_id=run.id if run is not None else None,
  4149. )
  4150. return True
  4151. async def _printer_gone(db, printer_id: int) -> bool:
  4152. """Whether the printer was deleted. A column read: the session's loaded
  4153. Printer would otherwise answer for the database."""
  4154. from backend.app.models.printer import Printer
  4155. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  4156. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  4157. """Remove the archive just written if its printer was deleted meanwhile.
  4158. The delete route sweeps the printer's archives before it commits, so a row
  4159. committed after that sweep (the check before writing passed while the
  4160. delete was still uncommitted) is left for a printer that will never report
  4161. the print's end. A row the sweep reached is the route's: deleted with the
  4162. printer's archives, or detached (printer_id NULL) when the user kept them,
  4163. and then left as it is. Either way nothing is registered for it. Run after
  4164. the archive's commit, before anything is registered for it.
  4165. """
  4166. from backend.app.models.archive import PrintArchive
  4167. if not await _printer_gone(db, printer_id):
  4168. return False
  4169. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  4170. if owner == printer_id:
  4171. logging.getLogger(__name__).info(
  4172. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  4173. )
  4174. await ArchiveService(db).delete_archive(archive_id)
  4175. await forget_printer(printer_id)
  4176. return True
  4177. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  4178. """After an IntegrityError on a print start's archive write: whether it was
  4179. the printer being deleted, forgotten then (the caller returns).
  4180. PostgreSQL: the delete route locks the printer from its archive sweep to its
  4181. commit, so an archive written or adopted for it meanwhile (one that sets
  4182. printer_id) waits and the printer's foreign key then refuses it. That is
  4183. the printer being deleted, not an error; anything else is re-raised by the
  4184. caller.
  4185. """
  4186. await db.rollback()
  4187. if not await _printer_gone(db, printer_id):
  4188. return False
  4189. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  4190. await forget_printer(printer_id)
  4191. return True
  4192. async def _forget_if_printer_gone(printer_id: int) -> None:
  4193. """At the end of a print start: the slow steps after the last check (smart
  4194. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  4195. printer's delete and its forget_printer, and then wrote state back.
  4196. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  4197. SQLite; PostgreSQL refuses it.)
  4198. Its own session: those steps can leave the handler's needing a rollback (a
  4199. write to the archive the delete removed). Never raises: it runs inside the
  4200. fallback branch's try, whose except reports the archive as failed.
  4201. """
  4202. try:
  4203. async with async_session() as db:
  4204. gone = await _printer_gone(db, printer_id)
  4205. if gone:
  4206. await forget_printer(printer_id)
  4207. except Exception:
  4208. logging.getLogger(__name__).warning(
  4209. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  4210. )
  4211. async def _announce_plate_check_failed(printer_id: int, printer_name: str, reason: str) -> None:
  4212. """Tell the UI a plate check could not run. It does not block the print,
  4213. but an unchecked plate is not an empty one."""
  4214. try:
  4215. await ws_manager.broadcast(
  4216. {"type": "plate_check_failed", "printer_id": printer_id, "printer_name": printer_name, "reason": reason}
  4217. )
  4218. except Exception as e:
  4219. logging.getLogger(__name__).warning("[PLATE CHECK] Could not announce the failed check: %s", e)
  4220. def _expected_print_keys(printer_id: int, filename: str | None, subtask_name: str | None) -> list[tuple[int, str]]:
  4221. """The ``_expected_prints`` keys a print start may be registered under."""
  4222. keys: list[tuple[int, str]] = []
  4223. if subtask_name:
  4224. keys.append((printer_id, subtask_name))
  4225. keys.append((printer_id, f"{subtask_name}.3mf"))
  4226. keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  4227. if filename:
  4228. fname = filename.split("/")[-1] if "/" in filename else filename
  4229. keys.append((printer_id, fname))
  4230. # Strip extensions to match
  4231. base = fname.replace(".gcode", "").replace(".3mf", "")
  4232. keys.append((printer_id, base))
  4233. keys.append((printer_id, f"{base}.3mf"))
  4234. return keys
  4235. async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, subtask_name: str | None) -> bool:
  4236. """Whether this print start is one Bambuddy sent to the printer."""
  4237. if any(key in _expected_prints for key in _expected_print_keys(printer_id, filename, subtask_name)):
  4238. return True
  4239. from backend.app.models.archive import PrintArchive
  4240. from backend.app.models.print_queue import PrintQueueItem
  4241. # The queue row the scheduler sets to printing before it sends -- but only
  4242. # when it was sent as this print: a row left printing by a run whose end
  4243. # was missed names another file.
  4244. dispatched_names = (
  4245. await db.execute(
  4246. select(PrintArchive.filename)
  4247. .join(PrintQueueItem, PrintQueueItem.archive_id == PrintArchive.id)
  4248. .where(PrintQueueItem.printer_id == printer_id, PrintQueueItem.status == "printing")
  4249. )
  4250. ).scalars()
  4251. observed = [name for name in (subtask_name, (filename or "").rsplit("/", 1)[-1]) if name]
  4252. return any(
  4253. _subtask_names_match(_subtask_name_from_filename(dispatched), _subtask_name_from_filename(seen))
  4254. for dispatched in dispatched_names
  4255. if dispatched
  4256. for seen in observed
  4257. )
  4258. async def on_print_start(printer_id: int, data: dict):
  4259. """Handle print start - archive the 3MF file immediately."""
  4260. logger = logging.getLogger(__name__)
  4261. # The print's start, before the 3MF download that the archive waits for
  4262. # (#3327): a minute of it would otherwise be missing from the print time.
  4263. detected_at = datetime.now(timezone.utc)
  4264. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  4265. try:
  4266. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  4267. except Exception:
  4268. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  4269. # Clear any stale user-stopped flag from previous print cycles
  4270. _user_stopped_printers.discard(printer_id)
  4271. _kill_switch_stopped.discard(printer_id)
  4272. # A new print starts its milestones from zero (#3211). The status path only
  4273. # resets on progress below 5 while not printing, which a printer that goes
  4274. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  4275. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  4276. # or on resume from pause, so it cannot repeat a milestone mid-print.
  4277. _last_progress_milestone[printer_id] = 0
  4278. _kill_switch_notification_tasks.pop(printer_id, None)
  4279. # #1721: drop any leftover pre-captured finish frame from a prior print
  4280. # so a never-consumed cache entry can't bleed into the new print's photo.
  4281. _stage22_finish_frames.pop(printer_id, None)
  4282. # #1867: same for the in-print frame bank — a queued print must not reuse
  4283. # the previous job's banked frame.
  4284. _inprint_frame_bank.pop(printer_id, None)
  4285. _inprint_frame_bank_ts.pop(printer_id, None)
  4286. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  4287. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  4288. # print's flag instead of inheriting it.
  4289. print_dispatch_context.adopt(printer_id)
  4290. # Cancel any active bed cooldown waiter for this printer
  4291. if _bed_cool_waiters.pop(printer_id, None):
  4292. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  4293. # Clear cached cover images so the new print's thumbnail is fetched fresh
  4294. from backend.app.api.routes.printers import clear_cover_cache
  4295. clear_cover_cache(printer_id)
  4296. await ws_manager.send_print_start(printer_id, data)
  4297. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  4298. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  4299. # MQTT relay - publish print start
  4300. try:
  4301. printer_info = printer_manager.get_printer(printer_id)
  4302. if printer_info:
  4303. await mqtt_relay.on_print_start(
  4304. printer_id,
  4305. printer_info.name,
  4306. printer_info.serial_number,
  4307. data.get("filename", ""),
  4308. data.get("subtask_name", ""),
  4309. )
  4310. except Exception:
  4311. pass # Don't fail print start callback if MQTT fails
  4312. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  4313. # and mapping, and the seeded tray-change log.
  4314. #
  4315. # Unconditional, for both inventory backends. This only *captures* — the
  4316. # writing is still split, with the internal tracker skipped at completion
  4317. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  4318. # carries its plate-scoped 3MF figures and stored mapping, but not the
  4319. # tray-change log, and that log is the only record of which spool fed
  4320. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  4321. # it on one side only would leave Spoolman users with the mid-print
  4322. # restart bug this fixes for everyone else.
  4323. try:
  4324. async with async_session() as db:
  4325. from backend.app.api.routes.settings import get_setting
  4326. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  4327. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4328. await usage_on_print_start(
  4329. printer_id,
  4330. data,
  4331. printer_manager,
  4332. db=db,
  4333. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  4334. )
  4335. except Exception as e:
  4336. logger.warning("Usage tracker on_print_start failed: %s", e)
  4337. # Track if notification was sent (to avoid sending twice)
  4338. notification_sent = False
  4339. # Smart plug automation: turn on plug when print starts
  4340. try:
  4341. async with async_session() as db:
  4342. await smart_plug_manager.on_print_start(printer_id, db)
  4343. except Exception as e:
  4344. logger.warning("Smart plug on_print_start failed: %s", e)
  4345. async with async_session() as db:
  4346. from backend.app.models.printer import Printer
  4347. from backend.app.services.bambu_ftp import list_files_async
  4348. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4349. printer = result.scalar_one_or_none()
  4350. # Plate detection check - pause if objects detected on build plate
  4351. logger.info(
  4352. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  4353. )
  4354. if printer and printer.plate_detection_enabled:
  4355. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  4356. # Release the pooled DB connection before the plate-detection camera
  4357. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  4358. # printer SELECT has run so far — nothing to persist — so this commit
  4359. # is a data-noop that ends the read transaction and returns the
  4360. # connection to the pool during the I/O (issue #2572). expire_on_commit
  4361. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  4362. # archive lookups below re-acquire a fresh connection on next execute.
  4363. await db.commit()
  4364. try:
  4365. from backend.app.services.plate_detection import check_plate_empty
  4366. # Build ROI tuple from printer settings if available
  4367. roi = None
  4368. if all(
  4369. [
  4370. printer.plate_detection_roi_x is not None,
  4371. printer.plate_detection_roi_y is not None,
  4372. printer.plate_detection_roi_w is not None,
  4373. printer.plate_detection_roi_h is not None,
  4374. ]
  4375. ):
  4376. roi = (
  4377. printer.plate_detection_roi_x,
  4378. printer.plate_detection_roi_y,
  4379. printer.plate_detection_roi_w,
  4380. printer.plate_detection_roi_h,
  4381. )
  4382. # The light is held, not switched, so a live view opened
  4383. # meanwhile keeps it when the check lets go (SP-C11). Every
  4384. # printer, whatever the camera light mode: detection needs it.
  4385. plate_photo_data = None
  4386. objects_detected = False
  4387. check_failure: str | None = None
  4388. async with camera_light(printer, any_mode=True, settle=2.5):
  4389. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  4390. plate_result = await check_plate_empty(
  4391. printer_id=printer_id,
  4392. ip_address=printer.ip_address,
  4393. access_code=printer.access_code,
  4394. model=printer.model,
  4395. include_debug_image=False,
  4396. external_camera_url=printer.external_camera_url,
  4397. external_camera_type=printer.external_camera_type,
  4398. use_external=printer.external_camera_enabled,
  4399. roi=roi,
  4400. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  4401. )
  4402. # No reference to compare against is a check that did not
  4403. # run either: say so rather than call the plate empty.
  4404. check_failure = getattr(plate_result, "failure_reason", None) or (
  4405. "not_calibrated" if plate_result.needs_calibration else None
  4406. )
  4407. objects_detected = not check_failure and not plate_result.is_empty
  4408. if objects_detected:
  4409. # Objects detected - pause the print!
  4410. logger.warning(
  4411. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  4412. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  4413. )
  4414. pause_client = printer_manager.get_client(printer_id)
  4415. if pause_client:
  4416. pause_client.pause_print()
  4417. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  4418. # Snapshot while the light's still on — restoring it first
  4419. # would leave the notification with a dark photo.
  4420. try:
  4421. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  4422. except Exception as snap_err:
  4423. logger.warning(
  4424. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  4425. )
  4426. if objects_detected:
  4427. # Send notification about plate not empty
  4428. await ws_manager.broadcast(
  4429. {
  4430. "type": "plate_not_empty",
  4431. "printer_id": printer_id,
  4432. "printer_name": printer.name,
  4433. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  4434. }
  4435. )
  4436. # Also send push notification
  4437. try:
  4438. await notification_service.on_plate_not_empty(
  4439. printer_id=printer_id,
  4440. printer_name=printer.name,
  4441. db=db,
  4442. difference_percent=plate_result.difference_percent,
  4443. image_data=plate_photo_data,
  4444. )
  4445. except Exception as notif_err:
  4446. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4447. elif check_failure:
  4448. logger.warning(
  4449. "[PLATE CHECK] Plate check could not run for printer %s (%s): %s; proceeding with print",
  4450. printer_id,
  4451. check_failure,
  4452. plate_result.message,
  4453. )
  4454. await _announce_plate_check_failed(printer_id, printer.name, check_failure)
  4455. else:
  4456. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4457. except Exception as plate_err:
  4458. # Don't block print on plate detection errors
  4459. logger.warning(
  4460. "[PLATE CHECK] Plate check could not run for printer %s: %s; proceeding with print",
  4461. printer_id,
  4462. plate_err,
  4463. )
  4464. await _announce_plate_check_failed(printer_id, printer.name, "error")
  4465. if not printer:
  4466. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4467. if not notification_sent:
  4468. await _send_print_start_notification(printer_id, data, logger=logger)
  4469. return
  4470. # Skip the printer's own jobs — a calibration run is not a user's print.
  4471. # See is_internal_printer_job for what counts and why both fields are
  4472. # tested; the pressure-advance line reports as a subtask name with no
  4473. # /usr/ path, which the old prefix-only test here missed entirely.
  4474. #
  4475. # No notification either. The event describes the printer calibrating
  4476. # itself, so "Print started" is as wrong as the archive was, and the
  4477. # matching completion is suppressed in on_print_complete for the same
  4478. # reason. Checked before the auto-archive switches, whose "off" path
  4479. # still notifies.
  4480. # A /usr/ path is the printer's own file. A name alone is not proof: a
  4481. # print Bambuddy dispatched is never one, whatever it is called.
  4482. # Dispatched = an expected print, or, after a restart that lost those,
  4483. # a queue job printing on the printer.
  4484. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")) and (
  4485. (data.get("filename") or "").startswith("/usr/")
  4486. or not await _dispatched_by_bambuddy(db, printer_id, data.get("filename", ""), data.get("subtask_name", ""))
  4487. ):
  4488. logger.info(
  4489. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4490. data.get("filename", ""),
  4491. data.get("subtask_name", ""),
  4492. )
  4493. return
  4494. # The global switch is the master: off, no printer archives prints
  4495. # started outside Bambuddy; on, each printer's own switch decides.
  4496. from backend.app.api.routes.settings import get_setting
  4497. _global_auto_archive = await get_setting(db, "auto_archive")
  4498. archives_prints = printer.auto_archive and (
  4499. _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4500. )
  4501. if not archives_prints:
  4502. # auto-archive disabled — check if there's an expected print (dispatched
  4503. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4504. # If so, fall through to the expected-print handling below so the archive
  4505. # is tracked in _active_prints and usage tracking works at completion.
  4506. _fn = data.get("filename", "")
  4507. _sn = data.get("subtask_name", "")
  4508. _check_keys: list[tuple[int, str]] = []
  4509. if _sn:
  4510. _check_keys += [
  4511. (printer_id, _sn),
  4512. (printer_id, f"{_sn}.3mf"),
  4513. (printer_id, f"{_sn}.gcode.3mf"),
  4514. ]
  4515. if _fn:
  4516. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4517. _check_keys.append((printer_id, _base_fn))
  4518. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4519. _check_keys += [
  4520. (printer_id, _no_archive_base),
  4521. (printer_id, f"{_no_archive_base}.3mf"),
  4522. ]
  4523. _has_expected = any(k in _expected_prints for k in _check_keys)
  4524. if not _has_expected:
  4525. # No expected print — truly external print (started from slicer/touchscreen)
  4526. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4527. if not notification_sent:
  4528. _no_archive_creator: int | None = None
  4529. for _key in _check_keys:
  4530. _expected_prints.pop(_key, None)
  4531. _expected_print_registered_at.pop(_key, None)
  4532. popped_creator = _expected_print_creators.pop(_key, None)
  4533. if _no_archive_creator is None:
  4534. _no_archive_creator = popped_creator
  4535. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4536. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4537. return
  4538. else:
  4539. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4540. # Get the filename and subtask_name
  4541. filename = data.get("filename", "")
  4542. subtask_name = data.get("subtask_name", "")
  4543. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4544. # present, it lets us match an archive across a backend restart (#972):
  4545. # same id → same print → resume the existing row instead of cancelling
  4546. # it and recreating from scratch (which loses started_at). Treat "0"
  4547. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4548. raw_mqtt = data.get("raw_data") or {}
  4549. subtask_id = raw_mqtt.get("subtask_id")
  4550. if subtask_id is not None:
  4551. subtask_id = str(subtask_id).strip()
  4552. if subtask_id in ("", "0"):
  4553. subtask_id = None
  4554. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4555. if not filename and not subtask_name:
  4556. # Send notification without archive data (no filename)
  4557. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4558. if not notification_sent:
  4559. await _send_print_start_notification(printer_id, data, logger=logger)
  4560. return
  4561. # Check if this is an expected print from reprint/scheduled
  4562. expected_keys = _expected_print_keys(printer_id, filename, subtask_name)
  4563. expected_archive_id = None
  4564. # Who queued it, taken with the entries it was registered beside: left
  4565. # behind once those are gone (the archive deleted mid-dispatch, or the
  4566. # start notification already sent), the expiry never saw it, and an
  4567. # unrelated later print of that name was attributed to that user (EP-2).
  4568. fallback_creator = None
  4569. for key in expected_keys:
  4570. expected_archive_id = _expected_prints.pop(key, None)
  4571. _expected_print_registered_at.pop(key, None)
  4572. if expected_archive_id:
  4573. # Clean up other possible keys for this print
  4574. for other_key in expected_keys:
  4575. _expected_prints.pop(other_key, None)
  4576. _expected_print_registered_at.pop(other_key, None)
  4577. creator = _expected_print_creators.pop(other_key, None)
  4578. if fallback_creator is None:
  4579. fallback_creator = creator
  4580. break
  4581. if expected_archive_id:
  4582. # This is a reprint/scheduled print - use existing archive, don't create new one
  4583. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4584. # Bambuddy dispatched it: the kill switch's fast path keeps it as
  4585. # Bambuddy's once the expected entry is consumed here.
  4586. _owned_print_archive_ids.add(expected_archive_id)
  4587. from backend.app.models.archive import PrintArchive
  4588. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4589. archive = result.scalar_one_or_none()
  4590. # Deleted after this handler loaded it (the plate check waits
  4591. # seconds) but before the route forgot the expected print: the
  4592. # archive the route kept or deleted is left as the route left it.
  4593. if archive and await _printer_gone(db, printer_id):
  4594. logger.info(
  4595. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4596. )
  4597. await forget_printer(printer_id)
  4598. return
  4599. if archive:
  4600. # As it was before this adoption: put back if the printer turns
  4601. # out to have been deleted while it was adopted (below).
  4602. before_adoption = {
  4603. attr.columns[0].name: getattr(archive, attr.key)
  4604. for attr in sa_inspect(PrintArchive).column_attrs
  4605. if attr.key != "id"
  4606. }
  4607. # Update archive status to printing
  4608. archive.status = "printing"
  4609. archive.started_at = datetime.now(timezone.utc)
  4610. # The previous run's outcome is not this one's: a reprint that
  4611. # completes must not keep showing why the last one failed.
  4612. archive.failure_reason = None
  4613. archive.completed_at = None
  4614. # The previous run's answer is still on this row and the
  4615. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4616. # so without a reset the second run inherits the first run's
  4617. # verdict: no prompt at all, and a green "good" badge on a run
  4618. # nobody ever judged.
  4619. if archive.confirm_requested:
  4620. archive.user_verdict = None
  4621. archive.user_verdict_source = None
  4622. archive.user_verdict_at = None
  4623. archive.confirm_token = None
  4624. archive.confirm_token_used_at = None
  4625. # Reprint of an archive reuses the source row. Without resetting
  4626. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4627. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4628. # extracts the *original* print's last frame, which then ships in
  4629. # the completion notification (#1707). Clear the path so the
  4630. # scanner runs fresh; also unlink the old video file so reprints
  4631. # don't accumulate orphans in the archive directory. Photos list
  4632. # is left alone — accumulating one finish photo per run is fine.
  4633. # The print-start baseline (#2704) is stale for the same reason:
  4634. # it describes the printer before the previous run. The capture
  4635. # below overwrites it, but clear it here too so an early failure
  4636. # can't leave the scan diffing against the wrong snapshot.
  4637. #
  4638. # Unlinked only when it is the same plate printing again. Every
  4639. # plate of a Send All shares this archive, and the video on it
  4640. # can be the only copy of another plate's run -- the printer's
  4641. # was deleted once it attached (#3275). That one is left in the
  4642. # archive directory, which goes with the archive. A video whose
  4643. # plate is not on record (attached by hand, or before the
  4644. # column existed) is kept too where the 3MF has other plates,
  4645. # or cannot be read: nothing tells it apart from another plate's,
  4646. # and keeping costs one file where deleting can cost the only
  4647. # copy. On an archive with exactly one plate it is that plate's.
  4648. archive.timelapse_baseline = None
  4649. stale_timelapse_relpath = archive.timelapse_path
  4650. stale_timelapse_plate_id = archive.timelapse_plate_id
  4651. starting_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4652. if stale_timelapse_relpath:
  4653. archive.timelapse_path = None
  4654. archive.timelapse_plate_id = None
  4655. stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
  4656. if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
  4657. from backend.app.services.archive import plate_indexes_in_3mf
  4658. plates = await asyncio.to_thread(
  4659. plate_indexes_in_3mf,
  4660. app_settings.base_dir / archive.file_path, # SEC-PATH-OK: stored relative archive path
  4661. )
  4662. stale_is_this_plates = len(plates) == 1
  4663. if stale_timelapse_relpath and not stale_is_this_plates:
  4664. logger.info(
  4665. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4666. stale_timelapse_relpath,
  4667. stale_timelapse_plate_id,
  4668. expected_archive_id,
  4669. starting_plate_id,
  4670. )
  4671. # The video is deleted once the adoption stands (below).
  4672. delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
  4673. # Persist a restart-stable id so a later restart resumes this
  4674. # archive by subtask_id instead of name-matching + duplicating
  4675. # it (#1485). The printer often hasn't echoed subtask_id back
  4676. # this soon after dispatch, so fall back to the id Bambuddy
  4677. # minted when it sent the print command. Scoped to this
  4678. # expected-print branch on purpose: an expected match means
  4679. # Bambuddy dispatched this exact print in this process, so the
  4680. # client's last-dispatch id genuinely belongs to it — using it
  4681. # for an externally-started print could mis-tag the archive.
  4682. effective_subtask_id = subtask_id
  4683. if not effective_subtask_id:
  4684. _client = printer_manager.get_client(printer_id)
  4685. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4686. if _dispatched:
  4687. effective_subtask_id = str(_dispatched).strip() or None
  4688. # Update on first-set OR on reprint (the queue dispatcher mints
  4689. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4690. # the rewrite for reprints leaves the archive holding the FIRST
  4691. # run's id; if MQTT then reconnects mid-print, the reconciler
  4692. # (#1542) compares the stale stored id against the printer's
  4693. # live id, sees a mismatch, and synthesises a bogus PRINT
  4694. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4695. # in #1807. Inequality check preserves the noop-on-stable-push
  4696. # behaviour the earlier `not archive.subtask_id` guard provided.
  4697. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4698. archive.subtask_id = effective_subtask_id
  4699. # #1403 follow-up: VP-queue archives are created with
  4700. # printer_id=None at queue-add time (we don't know which
  4701. # printer will run the job yet). When the print actually
  4702. # starts on a specific printer the expected-archive lookup
  4703. # used to skip this assignment, leaving printer_id=None
  4704. # forever — which then disables the "Scan for timelapse"
  4705. # button in ArchivesPage (gated on !archive.printer_id).
  4706. if archive.printer_id != printer_id:
  4707. archive.printer_id = printer_id
  4708. adopting_id = archive.id # a rollback expires the object
  4709. try:
  4710. await db.commit()
  4711. except (IntegrityError, StaleDataError):
  4712. # The archive stays unchanged, or is gone: "delete archives"
  4713. # removed the row under the adoption, which then matched no
  4714. # row (StaleDataError) rather than being refused.
  4715. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4716. return
  4717. raise
  4718. # The printer can be deleted between the check above and this
  4719. # commit (the route's transaction lasts seconds), and the commit
  4720. # then adopted the archive anyway: status, verdict and timelapse
  4721. # changed, and the deleted printer's id written on a row the
  4722. # route had detached or never touched. Undo the adoption.
  4723. if await _printer_gone(db, printer_id):
  4724. logger.info(
  4725. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4726. printer_id,
  4727. archive.id,
  4728. )
  4729. # Everything as before this adoption. The printer it had
  4730. # then stays, unless it was the deleted one: the route
  4731. # detached that row (kept) or deleted it (no row matches).
  4732. previous_printer = before_adoption["printer_id"]
  4733. await db.execute(
  4734. update(PrintArchive)
  4735. .where(PrintArchive.id == archive.id)
  4736. .values(
  4737. {
  4738. **before_adoption,
  4739. "printer_id": None if previous_printer == printer_id else previous_printer,
  4740. }
  4741. )
  4742. )
  4743. await db.commit()
  4744. await forget_printer(printer_id)
  4745. return
  4746. await _drop_replaced_plate_videos(
  4747. db,
  4748. archive.id,
  4749. starting_plate_id,
  4750. stale_timelapse_relpath if delete_stale_video else None,
  4751. logger,
  4752. )
  4753. # Track as active print
  4754. _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
  4755. await _open_run_for(archive.id, printer_id, subtask_id)
  4756. # Start timelapse session if external camera is enabled (#1353).
  4757. # Queue / VP-dispatched prints land here in the expected-archive
  4758. # branch and used to skip start_session entirely — frames were
  4759. # never captured and the post-print stitch silently returned None.
  4760. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4761. # Inject ams_mapping into usage tracker session — the session was created
  4762. # before expected-print promotion, so it may have ams_mapping=None when
  4763. # the MQTT request topic subscription failed (common on P1S/A1).
  4764. _stored_map = _print_ams_mappings.get((printer_id, expected_archive_id))
  4765. _stored_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4766. if _stored_map or _stored_plate_id is not None:
  4767. try:
  4768. from backend.app.services.usage_tracker import _active_sessions
  4769. _ut_session = _active_sessions.get(printer_id)
  4770. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4771. _ut_session.ams_mapping = _stored_map
  4772. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4773. # plate_id injection covers direct-Print of plate N of a multi-plate
  4774. # 3MF — queue prints already capture it via the on_print_start queue
  4775. # lookup, but direct-Print never goes through the queue (#1697).
  4776. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4777. _ut_session.plate_id = _stored_plate_id
  4778. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4779. except Exception:
  4780. pass
  4781. # Set up energy tracking (#941: persist start on archive row)
  4782. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4783. await ws_manager.send_archive_updated(
  4784. {
  4785. "id": archive.id,
  4786. "status": "printing",
  4787. }
  4788. )
  4789. # Send notification with archive data (reprint/scheduled)
  4790. if not notification_sent:
  4791. # Use archive's created_by_id; fall back to the creator registered via
  4792. # register_expected_print (handles library-file-based queue items where
  4793. # the freshly-created archive has no created_by_id yet), taken above.
  4794. archive_data = {
  4795. "print_time_seconds": archive.print_time_seconds,
  4796. "created_by_id": archive.created_by_id or fallback_creator,
  4797. }
  4798. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4799. # Extract printable objects from the archived 3MF file
  4800. _load_objects_from_archive(archive, printer_id, logger)
  4801. if archive.file_path:
  4802. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  4803. # Store Spoolman tracking data for per-filament usage reporting
  4804. try:
  4805. await _store_spoolman_print_data(
  4806. printer_id,
  4807. archive.id,
  4808. archive.file_path,
  4809. db,
  4810. printer_manager,
  4811. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4812. plate_id=_get_start_plate_id(printer_id, archive.id),
  4813. )
  4814. except Exception as e:
  4815. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4816. # Price the print from its spools now rather than only at completion (#3261)
  4817. _schedule_archive_cost_estimate(
  4818. printer_id,
  4819. archive.id,
  4820. printer_manager,
  4821. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4822. plate_id=_get_start_plate_id(printer_id, archive.id),
  4823. session_factory=async_session,
  4824. )
  4825. # Capture timelapse file baseline for snapshot-diff on completion
  4826. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4827. # hit this branch — without the baseline the completion-time scan
  4828. # falls into its "take baseline now" fallback, which snapshots
  4829. # AFTER the new MP4 already exists and never matches a diff
  4830. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4831. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4832. await _forget_if_printer_gone(printer_id)
  4833. return # Skip creating a new archive
  4834. # The archive was deleted after the job was queued.
  4835. if not archives_prints:
  4836. # Only the expected print brought a printer that does not
  4837. # archive this far; with it gone, nothing is archived.
  4838. return
  4839. # Otherwise archive the print anew rather than drop it, so it still
  4840. # gets its notification, usage tracking and history.
  4841. logger.warning(
  4842. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4843. expected_archive_id,
  4844. printer_id,
  4845. )
  4846. # Check if there's already a "printing" archive for this printer/file
  4847. # This prevents duplicates when backend restarts during an active print
  4848. from backend.app.models.archive import PrintArchive
  4849. existing_archive: PrintArchive | None = None
  4850. resumed_by_run = False
  4851. # Best match: this job's run, open on the printer since the print
  4852. # started. The archive row is shared by every plate of it, and its
  4853. # printer, job id and status are the latest start's, which may be
  4854. # another printer's.
  4855. if subtask_id:
  4856. from backend.app.services.print_log import open_run_on_printer
  4857. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  4858. if run is not None and run.archive_id is not None:
  4859. existing_archive = await db.scalar(
  4860. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  4861. )
  4862. resumed_by_run = existing_archive is not None
  4863. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4864. # across a backend restart for the same print, so this is the most
  4865. # reliable way to reattach. Only a row still printing: a cancelled one
  4866. # has been through completion (usage, history, notifications) already,
  4867. # and reopening it would count the print twice.
  4868. if subtask_id and existing_archive is None:
  4869. by_id = await db.execute(
  4870. select(PrintArchive)
  4871. .where(PrintArchive.printer_id == printer_id)
  4872. .where(PrintArchive.subtask_id == subtask_id)
  4873. .where(PrintArchive.status == "printing")
  4874. .order_by(PrintArchive.created_at.desc())
  4875. .limit(1)
  4876. )
  4877. existing_archive = by_id.scalar_one_or_none()
  4878. # Fallback match: name-based lookup. Kept as-is for prints whose
  4879. # subtask_id is missing ("0" / local / non-cloud prints).
  4880. if existing_archive is None:
  4881. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4882. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4883. # A print started from the printer's screen names its file in full,
  4884. # so the forms above double its extension. The file itself is the
  4885. # one exact match, and nothing looser is added (#3009).
  4886. if _subtask_is_the_file(subtask_name, filename):
  4887. archive_filenames.append(subtask_name)
  4888. existing = await db.execute(
  4889. select(PrintArchive)
  4890. .where(PrintArchive.printer_id == printer_id)
  4891. .where(PrintArchive.status == "printing")
  4892. .where(
  4893. or_(
  4894. PrintArchive.print_name == check_name,
  4895. PrintArchive.filename.in_(archive_filenames),
  4896. )
  4897. )
  4898. .order_by(PrintArchive.created_at.desc())
  4899. .limit(1)
  4900. )
  4901. existing_archive = existing.scalar_one_or_none()
  4902. if existing_archive:
  4903. # subtask_id match → always resume, regardless of age. Same print,
  4904. # just a backend restart.
  4905. subtask_match = resumed_by_run or bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4906. if subtask_match:
  4907. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4908. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4909. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  4910. _mark_owned_if_dispatched(existing_archive)
  4911. if await _run_needs_energy_start(existing_archive, printer_id, db):
  4912. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4913. if not notification_sent:
  4914. archive_data = {
  4915. "print_time_seconds": existing_archive.print_time_seconds,
  4916. "created_by_id": existing_archive.created_by_id,
  4917. }
  4918. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4919. _load_objects_from_archive(existing_archive, printer_id, logger)
  4920. if existing_archive.file_path:
  4921. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  4922. return
  4923. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4924. # stale from the printer's *current* progress, not wall-clock age.
  4925. # A genuinely long print used to trip a blind 4h cutoff and have its
  4926. # live archive cancelled + duplicated on every backend restart
  4927. # (#1485). If the printer reports real progress, this name-matched
  4928. # 'printing' archive IS that ongoing print — resume it whatever its
  4929. # age. Only treat it as a stale leftover when the printer clearly
  4930. # shows a different, freshly-started print: near-0% progress on an
  4931. # archive far too old to still be at 0%. Unknown progress (printer
  4932. # not connected) never cancels — resuming is the safe default.
  4933. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4934. live_status = printer_manager.get_status(printer_id)
  4935. live_progress = getattr(live_status, "progress", None) if live_status else None
  4936. looks_stale = (
  4937. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4938. )
  4939. # Two subtask ids are two prints, however young the archive: one
  4940. # whose completion was missed must not swallow the next print of
  4941. # the same file. Except Bambuddy's own reprint, which reuses the
  4942. # row and mints a fresh id (#1807): the id it last sent says so,
  4943. # and after a restart, which forgets it, this printer's queue job
  4944. # running the archive.
  4945. if (
  4946. not looks_stale
  4947. and subtask_id
  4948. and existing_archive.subtask_id
  4949. and existing_archive.subtask_id != subtask_id
  4950. ):
  4951. _client = printer_manager.get_client(printer_id)
  4952. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  4953. if _dispatched:
  4954. looks_stale = _dispatched != subtask_id
  4955. else:
  4956. from backend.app.models.print_queue import PrintQueueItem as _PQI
  4957. queue_run = await db.scalar(
  4958. select(_PQI.id)
  4959. .where(_PQI.archive_id == existing_archive.id)
  4960. .where(_PQI.printer_id == printer_id)
  4961. .where(_PQI.status == "printing")
  4962. .limit(1)
  4963. )
  4964. looks_stale = queue_run is None
  4965. if looks_stale:
  4966. logger.warning(
  4967. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  4968. " — marking cancelled and creating new archive",
  4969. existing_archive.id,
  4970. archive_age,
  4971. live_progress,
  4972. existing_archive.subtask_id,
  4973. subtask_id,
  4974. )
  4975. existing_archive.status = "cancelled"
  4976. # Canonical key, not a sentence (issue #2974). "No status update
  4977. # received" is what both stale paths actually observed; which of
  4978. # the two it was is already carried by ``status`` -- cancelled
  4979. # here, the reconciled outcome at the reconnect site -- so one
  4980. # key loses no information and gives the Statistics breakdown a
  4981. # single bucket instead of two untranslatable prose strings.
  4982. existing_archive.failure_reason = "noStatusUpdate"
  4983. # And its run, as before runs were opened at the start: a new
  4984. # print starts on the printer, so whatever is open there ended
  4985. # unseen. Left open, the next reconnect would close it again.
  4986. from backend.app.services.print_log import discard_open_runs
  4987. await discard_open_runs(db, printer_id)
  4988. await db.commit()
  4989. # Its print keys go with it; the new archive registers its own.
  4990. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id and k[0] == printer_id]:
  4991. del _active_prints[_key]
  4992. # Fall through to create new archive (don't return)
  4993. else:
  4994. logger.info(
  4995. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4996. )
  4997. # Track this as the active print
  4998. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4999. _mark_owned_if_dispatched(existing_archive)
  5000. # Attach subtask_id retroactively so future restarts can resume.
  5001. # Compare for inequality (not "is empty") to also pick up reprint
  5002. # dispatches that mint a fresh id — see #1807 for the bogus
  5003. # "Print Stopped" the strict-empty guard caused on reconnect.
  5004. if subtask_id and existing_archive.subtask_id != subtask_id:
  5005. existing_archive.subtask_id = subtask_id
  5006. await db.commit()
  5007. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  5008. # Also set up energy tracking if not already tracked (#941: persisted column)
  5009. if await _run_needs_energy_start(existing_archive, printer_id, db):
  5010. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  5011. # Send notification with archive data (existing archive)
  5012. if not notification_sent:
  5013. archive_data = {
  5014. "print_time_seconds": existing_archive.print_time_seconds,
  5015. "created_by_id": existing_archive.created_by_id,
  5016. }
  5017. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5018. # Extract printable objects from the archived 3MF file
  5019. _load_objects_from_archive(existing_archive, printer_id, logger)
  5020. if existing_archive.file_path:
  5021. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  5022. return
  5023. # Build list of possible 3MF filenames to try
  5024. possible_names = []
  5025. # Bambu printers typically store files as "Name.gcode.3mf"
  5026. # The subtask_name is usually the best source for the filename
  5027. if subtask_name:
  5028. if _subtask_is_the_file(subtask_name, filename):
  5029. # A print started from the printer's own screen reports the
  5030. # file's full name, extension included. That is the file, so
  5031. # no extension is appended to it (#3009).
  5032. possible_names.append(subtask_name)
  5033. else:
  5034. # Try common Bambu naming patterns
  5035. possible_names.append(f"{subtask_name}.gcode.3mf")
  5036. possible_names.append(f"{subtask_name}.3mf")
  5037. # Try original filename with .3mf extension
  5038. if filename:
  5039. # Extract just the filename part, not the full path
  5040. fname = filename.split("/")[-1] if "/" in filename else filename
  5041. if fname.endswith(".3mf"):
  5042. possible_names.append(fname)
  5043. elif fname.endswith(".gcode"):
  5044. base = fname.rsplit(".", 1)[0]
  5045. possible_names.append(f"{base}.gcode.3mf")
  5046. possible_names.append(f"{base}.3mf")
  5047. else:
  5048. possible_names.append(f"{fname}.gcode.3mf")
  5049. possible_names.append(f"{fname}.3mf")
  5050. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  5051. space_variants = []
  5052. for name in possible_names:
  5053. if " " in name:
  5054. space_variants.append(name.replace(" ", "_"))
  5055. possible_names.extend(space_variants)
  5056. # Remove duplicates while preserving order
  5057. seen = set()
  5058. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  5059. logger.info("Trying filenames: %s", possible_names)
  5060. # Release the pooled DB connection before the 3MF FTP download. Reaching
  5061. # here means none of the expected-/existing-archive write branches ran
  5062. # (they all return earlier) — only SELECTs have executed on this path, so
  5063. # this commit persists nothing; it ends the read transaction so the
  5064. # connection returns to the pool during the download. That download tries
  5065. # up to five remote paths per candidate filename with retry/backoff and
  5066. # can run for minutes under FTP contention; holding the session across it
  5067. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  5068. # work runs during the download — the new-archive writes below re-acquire
  5069. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  5070. await db.commit()
  5071. # Try to find and download the 3MF file
  5072. temp_path = None
  5073. downloaded_filename = None
  5074. # Cache check: cover endpoint may have already pulled this 3MF during
  5075. # the print (frontend opens the card and shows the thumbnail) — reuse
  5076. # that file instead of re-downloading 36MB over the same FTP link that
  5077. # just served it (#972). The cache keys on a normalized filename so
  5078. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  5079. for try_filename in possible_names:
  5080. if not try_filename.endswith(".3mf"):
  5081. continue
  5082. cached = get_cached_3mf(printer_id, try_filename)
  5083. if cached:
  5084. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  5085. temp_path = cached
  5086. downloaded_filename = try_filename
  5087. break
  5088. # Does this printer keep the sliced file somewhere FTPS can reach? On
  5089. # H2-series and P2S the answer is routinely no — the file stays on
  5090. # internal eMMC and port 990 only ever serves external storage — and
  5091. # then the whole sweep below (six filenames x five directories x four
  5092. # retries, then the directory walk) is ~110 connections that cannot
  5093. # succeed. Skip it and say why (#2780).
  5094. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  5095. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  5096. # running rather than because the file is somewhere unreachable. The
  5097. # distinction is the whole of #2957: one is permanent, the other clears
  5098. # in minutes with the file still sitting on the printer.
  5099. blocked_by_ftps_cooloff = False
  5100. # Set when a probe reached the printer and still came back without the
  5101. # file -- a timeout mid-transfer, a refused connection, anything that is
  5102. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  5103. # caught by name below, so a file that genuinely is not on the card
  5104. # leaves this False and schedules nothing. Anything else means the
  5105. # transfer, not the file, is what failed, and that does not last (#3063).
  5106. ftp_transfer_failed = False
  5107. # The narrower case of the above: the directory walk *listed* a file
  5108. # for this print and could not fetch it, so the file is on the card
  5109. # under a name that matches. The only failure that rules out an
  5110. # earlier run's 3MF standing in for it (#3307).
  5111. walk_transfer_failed = False
  5112. # Paths the sweep reached and could not transfer -- a timeout, not a
  5113. # 550. The directory walk lists the same folders and would download
  5114. # the same file again: on a slow A1 that was a second 300 s on the
  5115. # printer's one FTPS slot, at print start, for a file the recovery
  5116. # retry fetches with a deadline twice as long (#3308).
  5117. sweep_failed_paths: set[str] = set()
  5118. # The print's name, for a fallback archive whose `subtask_name` the
  5119. # plate guard below had to disown. Display only, and deliberately kept
  5120. # apart from `subtask_name`: that variable is what every file lookup
  5121. # here is built from, and once a name has been shown to fetch another
  5122. # plate's 3MF it must not key `_active_prints` either, or the cover
  5123. # endpoint hands the same contradicted file to
  5124. # `_recover_fallback_archive` and fills the row in with it (#3126).
  5125. display_name_after_plate_reject: str | None = None
  5126. # Get FTP retry settings
  5127. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  5128. # ...but "the printer put it on eMMC" is where it went, not whether we
  5129. # can read it. An H2D with a card in mirrors the job to /cache and
  5130. # serves it happily, and skipping on the URL alone cost that reporter
  5131. # every archive for two days (#2856). So ask the printer instead of
  5132. # guessing: the dispatch named the exact file, which is one connection
  5133. # walking five paths rather than the sweep's ~110. Only when the probe
  5134. # comes back empty does the verdict's reason stand.
  5135. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  5136. if ftps_handshake_blocked(printer.ip_address):
  5137. # Deliberately NOT recorded as a cool-off give-up. This branch
  5138. # only runs on an unreachable verdict, and that verdict is the
  5139. # honest, permanent reason the archive is empty — the probe was
  5140. # a long shot on top of it. Blaming the cool-off here would
  5141. # schedule a retry for a file sitting on internal eMMC, which is
  5142. # the sweep #2780 removed (#2957).
  5143. logger.debug(
  5144. "Not probing for %s on printer %s: its file service is not answering over TLS",
  5145. storage.probe_filename,
  5146. printer_id,
  5147. )
  5148. else:
  5149. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  5150. probe_path.parent.mkdir(parents=True, exist_ok=True)
  5151. try:
  5152. probe_hit = await download_file_try_paths_async(
  5153. printer.ip_address,
  5154. printer.access_code,
  5155. ftp_probe_paths(storage.probe_filename),
  5156. probe_path,
  5157. socket_timeout=ftp_timeout,
  5158. printer_model=printer.model,
  5159. )
  5160. except Exception as e:
  5161. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  5162. probe_hit = False
  5163. if probe_hit:
  5164. downloaded_filename = storage.probe_filename
  5165. temp_path = probe_path
  5166. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  5167. # Naming the path, not just the file: a printer that keeps
  5168. # uploads around for weeks can serve a same-named copy of an
  5169. # earlier slice, and without the directory in the log that
  5170. # mismatch is invisible rather than merely rare (#1820).
  5171. logger.info(
  5172. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  5173. downloaded_filename,
  5174. probe_hit,
  5175. printer_id,
  5176. storage.reason,
  5177. )
  5178. if not storage.reachable and not downloaded_filename:
  5179. # Same opening words whether or not a probe ran, because that is
  5180. # the phrase support asks people to grep for — only the tail says
  5181. # which of the two happened.
  5182. logger.info(
  5183. "Skipping the 3MF lookup for printer %s: %s — %s",
  5184. printer_id,
  5185. storage.reason,
  5186. "no copy of it on external storage either"
  5187. if storage.probe_filename
  5188. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  5189. )
  5190. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  5191. if not try_filename.endswith(".3mf"):
  5192. continue
  5193. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  5194. # printers, so try it first — deferring it to last cost #972's reporter
  5195. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  5196. # landing on the path that actually had the file.
  5197. remote_paths = [
  5198. f"/{try_filename}",
  5199. f"/cache/{try_filename}",
  5200. f"/model/{try_filename}",
  5201. f"/data/{try_filename}",
  5202. f"/data/Metadata/{try_filename}",
  5203. ]
  5204. temp_path = app_settings.archive_dir / "temp" / try_filename
  5205. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5206. for remote_path in remote_paths:
  5207. if ftps_handshake_blocked(printer.ip_address):
  5208. # The printer's FTPS service is not completing a TLS
  5209. # handshake, so it has no path we could reach — walking the
  5210. # remaining candidates only re-runs the same failure
  5211. # (#2780). Fall through to the no-3MF archive now.
  5212. #
  5213. # Remember *why*, though. This is the one give-up that is
  5214. # temporary: the cool-off clears in minutes and the file was
  5215. # on the printer the whole time. The fallback archive is
  5216. # stamped with it so a retry can be scheduled, and so the
  5217. # Archives banner stops blaming storage (#2957).
  5218. blocked_by_ftps_cooloff = True
  5219. logger.warning(
  5220. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  5221. printer_id,
  5222. )
  5223. break
  5224. logger.debug("Trying FTP download: %s", remote_path)
  5225. try:
  5226. if ftp_retry_enabled:
  5227. downloaded = await with_ftp_retry(
  5228. download_file_async,
  5229. printer.ip_address,
  5230. printer.access_code,
  5231. remote_path,
  5232. temp_path,
  5233. timeout=ftp_timeout,
  5234. socket_timeout=ftp_timeout,
  5235. printer_model=printer.model,
  5236. max_retries=ftp_retry_count,
  5237. retry_delay=ftp_retry_delay,
  5238. operation_name=f"Download 3MF from {remote_path}",
  5239. cooloff_ip=printer.ip_address,
  5240. non_retry_exceptions=(FileNotOnPrinterError,),
  5241. )
  5242. else:
  5243. downloaded = await download_file_async(
  5244. printer.ip_address,
  5245. printer.access_code,
  5246. remote_path,
  5247. temp_path,
  5248. timeout=ftp_timeout,
  5249. socket_timeout=ftp_timeout,
  5250. printer_model=printer.model,
  5251. )
  5252. if downloaded:
  5253. downloaded_filename = try_filename
  5254. logger.info("Downloaded: %s", remote_path)
  5255. # Populate shared cache so the cover endpoint (if it
  5256. # runs next) doesn't refetch the same 36MB over FTP.
  5257. cache_3mf_download(printer_id, try_filename, temp_path)
  5258. break
  5259. # with_ftp_retry returns None once it has spent its budget,
  5260. # and download_file_async returns False on a timeout, so an
  5261. # exhausted transfer arrives here rather than as an
  5262. # exception (#3063).
  5263. ftp_transfer_failed = True
  5264. sweep_failed_paths.add(remote_path)
  5265. except FileNotOnPrinterError:
  5266. # 550 — file isn't at this path. Advance to next candidate
  5267. # without burning the retry budget.
  5268. logger.debug("3MF not at %s (550), trying next path", remote_path)
  5269. except Exception as e:
  5270. ftp_transfer_failed = True
  5271. sweep_failed_paths.add(remote_path)
  5272. logger.debug("FTP download failed for %s: %s", remote_path, e)
  5273. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  5274. break
  5275. # If still not found, try listing directories to find matching file
  5276. # Different printer models use different directory structures. Skipped
  5277. # when the printer's FTPS handshake is failing — the directory walk is
  5278. # five more connections that cannot get further than the download did.
  5279. if (
  5280. not downloaded_filename
  5281. and storage.reachable
  5282. and (filename or subtask_name)
  5283. and not ftps_handshake_blocked(printer.ip_address)
  5284. ):
  5285. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  5286. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  5287. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  5288. # Every folder is listed before one file is picked, so a file named
  5289. # for the print in a later folder wins over one that merely
  5290. # contains the name in an earlier folder.
  5291. listed_paths: list[str] = []
  5292. for search_dir in search_dirs:
  5293. try:
  5294. dir_files = await list_files_async(
  5295. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  5296. )
  5297. except Exception as e:
  5298. logger.debug("Failed to list %s: %s", search_dir, e)
  5299. continue
  5300. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  5301. if threemf_files:
  5302. logger.info(
  5303. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  5304. )
  5305. listed_paths += [
  5306. posixpath.join(search_dir, f.get("name", "")) for f in dir_files if not f.get("is_directory")
  5307. ]
  5308. for remote_full_path in _3mf_files_for_print(listed_paths, search_term):
  5309. if remote_full_path in sweep_failed_paths:
  5310. # Listed for this print, and its transfer already failed:
  5311. # the same as a failed walk download, without spending a
  5312. # second deadline on it. Skipping it cannot hand the walk a
  5313. # look-alike: while a file of the print's own name is
  5314. # listed, files that merely contain the name are not.
  5315. logger.info(
  5316. "Not downloading %s again: its transfer already failed; the recovery retry will fetch it",
  5317. remote_full_path,
  5318. )
  5319. walk_transfer_failed = True
  5320. continue
  5321. fname = posixpath.basename(remote_full_path)
  5322. logger.info("Found matching file: %s", remote_full_path)
  5323. temp_path = app_settings.archive_dir / "temp" / fname
  5324. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5325. try:
  5326. if ftp_retry_enabled:
  5327. downloaded = await with_ftp_retry(
  5328. download_file_async,
  5329. printer.ip_address,
  5330. printer.access_code,
  5331. remote_full_path,
  5332. temp_path,
  5333. timeout=ftp_timeout,
  5334. socket_timeout=ftp_timeout,
  5335. printer_model=printer.model,
  5336. max_retries=ftp_retry_count,
  5337. retry_delay=ftp_retry_delay,
  5338. operation_name=f"Download 3MF from {remote_full_path}",
  5339. cooloff_ip=printer.ip_address,
  5340. )
  5341. else:
  5342. downloaded = await download_file_async(
  5343. printer.ip_address,
  5344. printer.access_code,
  5345. remote_full_path,
  5346. temp_path,
  5347. timeout=ftp_timeout,
  5348. socket_timeout=ftp_timeout,
  5349. printer_model=printer.model,
  5350. )
  5351. except Exception as e:
  5352. logger.debug("Failed to download %s: %s", remote_full_path, e)
  5353. continue
  5354. if downloaded:
  5355. downloaded_filename = fname
  5356. logger.info("Found and downloaded: %s", remote_full_path)
  5357. cache_3mf_download(printer_id, fname, temp_path)
  5358. break
  5359. # The listing named the file, so it is on the card;
  5360. # only the transfer failed (#3063).
  5361. ftp_transfer_failed = True
  5362. walk_transfer_failed = True
  5363. # A "Print again" on the printer's screen names no file Bambuddy can
  5364. # find: only its history copy under a generic name, and the 3MF's
  5365. # internal title (#3307). When an earlier run of the same job was
  5366. # archived, its 3MF is the one being printed again. Not when the
  5367. # directory walk listed a file for this print and only its transfer
  5368. # failed: that file is on the card, and the retry fetches it. A
  5369. # cool-off or a failed sweep path is no such evidence -- the retry
  5370. # tries the same names, which this print's file never had.
  5371. reused_3mf_from: int | None = None
  5372. if not downloaded_filename and not walk_transfer_failed:
  5373. reported_layers = raw_mqtt.get("total_layer_num")
  5374. earlier = await _archived_3mf_for_repeat(
  5375. db,
  5376. printer_id,
  5377. subtask_name,
  5378. filename,
  5379. reported_layers if isinstance(reported_layers, int) and reported_layers > 0 else None,
  5380. )
  5381. if earlier is not None:
  5382. reuse_name = Path(earlier.filename or "").name or f"archive_{earlier.id}.3mf"
  5383. # Per printer: two printers reprinting the same job at once
  5384. # must not write one temp file (archive_print names the
  5385. # archive after original_filename, not this path).
  5386. reuse_path = app_settings.archive_dir / "temp" / f"reprint_{printer_id}_{reuse_name}"
  5387. try:
  5388. reuse_path.parent.mkdir(parents=True, exist_ok=True)
  5389. await asyncio.to_thread(shutil.copyfile, app_settings.base_dir / earlier.file_path, reuse_path)
  5390. except OSError as e:
  5391. # A copy that fails leaves the print the fallback archive
  5392. # it would have had, not no archive at all.
  5393. logger.warning("Could not copy the 3MF of archive %s for printer %s: %s", earlier.id, printer_id, e)
  5394. else:
  5395. temp_path = reuse_path
  5396. downloaded_filename = reuse_name
  5397. reused_3mf_from = earlier.id
  5398. cache_3mf_download(printer_id, reuse_name, temp_path)
  5399. logger.info(
  5400. "No 3MF on printer %s for %s (%s); using the 3MF of archive %s, an earlier run of the same job",
  5401. printer_id,
  5402. subtask_name,
  5403. filename,
  5404. earlier.id,
  5405. )
  5406. # Validate the downloaded 3MF actually matches the plate that's running
  5407. # (#1204): subtask_name lags across consecutive plates of the same model,
  5408. # so the first FTP candidate (built from subtask_name) can land on the
  5409. # previous plate's still-resident upload. Cross-check the slice_info
  5410. # plate index against the plate parsed from gcode_file (always fresh —
  5411. # it's the field whose change triggered this callback).
  5412. if downloaded_filename and temp_path:
  5413. expected_plate = parse_plate_id(filename)
  5414. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  5415. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  5416. logger.warning(
  5417. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  5418. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  5419. downloaded_filename,
  5420. actual_plate,
  5421. expected_plate,
  5422. subtask_name,
  5423. )
  5424. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  5425. retry_succeeded = False
  5426. if corrected_subtask and corrected_subtask != subtask_name:
  5427. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  5428. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  5429. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  5430. for remote_path in (
  5431. f"/{try_filename}",
  5432. f"/cache/{try_filename}",
  5433. f"/model/{try_filename}",
  5434. f"/data/{try_filename}",
  5435. f"/data/Metadata/{try_filename}",
  5436. ):
  5437. try:
  5438. if ftp_retry_enabled:
  5439. downloaded = await with_ftp_retry(
  5440. download_file_async,
  5441. printer.ip_address,
  5442. printer.access_code,
  5443. remote_path,
  5444. retry_temp_path,
  5445. timeout=ftp_timeout,
  5446. socket_timeout=ftp_timeout,
  5447. printer_model=printer.model,
  5448. max_retries=ftp_retry_count,
  5449. retry_delay=ftp_retry_delay,
  5450. operation_name=f"Re-download 3MF from {remote_path}",
  5451. cooloff_ip=printer.ip_address,
  5452. non_retry_exceptions=(FileNotOnPrinterError,),
  5453. )
  5454. else:
  5455. downloaded = await download_file_async(
  5456. printer.ip_address,
  5457. printer.access_code,
  5458. remote_path,
  5459. retry_temp_path,
  5460. timeout=ftp_timeout,
  5461. socket_timeout=ftp_timeout,
  5462. printer_model=printer.model,
  5463. )
  5464. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  5465. logger.info(
  5466. "[CALLBACK] Re-download succeeded with corrected name %s "
  5467. "(plate %s) — replacing wrong file",
  5468. try_filename,
  5469. expected_plate,
  5470. )
  5471. try:
  5472. temp_path.unlink(missing_ok=True)
  5473. except OSError:
  5474. pass
  5475. temp_path = retry_temp_path
  5476. downloaded_filename = try_filename
  5477. subtask_name = corrected_subtask
  5478. cache_3mf_download(printer_id, try_filename, temp_path)
  5479. retry_succeeded = True
  5480. break
  5481. elif downloaded:
  5482. # Wrong plate again — discard and keep trying
  5483. try:
  5484. retry_temp_path.unlink(missing_ok=True)
  5485. except OSError:
  5486. pass
  5487. except FileNotOnPrinterError:
  5488. continue
  5489. except Exception as e:
  5490. logger.debug("Re-download failed for %s: %s", remote_path, e)
  5491. if retry_succeeded:
  5492. break
  5493. # If the retry didn't find a matching file, drop the wrong 3MF
  5494. # so the no-3MF fallback below creates an archive whose name
  5495. # at least reflects the right plate.
  5496. if not retry_succeeded:
  5497. logger.warning(
  5498. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  5499. expected_plate,
  5500. )
  5501. try:
  5502. temp_path.unlink(missing_ok=True)
  5503. except OSError:
  5504. pass
  5505. temp_path = None
  5506. downloaded_filename = None
  5507. # Whatever the sweep's transport did earlier, it is not why
  5508. # this archive ends up empty: a 3MF downloaded fine, it was
  5509. # just the wrong plate. Retrying would re-fetch that same
  5510. # contradicted file under the same stale names and hand it
  5511. # to _recover_fallback_archive, which checks that a
  5512. # candidate is a readable 3MF but not which plate it is --
  5513. # so the row would be filled in with another plate's
  5514. # filament and cost, the exact swap #2957 removed (#3063).
  5515. ftp_transfer_failed = False
  5516. # Disown the name for *lookups*: it has just been shown to
  5517. # fetch another plate's 3MF, and it keys `_active_prints`
  5518. # below, where the cover endpoint's own download of that
  5519. # same name would find this archive and fill it in with the
  5520. # file we are discarding here.
  5521. #
  5522. # Keep it for the *title*, which is a separate question.
  5523. # ``swap_plate_suffix`` returns None both for a name that
  5524. # carries no "- Plate N" / "_plate_N" suffix and for no
  5525. # name at all, and those are not the same situation: a name
  5526. # without a suffix holds no stale plate number to be wrong
  5527. # about. Blanking both uses at once dropped the project
  5528. # name too, and the row fell through to the gcode_file path
  5529. # titled "plate_1" though the real name was in hand.
  5530. # #1204's own premise is consecutive plates *of the same
  5531. # model*, so the project part is right either way (#3126).
  5532. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  5533. subtask_name = corrected_subtask or ""
  5534. # Deleted while the 3MF was being fetched (that can take minutes): no
  5535. # archive, timelapse or tracking for a printer that will never report
  5536. # the print's end. forget_printer again: the download registered its
  5537. # 3MF cache entry after the delete cleared the id. (A delete committing
  5538. # while the archive is written is caught after its commit.)
  5539. if await _printer_gone(db, printer_id):
  5540. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  5541. await forget_printer(printer_id)
  5542. return
  5543. if not downloaded_filename or not temp_path:
  5544. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  5545. # Create a fallback archive without 3MF data so the print is still tracked
  5546. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  5547. try:
  5548. from backend.app.models.archive import PrintArchive
  5549. # Why the card is empty. The two temporary causes outrank the
  5550. # storage verdict because they say the sweep never got a fair
  5551. # answer: a cool-off skipped it at the transport, and a failed
  5552. # transfer reached the printer but never finished. Either way
  5553. # the file is still on the card, so reporting where the printer
  5554. # files its jobs would describe a setting that is not the
  5555. # problem (#2957, #3063).
  5556. if blocked_by_ftps_cooloff:
  5557. no_3mf_reason = REASON_FTPS_COOLOFF
  5558. elif storage.reachable and ftp_transfer_failed:
  5559. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5560. else:
  5561. no_3mf_reason = storage.reason
  5562. # Derive print name from subtask_name or filename. The
  5563. # plate guard's disowned name comes second: it is a real name
  5564. # for a real print, and only the gcode_file path is left
  5565. # otherwise -- which titles the row "plate_1" (#3126).
  5566. print_name = subtask_name or display_name_after_plate_reject or filename
  5567. if print_name:
  5568. # Clean up the name (remove extensions, path parts)
  5569. print_name = print_name.split("/")[-1]
  5570. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5571. else:
  5572. print_name = "Unknown Print"
  5573. # Recover estimated print time from MQTT (best-effort for notifications)
  5574. fallback_print_time = None
  5575. mqtt_remaining = data.get("remaining_time")
  5576. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5577. fallback_print_time = int(mqtt_remaining)
  5578. if fallback_print_time is None:
  5579. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5580. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5581. fallback_print_time = int(mc_remaining * 60)
  5582. # Best-effort filament metadata from MQTT — see
  5583. # _extract_filament_data_from_mqtt. Without this the fallback
  5584. # archive's filament fields stayed NULL even though the AMS
  5585. # state at print start was sitting right there in `data`.
  5586. # The slicer's ams_mapping (when present) narrows the result
  5587. # to slots actually used by the print (#1533).
  5588. mqtt_filament_meta = _extract_filament_data_from_mqtt(
  5589. data, _get_start_ams_mapping(data, printer_id, None)
  5590. )
  5591. # Create minimal archive entry
  5592. fallback_archive = PrintArchive(
  5593. printer_id=printer_id,
  5594. filename=filename or f"{print_name}.3mf",
  5595. file_path="", # Empty - no 3MF file available
  5596. file_size=0,
  5597. print_name=print_name,
  5598. print_time_seconds=fallback_print_time,
  5599. status="printing",
  5600. started_at=detected_at,
  5601. subtask_id=subtask_id,
  5602. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5603. filament_type=mqtt_filament_meta.get("filament_type"),
  5604. filament_color=mqtt_filament_meta.get("filament_color"),
  5605. extra_data={
  5606. "no_3mf_available": True,
  5607. # Why the card is empty, when we know -- see above. The
  5608. # banner reads this to stop telling H2/P2 owners to
  5609. # switch on a setting that is already on and would not
  5610. # have helped (#2780).
  5611. "no_3mf_reason": no_3mf_reason,
  5612. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5613. "_print_data": data,
  5614. },
  5615. )
  5616. db.add(fallback_archive)
  5617. try:
  5618. await db.commit()
  5619. except IntegrityError:
  5620. # Not "Failed to create fallback archive" below, and no
  5621. # start notification for a printer that is gone.
  5622. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5623. return
  5624. raise
  5625. await db.refresh(fallback_archive)
  5626. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5627. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5628. return
  5629. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5630. # Track as active print
  5631. _bind_active_print(printer_id, fallback_archive.id, fallback_archive.filename, filename, subtask_name)
  5632. await _open_run_for(fallback_archive.id, printer_id, subtask_id)
  5633. # Record starting energy if smart plug available (#941: persisted column)
  5634. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5635. # Send WebSocket notification
  5636. await ws_manager.send_archive_created(
  5637. {
  5638. "id": fallback_archive.id,
  5639. "printer_id": fallback_archive.printer_id,
  5640. "filename": fallback_archive.filename,
  5641. "print_name": fallback_archive.print_name,
  5642. "status": fallback_archive.status,
  5643. }
  5644. )
  5645. # MQTT relay - publish archive created
  5646. try:
  5647. await mqtt_relay.on_archive_created(
  5648. archive_id=fallback_archive.id,
  5649. print_name=fallback_archive.print_name,
  5650. printer_name=printer.name,
  5651. status=fallback_archive.status,
  5652. )
  5653. except Exception:
  5654. pass # Don't fail if MQTT fails
  5655. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5656. try:
  5657. await _store_spoolman_print_data(
  5658. printer_id,
  5659. fallback_archive.id,
  5660. fallback_archive.file_path,
  5661. db,
  5662. printer_manager,
  5663. ams_mapping=_get_start_ams_mapping(data, printer_id, fallback_archive.id),
  5664. plate_id=_get_start_plate_id(printer_id, fallback_archive.id),
  5665. )
  5666. except Exception as e:
  5667. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5668. # Both temporary give-ups are worth coming back for, and for
  5669. # the same reason: the file is on the printer and the last look
  5670. # failed at the transport rather than finding nothing. One waits
  5671. # out the handshake block (#2957), the other waits for the
  5672. # printer to stop being busy (#3063). Deliberately not scheduled
  5673. # for a storage verdict: a file on internal eMMC will not appear
  5674. # at any FTPS path however long we wait, and retrying it is
  5675. # exactly the sweep #2780 removed.
  5676. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5677. # `possible_names`, not the raw MQTT strings: it is the exact
  5678. # list this flow just tried, already stripped of any path
  5679. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5680. # some firmware) and deduped.
  5681. _schedule_fallback_3mf_retry(
  5682. printer_id=printer_id,
  5683. archive_id=fallback_archive.id,
  5684. filenames=list(possible_names),
  5685. reason=no_3mf_reason,
  5686. )
  5687. # Send notification without archive data (file not found)
  5688. if not notification_sent:
  5689. await _send_print_start_notification(printer_id, data, logger=logger)
  5690. # The same baseline the other two on_print_start branches take
  5691. # (#2704), and last for the same reason they are: it lists the
  5692. # printer's timelapse directory, so a slow card must not delay
  5693. # the _active_prints registration, the energy reading, the
  5694. # archive-created event or the start notification above it.
  5695. #
  5696. # This branch never took one, so every no-3MF archive reached
  5697. # completion with no baseline in memory and none on the row, and
  5698. # the completion scan fell into its "snapshot now" fallback --
  5699. # which runs after the printer has written the video, so the new
  5700. # file landed inside the baseline and no diff ever matched
  5701. # (#2957 follow-up).
  5702. #
  5703. # Skipped when the FTPS cool-off is what produced this fallback:
  5704. # the listing needs the same connection that just failed, so it
  5705. # could only record that the card was unreadable. The scan
  5706. # handles that case by refusing to choose between candidates.
  5707. if not blocked_by_ftps_cooloff:
  5708. await _capture_timelapse_baseline_at_start(
  5709. printer, printer_id, logger, archive_id=fallback_archive.id
  5710. )
  5711. await _forget_if_printer_gone(printer_id)
  5712. return
  5713. except Exception as e:
  5714. logger.error("Failed to create fallback archive: %s", e)
  5715. # Send notification without archive data (file not found)
  5716. if not notification_sent:
  5717. await _send_print_start_notification(printer_id, data, logger=logger)
  5718. return
  5719. try:
  5720. # Archive the file with status "printing"
  5721. service = ArchiveService(db)
  5722. try:
  5723. archive = await service.archive_print(
  5724. printer_id=printer_id,
  5725. source_file=temp_path,
  5726. print_data={
  5727. **data,
  5728. "status": "printing",
  5729. # Where the 3MF came from when the printer had none to
  5730. # give (#3307), for whoever reads this archive later.
  5731. **({"_3mf_from_archive": reused_3mf_from} if reused_3mf_from is not None else {}),
  5732. },
  5733. subtask_id=subtask_id,
  5734. started_at=detected_at,
  5735. # The reused copy's temp name carries the printer id; a
  5736. # download's is the file's own name, as before.
  5737. original_filename=downloaded_filename if reused_3mf_from is not None else None,
  5738. )
  5739. except IntegrityError:
  5740. # archive_print removed the folder it had copied the 3MF into.
  5741. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5742. return
  5743. raise
  5744. if archive:
  5745. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5746. # Set on the row rather than passed to archive_print, which also
  5747. # serves the queue dispatcher — there the queue item decides.
  5748. # Guarded because this branch has no ``except``: an unhandled
  5749. # write error would take the _active_prints registration, the
  5750. # start notification, the energy reading and the timelapse
  5751. # baseline below it with it, and a missing prompt is by far the
  5752. # cheaper failure.
  5753. archive_id = archive.id
  5754. try:
  5755. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5756. archive.confirm_requested = True
  5757. await db.commit()
  5758. except Exception as e:
  5759. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5760. # The rollback expires every loaded object, and on an async
  5761. # session reading one afterwards raises instead of
  5762. # reloading, so the two this branch goes on to use are
  5763. # fetched again. The archive itself was committed by
  5764. # archive_print; only the flag is lost.
  5765. try:
  5766. await db.rollback()
  5767. archive = await db.get(PrintArchive, archive_id)
  5768. printer = await db.get(Printer, printer_id)
  5769. except Exception as reload_error:
  5770. logger.warning(
  5771. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5772. )
  5773. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5774. return
  5775. # Track this active print (use both original filename and downloaded filename)
  5776. _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
  5777. await _open_run_for(archive_id, printer_id, subtask_id)
  5778. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5779. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5780. # Record starting energy from smart plug if available (#941: persisted column)
  5781. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5782. await ws_manager.send_archive_created(
  5783. {
  5784. "id": archive.id,
  5785. "printer_id": archive.printer_id,
  5786. "filename": archive.filename,
  5787. "print_name": archive.print_name,
  5788. "status": archive.status,
  5789. }
  5790. )
  5791. # MQTT relay - publish archive created
  5792. try:
  5793. await mqtt_relay.on_archive_created(
  5794. archive_id=archive.id,
  5795. print_name=archive.print_name,
  5796. printer_name=printer.name,
  5797. status=archive.status,
  5798. )
  5799. except Exception:
  5800. pass # Don't fail if MQTT fails
  5801. # Send notification with archive data (new archive created)
  5802. if not notification_sent:
  5803. archive_data = {
  5804. "print_time_seconds": archive.print_time_seconds,
  5805. "created_by_id": archive.created_by_id,
  5806. }
  5807. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5808. # Extract printable objects for skip object functionality
  5809. try:
  5810. from backend.app.services.archive import extract_printable_objects_from_3mf
  5811. client = printer_manager.get_client(printer_id)
  5812. if client:
  5813. with open(temp_path, "rb") as f:
  5814. threemf_data = f.read()
  5815. # Extract with positions for UI overlay, scoped to the
  5816. # plate that is printing — an all-plates 3MF carries
  5817. # every plate's objects (#2522).
  5818. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5819. threemf_data,
  5820. plate_number=resolve_plate_id(client.state),
  5821. include_positions=True,
  5822. )
  5823. if printable_objects:
  5824. # Store objects in printer state
  5825. client.state.printable_objects = printable_objects
  5826. client.state.printable_objects_bbox_all = bbox_all
  5827. client.state.skipped_objects = [] # Reset skipped objects for new print
  5828. logger.info(
  5829. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5830. )
  5831. except Exception as e:
  5832. logger.debug("Failed to extract printable objects: %s", e)
  5833. # From the archived copy: the downloaded one may be removed
  5834. # below while the pauses are still being read.
  5835. if archive is not None and archive.file_path:
  5836. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  5837. # Store Spoolman tracking data for per-filament usage reporting
  5838. try:
  5839. await _store_spoolman_print_data(
  5840. printer_id,
  5841. archive.id,
  5842. archive.file_path,
  5843. db,
  5844. printer_manager,
  5845. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5846. plate_id=_get_start_plate_id(printer_id, archive_id),
  5847. )
  5848. except Exception as e:
  5849. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5850. # Price the print from its spools now rather than only at completion (#3261)
  5851. _schedule_archive_cost_estimate(
  5852. printer_id,
  5853. archive.id,
  5854. printer_manager,
  5855. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5856. plate_id=_get_start_plate_id(printer_id, archive_id),
  5857. session_factory=async_session,
  5858. )
  5859. # Capture timelapse file baseline for snapshot-diff on completion
  5860. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5861. await _forget_if_printer_gone(printer_id)
  5862. finally:
  5863. # Keep temp_path around until print completes so the cover endpoint
  5864. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5865. # the file. If the cache entry was evicted early (file vanished),
  5866. # clean up any stragglers here to avoid leaking disk on retries.
  5867. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5868. if temp_path and temp_path.exists() and cached_now != temp_path:
  5869. temp_path.unlink()
  5870. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5871. _TIMELAPSE_DIRECTORIES = ("/timelapse", "/timelapse/video", "/record", "/recording")
  5872. # A baseline that could not be read at print start is read again on this
  5873. # schedule while the print runs (#3412). The printer writes the video only once
  5874. # the print has ended, so a reading taken mid-print is as good as one taken at
  5875. # the start. The interval is shorter than the FTPS handshake cool-off (300 s),
  5876. # which is what usually makes the card unreadable, so the first reading after
  5877. # it ends is not long behind; while the cool-off runs a round costs nothing, as
  5878. # no connection is opened. The cap bounds a print that never reports an end.
  5879. _TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS = 120.0
  5880. _TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS = 720
  5881. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5882. # tests can shrink them without waiting out real delays.
  5883. #
  5884. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  5885. # looking. Across 247 support bundles the attempt that found the video was #1
  5886. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  5887. # decaying one, which is the signature of a budget that expires while files are
  5888. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  5889. # prints make big videos and the printer writes them after the print ends, so
  5890. # the poll now runs for minutes and costs one FTP LIST per round.
  5891. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  5892. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  5893. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  5894. def _timelapse_scan_max_attempts() -> int:
  5895. """Round cap for the poll, derived from the wall-clock budget.
  5896. The deadline alone is not a sufficient bound: it assumes each round really
  5897. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5898. and an FTP list that fails immediately would otherwise spin against the
  5899. printer at full speed for the whole window. Whichever bound is reached
  5900. first ends the poll.
  5901. """
  5902. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5903. # A zero interval makes the wall-clock budget meaningless; fall back to
  5904. # the round count the production interval would have given.
  5905. return 32
  5906. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5907. async def _read_timelapse_baseline(printer) -> tuple[set[str], bool]:
  5908. """The video names on *printer*'s card, and whether the card was read.
  5909. ``_list_timelapse_videos`` answers ``[]`` when its connect fails rather
  5910. than raising, so a card behind the FTPS handshake cool-off, or one whose
  5911. listing timed out, is indistinguishable from one holding no videos.
  5912. Everywhere that only wants to know "is there a video yet" the difference
  5913. does not matter -- both mean "not yet, retry".
  5914. It matters where an empty listing is recorded as a *baseline*. Recording
  5915. "the card held nothing" for a card that was never read means every video on
  5916. it counts as new, and the completion scan then attaches a stale video to
  5917. this print and deletes it from the printer (#2957 follow-up, #3412). So an
  5918. empty listing is asked again here in a way that tells the two apart: the
  5919. card counts as read only when every directory walked answered, with a
  5920. listing or with "no such directory". One that failed may be the one
  5921. holding the videos.
  5922. """
  5923. from backend.app.services.bambu_ftp import ftps_handshake_blocked, list_files_result_async
  5924. files, _ = await _list_timelapse_videos(printer)
  5925. if files:
  5926. return {f.get("name", "") for f in files}, True
  5927. ip_address = getattr(printer, "ip_address", None)
  5928. printer_id = getattr(printer, "id", None)
  5929. if not ip_address:
  5930. return set(), True
  5931. # No card in the slot: nothing to read, and nothing a video could land on.
  5932. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5933. return set(), True
  5934. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  5935. if ftps_handshake_blocked(ip_address):
  5936. # Below any path: every remaining one would fail the same way.
  5937. return set(), False
  5938. listing = await list_files_result_async(
  5939. ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5940. )
  5941. if not (listing.available or listing.missing):
  5942. return set(), False
  5943. videos = [
  5944. f
  5945. for f in listing.files
  5946. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5947. ]
  5948. if videos:
  5949. return {f.get("name", "") for f in videos}, True
  5950. return set(), True
  5951. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5952. """List video files from printer's timelapse directory.
  5953. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5954. Returns (video_files, found_path) where video_files is a list of file dicts
  5955. and found_path is the directory where they were found, or ([], None).
  5956. An empty return does not distinguish "no videos" from "could not read the
  5957. card" — see :func:`_read_timelapse_baseline`, which the two baseline
  5958. callers use instead.
  5959. """
  5960. from backend.app.services.bambu_ftp import list_files_async
  5961. logger = logging.getLogger(__name__)
  5962. # No card in the slot means no /timelapse to walk — four connections that
  5963. # can only fail, on a path whose failures are swallowed and so would go on
  5964. # costing time silently forever (#2780).
  5965. #
  5966. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5967. # inside the loop's own try/except, so a caller that passed something
  5968. # unexpected used to get an empty listing rather than an exception. Keep
  5969. # that, instead of making this gate the first thing that can raise here.
  5970. printer_id = getattr(printer, "id", None)
  5971. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5972. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5973. return [], None
  5974. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  5975. try:
  5976. found_files = await list_files_async(
  5977. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5978. )
  5979. if found_files:
  5980. video_files = [
  5981. f
  5982. for f in found_files
  5983. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5984. ]
  5985. if video_files:
  5986. return video_files, timelapse_path
  5987. except Exception as e:
  5988. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5989. continue
  5990. return [], None
  5991. async def _capture_timelapse_baseline_at_start(
  5992. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5993. ) -> None:
  5994. """Snapshot the printer's timelapse directory at print start so the
  5995. completion-time scan can pick the new file by set-difference.
  5996. Must be called from every on_print_start path that proceeds to a real
  5997. print — both the new-archive branch and the expected-archive branch (which
  5998. queue / VP-dispatched prints take). Without a baseline,
  5999. _scan_for_timelapse_with_retries falls into its "take baseline now"
  6000. fallback that runs AFTER the new MP4 has already landed on the SD card,
  6001. so the new file ends up in the "baseline" set and no diff ever matches.
  6002. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  6003. unreliable — the snapshot-diff approach sidesteps that entirely.
  6004. When ``archive_id`` is known the baseline is also written to the archive
  6005. row, so it survives a restart and the manual "Scan for Timelapse" button
  6006. can run the same diff instead of falling back to clock-based matching
  6007. (#2704). Only baselines taken at print start are persisted — one taken at
  6008. completion already contains the new video and would poison a later scan.
  6009. """
  6010. names: set[str] | None = None
  6011. unread = False
  6012. _timelapse_baselines_unread.discard(printer_id)
  6013. try:
  6014. names, read = await _read_timelapse_baseline(printer)
  6015. unread = not read
  6016. _timelapse_baselines[printer_id] = names
  6017. if unread:
  6018. # Recorded anyway, deliberately, and marked. An empty baseline taken
  6019. # off a card we could not read is not evidence, but it is still the
  6020. # right *default*: Bambuddy deletes each video from the printer once
  6021. # it is attached, so the usual card holds exactly one video at
  6022. # completion and an empty baseline resolves it. Persisting NULL
  6023. # instead would send completion to take its own snapshot, by which
  6024. # point this print's video is on the card and would be swallowed by
  6025. # it. The mark keeps the scan from choosing between several videos
  6026. # (#3412), and the card is read again while the print runs.
  6027. _timelapse_baselines_unread.add(printer_id)
  6028. logger.warning(
  6029. "[TIMELAPSE] Baseline for printer %s taken while its card could not be read — "
  6030. "treating it as empty for now and reading it again during the print",
  6031. printer_id,
  6032. )
  6033. logger.info(
  6034. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  6035. len(names),
  6036. printer_id,
  6037. )
  6038. except Exception as e:
  6039. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  6040. run_started_at: datetime | None = None
  6041. run_id: int | None = None
  6042. if archive_id is not None:
  6043. try:
  6044. async with async_session() as db:
  6045. from backend.app.models.archive import PrintArchive
  6046. from backend.app.services.print_log import open_run_on_printer
  6047. archive = await db.get(PrintArchive, archive_id)
  6048. if archive is not None:
  6049. # Written even when the listing failed, and then as NULL. A
  6050. # reprint reuses the archive row, so leaving the previous
  6051. # run's baseline in place would have the scan diff this print
  6052. # against the state of the printer before the *last* one —
  6053. # and a stale baseline reads as authoritative, where NULL
  6054. # correctly falls back to a fresh snapshot.
  6055. baseline = sorted(names) if names is not None else None
  6056. archive.timelapse_baseline = baseline
  6057. archive.timelapse_baseline_unread = unread
  6058. run_started_at = archive.started_at
  6059. # And on the run this print opened, whose scan reads it:
  6060. # the archive's is its latest start's, which another plate
  6061. # of it on another printer can take over.
  6062. run = await open_run_on_printer(db, printer_id)
  6063. if run is not None and run.archive_id == archive_id:
  6064. run.timelapse_baseline = baseline
  6065. run.timelapse_baseline_unread = unread
  6066. run_id = run.id
  6067. await db.commit()
  6068. except Exception as e:
  6069. # In-memory baseline still covers the normal completion path.
  6070. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  6071. if unread and names is not None:
  6072. spawn_background_task(
  6073. _reread_unread_timelapse_baseline(printer_id, names, archive_id, run_started_at, run_id),
  6074. name=f"reread-timelapse-baseline-{printer_id}",
  6075. )
  6076. # Before the print has ended there is no video yet: a long PREPARE (heating,
  6077. # levelling) counts as much as the print itself.
  6078. _BASELINE_REREAD_STATES = _ACTIVE_PRINT_STATES | {"PREPARE", "SLICING"}
  6079. def _schedule_timelapse_scan(
  6080. archive_id: int, printer_id: int, *, plate_id: int | None, run_id: int | None = None
  6081. ) -> None:
  6082. """Start the completion scan with the print-start baseline: the names, and
  6083. whether they were taken off a card that could not be read. Taking them
  6084. ends any re-read still running for it. ``run_id`` is the print that
  6085. ended, whose video it looks for."""
  6086. unread = printer_id in _timelapse_baselines_unread
  6087. _timelapse_baselines_unread.discard(printer_id)
  6088. baseline = _timelapse_baselines.pop(printer_id, None)
  6089. spawn_background_task(
  6090. _mark_run_finishing(
  6091. archive_id,
  6092. _scan_for_timelapse_with_retries(
  6093. archive_id, baseline, plate_id=plate_id, baseline_unread=unread, run_id=run_id
  6094. ),
  6095. ),
  6096. name=f"scan-timelapse-{archive_id}",
  6097. )
  6098. def _unread_baseline_round(printer_id: int, names: set[str]) -> bool | None:
  6099. """Whether to read an unread baseline again now: True to read, None to
  6100. skip this round, False once it is over -- the print it was taken for is
  6101. no longer the one on the printer, has stopped printing, or the baseline
  6102. has been read.
  6103. ``names`` is the very set object recorded at print start: completion pops
  6104. it and the next print records a new one, so identity marks the run. A
  6105. printer that is momentarily disconnected says nothing about its print, so
  6106. that only skips the round.
  6107. """
  6108. if _timelapse_baselines.get(printer_id) is not names or printer_id not in _timelapse_baselines_unread:
  6109. return False
  6110. state = printer_manager.get_status(printer_id)
  6111. if state is None or not state.connected:
  6112. return None
  6113. return state.state in _BASELINE_REREAD_STATES
  6114. async def _reread_unread_timelapse_baseline(
  6115. printer_id: int,
  6116. names: set[str],
  6117. archive_id: int | None,
  6118. run_started_at: datetime | None,
  6119. run_id: int | None = None,
  6120. ) -> None:
  6121. """Read again a print-start baseline the card could not give (#3412).
  6122. The printer writes the video only once the print has ended, so the card
  6123. read at any point during the print holds exactly what it held at the
  6124. start. Each round stops once the print is no longer the one the baseline
  6125. was taken for or has stopped printing, and checks that again after the
  6126. listing returns, before anything is recorded.
  6127. """
  6128. from backend.app.models.archive import PrintArchive
  6129. from backend.app.models.printer import Printer
  6130. from backend.app.services.print_log import run_of
  6131. logger = logging.getLogger(__name__)
  6132. for _ in range(_TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS):
  6133. await asyncio.sleep(_TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS)
  6134. now = _unread_baseline_round(printer_id, names)
  6135. if now is False:
  6136. return
  6137. if now is None:
  6138. continue
  6139. try:
  6140. async with async_session() as db:
  6141. printer = await db.get(Printer, printer_id)
  6142. if printer is None:
  6143. return
  6144. fresh, read = await _read_timelapse_baseline(printer)
  6145. except Exception as e:
  6146. logger.debug("[TIMELAPSE] Re-reading the baseline for printer %s failed: %s", printer_id, e)
  6147. continue
  6148. if not read:
  6149. continue
  6150. now = _unread_baseline_round(printer_id, names)
  6151. if now is False:
  6152. return
  6153. if now is None:
  6154. # The printer dropped off while the listing was out, so nothing
  6155. # says it did not end meanwhile: keep the reading for a round that
  6156. # can vouch for it.
  6157. continue
  6158. names.update(fresh)
  6159. _timelapse_baselines_unread.discard(printer_id)
  6160. logger.info(
  6161. "[TIMELAPSE] Baseline for printer %s read during the print: %s video files",
  6162. printer_id,
  6163. len(fresh),
  6164. )
  6165. if archive_id is None:
  6166. return
  6167. try:
  6168. async with async_session() as db:
  6169. archive = await db.get(PrintArchive, archive_id)
  6170. # Only the run it was taken for: by now the row can belong to a
  6171. # reprint, whose baseline is its own.
  6172. if archive is not None and archive.started_at == run_started_at and archive.timelapse_baseline_unread:
  6173. archive.timelapse_baseline = sorted(names)
  6174. archive.timelapse_baseline_unread = False
  6175. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6176. if run is not None and run.timelapse_baseline_unread:
  6177. run.timelapse_baseline = sorted(names)
  6178. run.timelapse_baseline_unread = False
  6179. await db.commit()
  6180. except Exception as e:
  6181. # The in-memory baseline is read now, which covers completion
  6182. # unless Bambuddy restarts first.
  6183. logger.warning("[TIMELAPSE] Failed to persist the re-read baseline for archive %s: %s", archive_id, e)
  6184. return
  6185. async def _timelapse_still_wanted(db, archive, run_id: int | None, run_started_at: datetime | None) -> bool:
  6186. """Whether the print a timelapse is for still has none: its run, by id,
  6187. exists without a video and no later print took over (``superseded``).
  6188. Without a run, the archive is still on that print's start (a newer run's
  6189. video is its own) and has none."""
  6190. from backend.app.services.print_log import run_of, superseded
  6191. if run_id is not None:
  6192. run = await run_of(db, archive.id, run_id)
  6193. return run is not None and run.timelapse_path is None and not await superseded(db, run)
  6194. return archive.timelapse_path is None and archive.started_at == run_started_at
  6195. async def _scan_for_timelapse_with_retries(
  6196. archive_id: int,
  6197. baseline_names: set[str] | None = None,
  6198. *,
  6199. plate_id: int | None = None,
  6200. baseline_unread: bool = False,
  6201. run_id: int | None = None,
  6202. ):
  6203. """Poll the printer for this print's timelapse and attach it.
  6204. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  6205. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  6206. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  6207. (#2704). Comparing the current listing against the set of filenames that
  6208. existed when the print started needs no clock at all, because the printer
  6209. writes the video only once the print has ended.
  6210. Baseline precedence: the caller's in-memory set, then the one persisted on
  6211. the archive at print start, then a snapshot taken now. The last of those is
  6212. a poor substitute — by completion the new video may already be on the card,
  6213. in which case it lands in the "baseline" and no diff can ever match — but it
  6214. is all that is available for a print that began before Bambuddy started.
  6215. On success the video is deleted from the printer, which keeps ``/timelapse``
  6216. down to the unclaimed files and makes the next diff unambiguous.
  6217. ``baseline_unread`` marks the caller's baseline as taken off a card that
  6218. could not be read; a stored one carries the same mark on the archive.
  6219. ``run_id`` is the print that ended (archive redesign): the video is that
  6220. run's, the stored baseline is the run's own, and the poll ends once the
  6221. run has a video or is gone. Without it (no run was written), the run is
  6222. whichever the archive is on when the scan starts.
  6223. """
  6224. from backend.app.services.print_log import run_of
  6225. logger = logging.getLogger(__name__)
  6226. # Cleared when the baseline was taken off a card we could not read, so the
  6227. # attach step refuses to choose between several candidates (#2957, #3412).
  6228. baseline_trusted = True
  6229. # --- Phase 1: establish the baseline -------------------------------------
  6230. try:
  6231. async with async_session() as db:
  6232. from backend.app.models.printer import Printer
  6233. service = ArchiveService(db)
  6234. archive = await service.get_archive(archive_id)
  6235. if not archive:
  6236. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  6237. return
  6238. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6239. if run_id is not None and run is None:
  6240. logger.info("[TIMELAPSE] Run %s of archive %s is gone, aborting", run_id, archive_id)
  6241. return
  6242. if run.timelapse_path if run is not None else archive.timelapse_path:
  6243. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  6244. return
  6245. # The printer the print ran on: plates of one archive can print on
  6246. # two printers, and the archive's is the one that started last.
  6247. scan_printer_id = run.printer_id if run is not None and run.printer_id else archive.printer_id
  6248. if not scan_printer_id:
  6249. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  6250. return
  6251. # The run this scan is for. The archive row passes to a newer run
  6252. # when it prints again (the next plate, a reprint), and that run's
  6253. # video is its own.
  6254. run_started_at = run.started_at if run is not None else archive.started_at
  6255. # The baseline stored for it: the run's own, else the archive's
  6256. # while that is still this run's start's.
  6257. stored_baseline, stored_unread = None, False
  6258. if run is not None and run.timelapse_baseline is not None:
  6259. stored_baseline, stored_unread = run.timelapse_baseline, bool(run.timelapse_baseline_unread)
  6260. elif archive.started_at == run_started_at:
  6261. stored_baseline, stored_unread = archive.timelapse_baseline, archive.timelapse_baseline_unread
  6262. if baseline_names is not None and baseline_unread and stored_baseline is not None and not stored_unread:
  6263. # The card was read at print start, and the in-memory copy is
  6264. # one Bambuddy took after a restart off a card it could not
  6265. # read: the stored one is this run's and is evidence.
  6266. baseline_names = set(stored_baseline)
  6267. logger.info(
  6268. "[TIMELAPSE] Using stored baseline over an unread one: %s existing video files for archive %s",
  6269. len(baseline_names),
  6270. archive_id,
  6271. )
  6272. elif baseline_names is not None:
  6273. baseline_trusted = not baseline_unread
  6274. logger.info(
  6275. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  6276. len(baseline_names),
  6277. archive_id,
  6278. )
  6279. elif stored_baseline is not None:
  6280. # Persisted at print start — survives a restart mid-print.
  6281. baseline_names = set(stored_baseline)
  6282. baseline_trusted = not stored_unread
  6283. logger.info(
  6284. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  6285. len(baseline_names),
  6286. archive_id,
  6287. )
  6288. else:
  6289. result = await db.execute(select(Printer).where(Printer.id == scan_printer_id))
  6290. printer = result.scalar_one_or_none()
  6291. if not printer:
  6292. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  6293. return
  6294. baseline_names, baseline_trusted = await _read_timelapse_baseline(printer)
  6295. if not baseline_trusted:
  6296. # The card is unreadable at the one moment a baseline has to
  6297. # be taken, so the empty listing means "we never looked",
  6298. # not "these are all new". Carry on with it anyway — the
  6299. # usual card holds exactly one video, which resolves
  6300. # correctly — but stop the poll from *choosing* between
  6301. # several, which is how a stale video got attached to this
  6302. # print and then deleted off the printer (#2957 follow-up).
  6303. logger.warning(
  6304. "[TIMELAPSE] Baseline for archive %s taken while printer %s's card could not be "
  6305. "read. A single new video still resolves; several will not be guessed between — "
  6306. "use Scan for Timelapse to pick one by hand",
  6307. archive_id,
  6308. scan_printer_id,
  6309. )
  6310. logger.info(
  6311. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  6312. len(baseline_names),
  6313. archive_id,
  6314. )
  6315. except Exception as e:
  6316. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  6317. return
  6318. # --- Phase 2: poll for a file that was not there when the print began -----
  6319. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  6320. max_attempts = _timelapse_scan_max_attempts()
  6321. seen_names: set[str] = set()
  6322. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  6323. attempt = 0
  6324. while True:
  6325. await asyncio.sleep(delay)
  6326. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  6327. attempt += 1
  6328. try:
  6329. from backend.app.models.printer import Printer
  6330. # Read phase: fetch archive + printer in a short session and release
  6331. # the pooled connection BEFORE the FTP list/download below. Holding it
  6332. # across the FTP round-trips left one connection idle-in-transaction per
  6333. # in-flight scan (issue #2572).
  6334. async with async_session() as db:
  6335. from backend.app.services.print_log import claimed_timelapse_stems
  6336. service = ArchiveService(db)
  6337. archive = await service.get_archive(archive_id)
  6338. if not archive:
  6339. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  6340. return
  6341. if not await _timelapse_still_wanted(db, archive, run_id, run_started_at):
  6342. logger.info(
  6343. "[TIMELAPSE] Archive %s has its video or is printing again, stopping the run's poll",
  6344. archive_id,
  6345. )
  6346. return
  6347. result = await db.execute(select(Printer).where(Printer.id == scan_printer_id))
  6348. printer = result.scalar_one_or_none()
  6349. if not printer:
  6350. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  6351. return
  6352. claimed = await claimed_timelapse_stems(db, scan_printer_id, archive_id=archive_id, run_id=run_id)
  6353. # I/O phase (no DB connection held): FTP list + download.
  6354. video_files, found_path = await _list_timelapse_videos(printer)
  6355. # The poll can run for dozens of rounds, so only narrate a round
  6356. # that saw something change. Repeating the whole listing every 30 s
  6357. # would bury the one interesting line in the support bundle.
  6358. names_now = {f.get("name", "") for f in video_files}
  6359. changed = attempt == 1 or names_now != seen_names
  6360. seen_names = names_now
  6361. speak = logger.info if changed else logger.debug
  6362. if video_files:
  6363. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  6364. if changed:
  6365. for f in video_files[:5]:
  6366. logger.info("[TIMELAPSE] - %s", f.get("name"))
  6367. attached = await _attach_first_unclaimed_timelapse(
  6368. archive_id,
  6369. printer,
  6370. video_files,
  6371. baseline_names,
  6372. claimed,
  6373. attempt,
  6374. logger,
  6375. quiet=not changed,
  6376. require_unambiguous=not baseline_trusted,
  6377. plate_id=plate_id,
  6378. run_started_at=run_started_at,
  6379. run_id=run_id,
  6380. )
  6381. if attached:
  6382. return
  6383. else:
  6384. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  6385. except Exception as e:
  6386. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  6387. if attempt >= max_attempts or time.monotonic() >= deadline:
  6388. break
  6389. # No name-match fallback: it compared the print name against the filename,
  6390. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  6391. # bundles it fired 159 times and matched zero times, so all it added was a
  6392. # misleading log line before giving up.
  6393. logger.warning(
  6394. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  6395. archive_id,
  6396. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  6397. )
  6398. async def _attach_layer_timelapse(
  6399. archive_id: int,
  6400. timelapse_path: Path,
  6401. plate_id: int | None,
  6402. run_started_at: datetime | None,
  6403. run_id: int | None = None,
  6404. ) -> None:
  6405. """Attach the external camera's stitched timelapse to the archive.
  6406. The camera's video is the one the user set up in Bambuddy, so it wins
  6407. over the printer's own when both are on: it replaces the printer's video
  6408. (usually there first; stitching takes minutes) and that file is deleted,
  6409. leaving nothing in the archive folder unreferenced. ``run_started_at`` is
  6410. the run the frames were taken for: when the archive is printing again by
  6411. the time the stitch is done, the video is not the new run's and is
  6412. dropped. The stitched file is a temporary either way.
  6413. ``run_id`` is the print that ended (archive redesign): the video is that
  6414. run's and replaces that run's printer video; the poll by start above is
  6415. for a print without a run.
  6416. """
  6417. from backend.app.services.print_log import run_of, superseded
  6418. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  6419. logger = logging.getLogger(__name__)
  6420. try:
  6421. async with async_session() as db:
  6422. service = ArchiveService(db)
  6423. archive = await service.get_archive(archive_id)
  6424. if archive is None:
  6425. return
  6426. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6427. if run_id is not None and run is None:
  6428. logger.info("[LAYER-TL] Run %s of archive %s is gone; dropping its layer timelapse", run_id, archive_id)
  6429. return
  6430. if run is not None and await superseded(db, run):
  6431. logger.info(
  6432. "[LAYER-TL] A later print took over run %s of archive %s; dropping its layer timelapse",
  6433. run_id,
  6434. archive_id,
  6435. )
  6436. return
  6437. if run is None and archive.started_at != run_started_at:
  6438. logger.info(
  6439. "[LAYER-TL] Archive %s is printing again; dropping the previous run's layer timelapse", archive_id
  6440. )
  6441. return
  6442. holder = run if run is not None else archive
  6443. replaced = holder.timelapse_path
  6444. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  6445. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  6446. if not await service.attach_timelapse(
  6447. archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=plate_id, run_id=run_id
  6448. ):
  6449. return
  6450. attached = holder.timelapse_path
  6451. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  6452. if replaced and replaced != attached:
  6453. try:
  6454. old = safe_join_under(app_settings.base_dir, replaced, http=False)
  6455. except PathTraversalError:
  6456. return
  6457. await asyncio.to_thread(old.unlink, missing_ok=True)
  6458. logger.info("[LAYER-TL] Replaced the printer's timelapse %s on archive %s", replaced, archive_id)
  6459. finally:
  6460. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6461. # ``run_started_at`` not given: attach whichever run the archive is on.
  6462. _ANY_RUN = object()
  6463. async def _attach_first_unclaimed_timelapse(
  6464. archive_id: int,
  6465. printer,
  6466. video_files: list[dict],
  6467. baseline_names: set[str],
  6468. claimed: set[str],
  6469. attempt: int,
  6470. logger: logging.Logger,
  6471. *,
  6472. quiet: bool = False,
  6473. require_unambiguous: bool = False,
  6474. plate_id: int | None = None,
  6475. run_started_at: datetime | None | object = _ANY_RUN,
  6476. run_id: int | None = None,
  6477. ) -> bool:
  6478. """Download and attach the one video that belongs to this print.
  6479. A candidate is any file absent from the print-start baseline. More than one
  6480. can qualify when a previous print's video landed late, after this print's
  6481. baseline was taken — those are filtered out by name, because they are
  6482. already attached to another archive. Sorting the candidates instead would
  6483. mean sorting on mtime or on the filename timestamp, both of which come from
  6484. the printer's unsynced clock.
  6485. Returns True once a video is attached. The printer's copy is deleted only
  6486. after the attach succeeds on bytes whose length matched the listing.
  6487. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  6488. already seen this exact listing — the poll runs for many rounds and only the
  6489. rounds where something changed are worth an INFO line.
  6490. """
  6491. from backend.app.services.bambu_ftp import (
  6492. DownloadDeadlineExceeded,
  6493. delete_archived_timelapse,
  6494. download_file_bytes_async,
  6495. remote_file_settled,
  6496. )
  6497. speak = logger.debug if quiet else logger.info
  6498. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  6499. if not new_files:
  6500. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  6501. return False
  6502. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  6503. if not candidates:
  6504. speak(
  6505. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  6506. attempt,
  6507. len(new_files),
  6508. )
  6509. return False
  6510. if len(candidates) > 1:
  6511. if require_unambiguous:
  6512. # The baseline is not evidence -- it was taken off a card that could
  6513. # not be read -- so "new since the baseline" does not narrow these
  6514. # down at all. Taking the first would attach an arbitrary video to
  6515. # this print and then delete it from the printer.
  6516. logger.warning(
  6517. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  6518. "leaving all of them on the printer for manual selection",
  6519. attempt,
  6520. len(candidates),
  6521. ", ".join(str(f.get("name")) for f in candidates),
  6522. )
  6523. return False
  6524. logger.warning(
  6525. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  6526. "the rest stay on the printer for manual selection",
  6527. attempt,
  6528. len(candidates),
  6529. ", ".join(str(f.get("name")) for f in candidates),
  6530. )
  6531. target = candidates[0]
  6532. file_name = str(target.get("name") or "") # every listed entry has one
  6533. remote_path = target.get("path") or f"/timelapse/{file_name}"
  6534. logger.info(
  6535. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  6536. attempt,
  6537. file_name,
  6538. archive_id,
  6539. )
  6540. # The listing always carries a size (`list_files` skips entries it can't
  6541. # parse), but read it explicitly: the delete below is destructive and must
  6542. # depend on a size we actually had, not on one we hoped was there.
  6543. expected_size = target.get("size")
  6544. try:
  6545. timelapse_data = await download_file_bytes_async(
  6546. printer.ip_address,
  6547. printer.access_code,
  6548. remote_path,
  6549. printer_model=printer.model,
  6550. expected_size=expected_size,
  6551. )
  6552. except DownloadDeadlineExceeded:
  6553. # Too slow for its size this round; the printer keeps its copy.
  6554. timelapse_data = None
  6555. if not timelapse_data:
  6556. # Short or failed transfer. The printer keeps its copy, so the next
  6557. # round can try again — which is exactly why the delete below is
  6558. # gated on a verified download.
  6559. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  6560. return False
  6561. # The length check above proves we got what the listing said, not that the
  6562. # printer had finished writing. A video still being written can be listed
  6563. # short, served short, and pass — so confirm it has stopped growing before
  6564. # committing to it and deleting the original (#2704).
  6565. if not await remote_file_settled(
  6566. printer.ip_address,
  6567. printer.access_code,
  6568. remote_path,
  6569. len(timelapse_data),
  6570. printer_model=printer.model,
  6571. ):
  6572. return False
  6573. # Write phase: attach in a fresh short-lived session. The download took a
  6574. # while: by now the archive may have its video, or be printing again for a
  6575. # newer run, whose video this is not. Then nothing is attached or deleted,
  6576. # and the poll ends (True).
  6577. async with async_session() as db:
  6578. service = ArchiveService(db)
  6579. if run_id is not None or run_started_at is not _ANY_RUN:
  6580. current = await service.get_archive(archive_id)
  6581. started = None if run_started_at is _ANY_RUN else cast("datetime | None", run_started_at)
  6582. if current is None or not await _timelapse_still_wanted(db, current, run_id, started):
  6583. logger.info(
  6584. "[TIMELAPSE] Archive %s moved on during the download (video attached or printing again); "
  6585. "%s stays on the printer",
  6586. archive_id,
  6587. file_name,
  6588. )
  6589. return True
  6590. success = await service.attach_timelapse(
  6591. archive_id, timelapse_data, file_name, plate_id=plate_id, run_id=run_id
  6592. )
  6593. if not success:
  6594. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  6595. return False
  6596. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  6597. await delete_archived_timelapse(
  6598. printer.ip_address,
  6599. printer.access_code,
  6600. remote_path,
  6601. verified=expected_size is not None,
  6602. printer_model=printer.model,
  6603. printer_name=printer.name,
  6604. )
  6605. return True
  6606. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  6607. # module-level so tests can monkeypatch them down to ~0 without timing out.
  6608. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  6609. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  6610. # How long the *background* upgrade keeps waiting after the notification has
  6611. # already gone out (#2704 follow-up). The short bound above exists so a slow
  6612. # printer can't hold up the print-complete notification; this one exists so the
  6613. # archive still ends up with the better frame afterwards.
  6614. #
  6615. # Measured across 261 attaches in the support bundles, the video lands a median
  6616. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  6617. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  6618. # was 546s. Every other model was inside 26s. The long budget is therefore
  6619. # almost entirely for P1-series users; on everything else the short wait already
  6620. # wins and this task never runs.
  6621. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  6622. async def _capture_finish_photo_from_timelapse(
  6623. archive_id: int,
  6624. archive_dir: Path,
  6625. timeout: float | None = None,
  6626. rotation: int = 0,
  6627. run_id: int | None = None,
  6628. ) -> tuple[str | None, bool]:
  6629. """Wait for the per-print timelapse to land on the archive and extract its
  6630. last frame as the finish photo (#1397).
  6631. Bambu firmware stops timelapse recording after the toolhead parks but
  6632. before the bed-drop end-gcode runs, so the last frame frames the finished
  6633. print correctly. A live camera grab at gcode_state=FINISH captures the
  6634. bed already lowered.
  6635. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  6636. ``archive.timelapse_path`` when the file lands. This function polls for
  6637. that field.
  6638. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  6639. the wait ran out with no video on the archive yet — i.e. the video may
  6640. still be coming and a later attempt could succeed. It is False when the
  6641. video landed (whether or not extraction worked), because in that case
  6642. waiting longer changes nothing. The caller uses that to decide between
  6643. falling back permanently and scheduling a background upgrade.
  6644. ``rotation`` is the printer's camera_rotation, applied to the extracted
  6645. still (#2708) so this source agrees with every other finish-photo source.
  6646. The archived video itself is the printer's own file and is left alone —
  6647. rotating it would mean re-encoding it.
  6648. ``run_id`` is the print that ended: its own video is the one waited for,
  6649. not the archive's, which can be another plate's.
  6650. """
  6651. import uuid
  6652. from backend.app.models.archive import PrintArchive
  6653. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  6654. from backend.app.services.print_log import run_of
  6655. logger = logging.getLogger(__name__)
  6656. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  6657. deadline = asyncio.get_event_loop().time() + budget
  6658. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  6659. while True:
  6660. async with async_session() as db:
  6661. if run_id is not None:
  6662. run = await run_of(db, archive_id, run_id)
  6663. timelapse_relpath = run.timelapse_path if run else None
  6664. else:
  6665. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6666. archive = result.scalar_one_or_none()
  6667. timelapse_relpath = archive.timelapse_path if archive else None
  6668. if timelapse_relpath:
  6669. video_path = app_settings.base_dir / timelapse_relpath
  6670. if video_path.exists() and video_path.stat().st_size > 0:
  6671. photos_dir = archive_dir / "photos"
  6672. photos_dir.mkdir(parents=True, exist_ok=True)
  6673. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6674. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6675. output_path = photos_dir / filename
  6676. if await extract_video_last_frame(video_path, output_path):
  6677. await apply_camera_rotation_to_file(output_path, rotation, logger)
  6678. logger.info(
  6679. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  6680. video_path.name,
  6681. archive_id,
  6682. )
  6683. return filename, False
  6684. logger.warning(
  6685. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  6686. video_path.name,
  6687. archive_id,
  6688. )
  6689. return None, False
  6690. if asyncio.get_event_loop().time() >= deadline:
  6691. logger.info(
  6692. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  6693. archive_id,
  6694. budget,
  6695. )
  6696. return None, True
  6697. await asyncio.sleep(poll_interval)
  6698. async def _upgrade_finish_photo_from_timelapse(
  6699. archive_id: int, archive_dir: Path, rotation: int = 0, run_id: int | None = None
  6700. ) -> None:
  6701. """Add the timelapse's last frame to an archive after the fact (#2704).
  6702. The print-complete notification waits only ~60s for the video, because
  6703. holding a notification for minutes is worse than sending it with a live
  6704. camera grab. On a P1-series printer the video often lands well after that,
  6705. so the archive used to be stuck with the live grab — which is taken at
  6706. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  6707. the worse photo of the two.
  6708. This keeps waiting in the background and, when the video arrives, extracts
  6709. the frame and puts it *first* in the archive's photo list, so opening the
  6710. gallery shows it. The live grab is deliberately kept: the notification that
  6711. already went out links to that exact file, and deleting it would leave a
  6712. broken image in Discord or Telegram. ``run_id`` is the print it is for,
  6713. whose list leads with it too.
  6714. """
  6715. from backend.app.services.print_log import add_run_photo, run_of
  6716. logger = logging.getLogger(__name__)
  6717. filename, _ = await _capture_finish_photo_from_timelapse(
  6718. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation, run_id=run_id
  6719. )
  6720. if not filename:
  6721. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  6722. return
  6723. try:
  6724. async with async_session() as db:
  6725. from backend.app.models.archive import PrintArchive
  6726. archive = await db.get(PrintArchive, archive_id)
  6727. if archive is None:
  6728. return
  6729. photos = list(archive.photos or [])
  6730. if filename in photos:
  6731. return
  6732. # Front of the list: PhotoGalleryModal opens at index 0.
  6733. archive.photos = [filename, *photos]
  6734. add_run_photo(await run_of(db, archive_id, run_id) if run_id is not None else None, filename, first=True)
  6735. await db.commit()
  6736. except Exception as e:
  6737. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  6738. return
  6739. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  6740. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  6741. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  6742. """Put the filament-attribution context back after a restart mid-print.
  6743. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  6744. both die with the process. The print keeps running, so at completion the
  6745. tracker would fall back to whatever the printer reports *now* — and AMS
  6746. filament backup makes "now" the substitute tray, charging the whole print
  6747. to the spool that only finished it.
  6748. The persisted row is only trusted when its print name still matches what
  6749. the printer says it is running: a row left behind by a completion we never
  6750. saw must not attach itself to the next print.
  6751. """
  6752. try:
  6753. from backend.app.api.routes.settings import get_setting
  6754. from backend.app.services.usage_tracker import (
  6755. clear_persisted_session,
  6756. get_persisted_ams_mapping,
  6757. get_persisted_print_name,
  6758. get_persisted_spool_change_log,
  6759. restore_session,
  6760. )
  6761. persisted_name = await get_persisted_print_name(db, printer_id)
  6762. current_name = (state.subtask_name or "").strip()
  6763. if persisted_name and current_name and persisted_name.strip() != current_name:
  6764. logger.info(
  6765. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  6766. printer_id,
  6767. persisted_name,
  6768. current_name,
  6769. )
  6770. await clear_persisted_session(db, printer_id)
  6771. # Fall through to seeding: the print on the printer is real, it just
  6772. # isn't the one the row described.
  6773. persisted_log = None
  6774. else:
  6775. # Spoolman users get the tray-change log back but no in-memory
  6776. # session — see ``on_print_start`` on why that dict is load-bearing
  6777. # for the remain%-sync guard.
  6778. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6779. persisted_log = await restore_session(
  6780. db,
  6781. printer_id,
  6782. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  6783. )
  6784. # The slot pills (#1762) read the mapping captured from the print
  6785. # command, which dies with the process as well. One this process
  6786. # has captured since is newer.
  6787. if state.print_ams_mapping is None:
  6788. state.print_ams_mapping = await get_persisted_ams_mapping(db, printer_id)
  6789. # Spools swapped on a tray before the restart (#3325); anything this
  6790. # process has recorded since goes after them.
  6791. persisted_swaps = await get_persisted_spool_change_log(db, printer_id)
  6792. if persisted_swaps:
  6793. seen = getattr(state, "spool_change_log", None) or []
  6794. state.spool_change_log = persisted_swaps + [item for item in seen if item not in persisted_swaps]
  6795. if persisted_log:
  6796. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  6797. # Anything this process already observed goes after the persisted
  6798. # history — the log is ordered by layer, and a fresh process can
  6799. # only have seen changes from later in the print.
  6800. for entry in state.tray_change_log or []:
  6801. if tuple(entry) not in restored:
  6802. restored.append(tuple(entry))
  6803. state.tray_change_log = restored
  6804. tray_now = state.tray_now
  6805. if 0 <= tray_now <= 254:
  6806. if not state.tray_change_log:
  6807. # No persisted history — a print that started before this build,
  6808. # or before the row existed. Seed with the tray feeding right
  6809. # now so the remainder of the print is at least attributable to
  6810. # the right spool.
  6811. state.tray_change_log = [(tray_now, state.layer_num)]
  6812. logger.info(
  6813. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  6814. printer_id,
  6815. tray_now,
  6816. state.layer_num,
  6817. )
  6818. # The tray handler updates ``last_loaded_tray`` on every push
  6819. # regardless of whether it logged a change, so re-align it to avoid
  6820. # a duplicate entry on the next push. Only ever with a real tray:
  6821. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  6822. # 255" fallback, and writing 255 into it would defeat that.
  6823. state.last_loaded_tray = tray_now
  6824. except Exception:
  6825. # Never let attribution recovery cost the caller its timelapse
  6826. # baseline — that capture has to happen before the printer uploads
  6827. # the in-flight MP4 and there is no second chance at it.
  6828. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  6829. async def on_print_running_observed(printer_id: int, data: dict):
  6830. """Restart-recovery for a print that started before Bambuddy came up.
  6831. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  6832. after Bambuddy startup (#1304 guard, prevents duplicate archive
  6833. creation). This hook restores the persisted archive into ``_active_prints``
  6834. and captures the timelapse baseline that normally hangs off print start.
  6835. Fires once per session, in lieu of on_print_start when restart-recovery
  6836. kicks in. The printer doesn't upload the timelapse until after PRINT
  6837. COMPLETE, so a baseline captured any time during the print is still
  6838. pre-upload.
  6839. """
  6840. logger = logging.getLogger(__name__)
  6841. async with async_session() as db:
  6842. from backend.app.models.printer import Printer
  6843. state = printer_manager.get_status(printer_id)
  6844. if state is not None:
  6845. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  6846. if authorization is True:
  6847. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  6848. await _restore_usage_tracking_session(printer_id, state, db, logger)
  6849. await _restore_printable_objects(printer_id, state, db, logger)
  6850. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6851. printer = result.scalar_one_or_none()
  6852. if not printer:
  6853. logger.warning(
  6854. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  6855. printer_id,
  6856. )
  6857. return
  6858. # Avoid double-capture: ownership reconciliation above must still run when
  6859. # a baseline already exists, but the camera work itself is one-shot.
  6860. if printer_id in _timelapse_baselines:
  6861. logger.debug(
  6862. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  6863. printer_id,
  6864. )
  6865. return
  6866. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  6867. class _RunOfArchive:
  6868. """An archive as one of its runs printed it: the run's job id, start and
  6869. plate, the rest the archive's. What the reconcile judges and closes."""
  6870. def __init__(self, archive, run):
  6871. self._archive = archive
  6872. self.subtask_id = run.subtask_id
  6873. self.started_at = run.started_at
  6874. self.plate_id = run.plate_id if run.plate_id is not None else archive.plate_id
  6875. def __getattr__(self, name):
  6876. return getattr(self._archive, name)
  6877. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  6878. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  6879. against the printer's current MQTT state.
  6880. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  6881. COMPLETE events, typically a print finishing during an MQTT disconnect
  6882. window followed by a smart-plug power cycle):
  6883. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  6884. provably not running anymore — only branch that should fire under
  6885. normal disconnect-then-reconnect timing.
  6886. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  6887. firmware mints a fresh ``subtask_id`` for each print, including the
  6888. ghost replay it runs after a power cycle from a leftover SD file —
  6889. so a mismatch unambiguously means the in-DB archive is no longer
  6890. the print on the printer.
  6891. 3. Printer is running but ``subtask_name`` is empty. The printer
  6892. doesn't know what it's running; the archive's reference to it is
  6893. already broken.
  6894. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  6895. with matching subtask_id+subtask_name is left alone. The cost of a false
  6896. positive is a print closed while it still runs: the reconcile takes its
  6897. ``_active_prints`` entry and the archive is no longer ``printing``, so
  6898. the real PRINT COMPLETE later finds no archive to close (#1679). The
  6899. cost of a false negative is the ghost-print loop in #1542. What the
  6900. archive is closed as is ``_reconciled_outcome``'s call.
  6901. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  6902. MQTT has connected but the first ``push_status`` response hasn't been
  6903. applied yet — ``PrinterState`` is sitting on its construction defaults.
  6904. The reconcile caller in ``on_printer_status_change`` is already gated
  6905. on a real ``state.state``, so in normal operation this branch is
  6906. unreachable; it's kept as belt-and-braces for future callers and for
  6907. the narrow window where a partial state update could arrive
  6908. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  6909. ``not stale`` on degenerate input is strictly conservative: a real
  6910. stale archive will still be caught by the next push_status arriving
  6911. with terminal state.
  6912. """
  6913. current_state = (state.state or "").upper()
  6914. if current_state in ("", "UNKNOWN"):
  6915. # No real push_status yet — PrinterState defaults are not evidence.
  6916. return False, ""
  6917. if current_state in ("IDLE", "FINISH", "FAILED"):
  6918. return True, f"printer state {current_state}"
  6919. # Below here the printer is in a running / pre-running state (RUNNING /
  6920. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  6921. current_subtask_id = (state.subtask_id or "").strip()
  6922. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  6923. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  6924. current_subtask_name = (state.subtask_name or "").strip()
  6925. if not current_subtask_name:
  6926. return True, "printer subtask_name empty"
  6927. return False, ""
  6928. async def prime_kprofile_table(printer_id: int) -> int:
  6929. """Read the printer's calibration table once per connection.
  6930. The AMS slot card shows a K value per slot (#2854). On the printers whose
  6931. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  6932. report ``cali_idx`` and nothing else -- that number can only come from
  6933. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  6934. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  6935. backup, or the printer answering a query BambuStudio made on the report
  6936. topic we share. A Bambuddy that nobody visited showed a card with no K
  6937. values at all.
  6938. Only the diameters actually fitted are asked for, which is one request on a
  6939. single-nozzle printer and two on a dual. Probing the four sizes blind is
  6940. what the backup does, and it is both wasteful and the thing that used to
  6941. blank the table.
  6942. Returns the number of nozzles whose table was read.
  6943. """
  6944. client = printer_manager.get_client(printer_id)
  6945. state = printer_manager.get_status(printer_id)
  6946. if client is None or state is None or not state.connected:
  6947. return 0
  6948. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  6949. # ask once, and both entries are empty until the first push_status lands.
  6950. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  6951. if not diameters:
  6952. logging.getLogger(__name__).debug(
  6953. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  6954. printer_id,
  6955. )
  6956. return 0
  6957. primed = 0
  6958. for diameter in diameters:
  6959. try:
  6960. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  6961. except Exception as exc: # noqa: BLE001
  6962. # A printer that won't answer costs the card its K values, nothing
  6963. # more — never the connection this runs on the back of.
  6964. logging.getLogger(__name__).warning(
  6965. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  6966. )
  6967. continue
  6968. primed += 1
  6969. logging.getLogger(__name__).info(
  6970. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  6971. )
  6972. return primed
  6973. def _sd_files_in_use(state) -> set[str]:
  6974. """Names of the SD-card files the printer may be printing right now (#3009).
  6975. The post-print cleanup works out what to delete from the finished archive,
  6976. not from the printer. When reconciliation closes an old archive because the
  6977. printer has moved on to a new job, and that job is the same file reprinted
  6978. from the printer's screen, the cleanup would delete the file mid-print.
  6979. Empty unless the printer is busy: on an ordinary completion the state is
  6980. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  6981. name, a path or a URL depending on firmware, and some report only the
  6982. plate's G-code, so the job name is matched as well, in the same spellings
  6983. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  6984. ignores case.
  6985. """
  6986. def _text(value) -> str:
  6987. return value.strip() if isinstance(value, str) else ""
  6988. if state is None:
  6989. return set()
  6990. current_state = _text(getattr(state, "state", None)).upper()
  6991. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  6992. return set()
  6993. in_use: set[str] = set()
  6994. gcode_file = _text(getattr(state, "gcode_file", None))
  6995. if gcode_file:
  6996. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  6997. # both legal in a file name, and raises on some inputs.
  6998. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  6999. if name:
  7000. in_use.add(name.lower())
  7001. subtask_name = _text(getattr(state, "subtask_name", None))
  7002. if subtask_name:
  7003. for name in (subtask_name, subtask_name.replace(" ", "_")):
  7004. for ext in (".3mf", ".gcode"):
  7005. in_use.add(f"{name}{ext}".lower())
  7006. return in_use
  7007. def _reconciled_outcome(archive, state) -> str:
  7008. """What a stale archive is closed as at reconnect (#3310).
  7009. A print that ends while Bambuddy restarts is never seen to end: the new
  7010. MQTT client's first status is already FINISH, which is not a transition.
  7011. The printer keeps reporting the finished job's ``subtask_id`` until the
  7012. next print, so a matching id proves the FINISH or FAILED is this
  7013. archive's. Anything else -- IDLE, another job, an id of "0" (a print
  7014. started outside the cloud) or none -- says only that the print is over,
  7015. not how, and stays ``aborted``.
  7016. """
  7017. current_state = (state.state or "").upper()
  7018. if current_state not in ("FINISH", "FAILED"):
  7019. return "aborted"
  7020. archive_id = (archive.subtask_id or "").strip()
  7021. current_id = str(state.subtask_id or "").strip()
  7022. if archive_id in ("", "0") or archive_id != current_id:
  7023. return "aborted"
  7024. return "completed" if current_state == "FINISH" else "failed"
  7025. def _reconciled_end_time(archive, now: datetime, plate_id: int | None = None) -> datetime | None:
  7026. """When a print reconciled as completed most likely ended, or None (#3310).
  7027. The printer does not say when it finished, and the reconnect can be hours
  7028. later. Its start plus the slicer's estimate for the plate it printed,
  7029. never later than now, is the best guess; None when either is missing,
  7030. and the run then keeps no duration, as an aborted one does.
  7031. ``plate_id`` is the plate this run printed, from its queue job: a reprint
  7032. of another plate reuses the archive without changing ``archive.plate_id``.
  7033. """
  7034. started = archive.started_at
  7035. if not started:
  7036. return None
  7037. if started.tzinfo is None:
  7038. started = started.replace(tzinfo=timezone.utc)
  7039. plate = plate_id if plate_id is not None else archive.plate_id
  7040. estimate = None
  7041. if archive.file_path:
  7042. from backend.app.utils.threemf_tools import extract_print_time_from_3mf
  7043. full_path = (
  7044. app_settings.base_dir / archive.file_path
  7045. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7046. try:
  7047. estimate = extract_print_time_from_3mf(full_path, plate)
  7048. except Exception as exc: # noqa: BLE001
  7049. logging.getLogger(__name__).debug(
  7050. "Plate estimate for reconciled archive %s unreadable: %s", archive.id, exc
  7051. )
  7052. if plate is None and estimate != archive.print_time_seconds:
  7053. # Without a plate the first plate's estimate is read. The archive
  7054. # carries the sum over all plates (#1593), so a difference means
  7055. # several plates and no telling which one printed.
  7056. estimate = None
  7057. elif plate is None:
  7058. # Nothing to read the plate from; the archive's own estimate, as for
  7059. # a single-plate file.
  7060. estimate = archive.print_time_seconds
  7061. if not estimate or estimate <= 0:
  7062. return None
  7063. return min(started + timedelta(seconds=int(estimate)), now)
  7064. async def reconcile_stale_active_prints(printer_id: int) -> int:
  7065. """Synthesise ``on_print_complete`` for archives whose print can't be
  7066. running on the printer anymore.
  7067. Called once per MQTT (re)connection (from on_printer_status_change when
  7068. the connected edge flips False → True) and at Bambuddy startup (from
  7069. the FastAPI lifespan). Without this, a print that completes during a
  7070. disconnect window — followed by a smart-plug-driven power cycle — leaves
  7071. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  7072. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  7073. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  7074. power cycle until the operator notices (#1542 follow-up). Reconciliation
  7075. closes the loop by faking the missed PRINT COMPLETE — the existing
  7076. cleanup chain handles SD-file deletion, status updates, usage tracking,
  7077. and notifications.
  7078. The status is ``_reconciled_outcome``'s: ``completed`` or ``failed``
  7079. when the printer still reports the archive's own job as finished or
  7080. failed, ``aborted`` otherwise. Nothing corrects it later: the archive is
  7081. no longer ``printing``, so a later PRINT COMPLETE finds no archive, and
  7082. after a restart the printer's FINISH is not one (#3310).
  7083. Returns the number of archives reconciled.
  7084. """
  7085. state = printer_manager.get_status(printer_id)
  7086. if not state:
  7087. return 0
  7088. # Don't reconcile while disconnected — we'd be making a decision against
  7089. # stale cached state. The connected → reconcile edge handles this.
  7090. if not state.connected:
  7091. return 0
  7092. from backend.app.models.archive import PrintArchive
  7093. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
  7094. reconciled = 0
  7095. async with async_session() as db:
  7096. # The prints on this printer Bambuddy saw start: their runs open here.
  7097. # The archive row is shared by every plate of a file, its printer, job
  7098. # and start the latest start's, so each is judged as its run.
  7099. open_runs = (
  7100. await db.scalars(
  7101. select(PrintLogEntry)
  7102. .where(PrintLogEntry.printer_id == printer_id, PrintLogEntry.status == RUN_OPEN)
  7103. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7104. )
  7105. ).all()
  7106. by_run = {
  7107. archive.id: archive
  7108. for archive in (
  7109. await db.scalars(
  7110. select(PrintArchive).where(
  7111. PrintArchive.id.in_([run.archive_id for run in open_runs if run.archive_id is not None])
  7112. )
  7113. )
  7114. ).all()
  7115. }
  7116. active: list = [_RunOfArchive(by_run[run.archive_id], run) for run in open_runs if run.archive_id in by_run]
  7117. # And as before runs were opened at the start: a printing archive of
  7118. # this printer with no run open anywhere (printing since before).
  7119. archives_with_open_runs = select(PrintLogEntry.archive_id).where(
  7120. PrintLogEntry.status == RUN_OPEN, PrintLogEntry.archive_id.is_not(None)
  7121. )
  7122. result = await db.execute(
  7123. select(PrintArchive)
  7124. .where(
  7125. PrintArchive.printer_id == printer_id,
  7126. PrintArchive.status == "printing",
  7127. PrintArchive.id.not_in(archives_with_open_runs),
  7128. )
  7129. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7130. )
  7131. active.extend(result.scalars().all())
  7132. if not active:
  7133. return 0
  7134. # The plate each run printed, from its queue job (#3310).
  7135. from backend.app.models.print_queue import PrintQueueItem
  7136. async with async_session() as db:
  7137. plate_rows = await db.execute(
  7138. select(PrintQueueItem.archive_id, PrintQueueItem.plate_id).where(
  7139. PrintQueueItem.printer_id == printer_id,
  7140. PrintQueueItem.status == "printing",
  7141. PrintQueueItem.archive_id.in_([a.id for a in active]),
  7142. )
  7143. )
  7144. run_plates = {archive_id: plate for archive_id, plate in plate_rows.all() if plate is not None}
  7145. logger = logging.getLogger(__name__)
  7146. for archive in active:
  7147. is_stale, reason = _is_active_archive_stale(archive, state)
  7148. if not is_stale:
  7149. continue
  7150. logger.info(
  7151. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  7152. printer_id,
  7153. archive.id,
  7154. archive.filename,
  7155. reason,
  7156. )
  7157. # Synthesised payload: minimal fields the on_print_complete chain
  7158. # needs. `_reconciled` marker lets downstream code distinguish this
  7159. # from a real MQTT-driven completion if it ever needs to (e.g. for
  7160. # metrics / debug logging). raw_data is the live printer state so
  7161. # the usage tracker can compare end-of-print remain% against the
  7162. # captured start values.
  7163. outcome = _reconciled_outcome(archive, state)
  7164. payload = {
  7165. "status": outcome,
  7166. "filename": archive.filename,
  7167. "subtask_name": archive.print_name or "",
  7168. "subtask_id": archive.subtask_id or "",
  7169. "raw_data": state.raw_data or {},
  7170. "_reconciled": True,
  7171. }
  7172. if isinstance(archive, _RunOfArchive):
  7173. # The archive it closes, which its names and printer may not find:
  7174. # another printer's plate of it can have started since.
  7175. payload["_reconciled_archive_id"] = archive.id
  7176. if outcome != "aborted":
  7177. # The printer's progress and layer are this job's, so a partial
  7178. # run is charged what it printed rather than nothing.
  7179. if state.progress:
  7180. payload["last_progress"] = state.progress
  7181. if state.layer_num:
  7182. payload["last_layer_num"] = state.layer_num
  7183. if outcome == "failed":
  7184. payload["hms_errors"] = [e.completion_payload() for e in state.hms_errors or []]
  7185. if outcome == "completed":
  7186. ended = _reconciled_end_time(archive, datetime.now(timezone.utc), run_plates.get(archive.id))
  7187. if ended:
  7188. payload["_reconciled_completed_at"] = ended
  7189. try:
  7190. await on_print_complete(printer_id, payload)
  7191. reconciled += 1
  7192. except Exception as e:
  7193. # Catch-all: a reconciliation failure must not block the
  7194. # printer's normal status flow. The archive stays in
  7195. # ``status="printing"`` and the next reconnect retries.
  7196. logger.warning(
  7197. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  7198. archive.id,
  7199. e,
  7200. )
  7201. return reconciled
  7202. # #2547: clearance left between the nozzle and the top of the print when the
  7203. # plate is commanded back into camera framing. The nozzle is parked away from
  7204. # the part by then, so this is belt-and-braces against a max_z_height that
  7205. # under-reports (e.g. a slicer that excludes a final Z hop).
  7206. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  7207. # How far below the restored position to drop the plate again afterwards, so
  7208. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  7209. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  7210. # on machines with less headroom.
  7211. _PLATE_PARK_DROP_MM = 100.0
  7212. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  7213. # this axis, so it is a proven-safe speed for the full travel.
  7214. _PLATE_RESTORE_FEEDRATE = 600
  7215. # Time allowed for the plate to reach the restored position before the camera
  7216. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  7217. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  7218. # How long `_background_finish_photo` waits for this producer. Must cover the
  7219. # settle window plus a worst-case RTSP grab (15s), and stay below the
  7220. # notification path's own photo wait so a slow producer degrades to a
  7221. # photo-less notification rather than a missed one. The chamber light's
  7222. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  7223. # camera_light.MAX_DELAY_SECONDS stays below it.
  7224. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  7225. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  7226. """The ``_active_prints`` keys a finished print may be registered under.
  7227. Matching how they were registered in on_print_start. Shared by
  7228. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  7229. to find the same binding.
  7230. """
  7231. possible_keys = []
  7232. # Try subtask_name variations first (most reliable for matching)
  7233. if subtask_name:
  7234. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  7235. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  7236. possible_keys.append((printer_id, subtask_name))
  7237. # Try filename variations
  7238. if filename:
  7239. # Extract just the filename if it's a path
  7240. fname = filename.split("/")[-1] if "/" in filename else filename
  7241. if fname.endswith(".3mf"):
  7242. possible_keys.append((printer_id, fname))
  7243. elif fname.endswith(".gcode"):
  7244. base_name = fname.rsplit(".", 1)[0]
  7245. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  7246. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7247. possible_keys.append((printer_id, fname))
  7248. else:
  7249. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  7250. possible_keys.append((printer_id, f"{fname}.3mf"))
  7251. possible_keys.append((printer_id, fname))
  7252. # Also try full path versions
  7253. if filename.endswith(".3mf"):
  7254. possible_keys.append((printer_id, filename))
  7255. elif filename.endswith(".gcode"):
  7256. base_name = filename.rsplit(".", 1)[0]
  7257. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7258. possible_keys.append((printer_id, filename))
  7259. else:
  7260. possible_keys.append((printer_id, f"{filename}.3mf"))
  7261. possible_keys.append((printer_id, filename))
  7262. return possible_keys
  7263. def _archive_name_forms(archive) -> set[str]:
  7264. """The names an archive could be echoed back as, in normalised form (#3240).
  7265. Its print name, and its filename with and without the 3MF extension.
  7266. """
  7267. forms = set()
  7268. if archive.print_name:
  7269. forms.add(_normalise_subtask_name(archive.print_name))
  7270. if archive.filename:
  7271. forms.add(_normalise_subtask_name(archive.filename))
  7272. for suffix in (".gcode.3mf", ".3mf"):
  7273. if archive.filename.lower().endswith(suffix):
  7274. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  7275. forms.discard("")
  7276. return forms
  7277. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  7278. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  7279. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  7280. from the plate recorded when the job was dispatched. Neither is touched:
  7281. ``on_print_complete`` pops both, which is why the finish-photo producer
  7282. calls this before its first await, while they are still there.
  7283. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  7284. archive, or that it only knows by a name -- and on any error: the producer
  7285. calls this before the ``try`` that always releases the photo consumer, so
  7286. it must not raise.
  7287. """
  7288. try:
  7289. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  7290. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  7291. if archive_id is None:
  7292. return None, None
  7293. return archive_id, _print_plate_ids.get((printer_id, archive_id))
  7294. except Exception:
  7295. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  7296. return None, None
  7297. async def _max_z_for_current_print(
  7298. printer_id: int,
  7299. data: dict,
  7300. logger,
  7301. archive_id: int | None,
  7302. plate_id: int | None = None,
  7303. ) -> float | None:
  7304. """Height of the print that just finished on ``printer_id``, or None (#2547).
  7305. This number becomes the target of a real Z move, so every step here refuses
  7306. rather than guesses. A height belonging to some *other* print is the one
  7307. failure that could drive the nozzle into the model: 20 mm carried onto a
  7308. 200 mm print would command the plate up through the part.
  7309. Three independent things therefore have to agree before a height is
  7310. returned:
  7311. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  7312. when it started (see ``_bound_print``), never one found by name. A name
  7313. is not an identity: every plate of a multi-plate file shares one, and a
  7314. reprint reuses its archive row, so the newest archive with the right
  7315. name can be another plate of the same file. Support bundles show the
  7316. old name lookup doing exactly that (archive 288 for a print bound to
  7317. 169, 313 layers against 125), stopped only by the layer check below.
  7318. No binding, no move.
  7319. 2. **Identity.** The bound archive's name still has to be the finished
  7320. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  7321. because the printer echoes spaces as underscores (#3240). Exact: not a
  7322. substring, and not the completion check's tolerance for a truncated
  7323. echo.
  7324. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  7325. match the layer count the printer itself reported over MQTT for the print
  7326. that just ended. These come from genuinely different sources, so a
  7327. mismatch means the row is not this print, whatever its name says.
  7328. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  7329. plate of a multi-plate file reuses the archive row without updating its
  7330. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  7331. ``on_print_complete`` may already have flipped the status by the time we
  7332. run.
  7333. """
  7334. subtask_name = (data.get("subtask_name") or "").strip()
  7335. if not subtask_name:
  7336. # Nothing to identify the print by — refuse rather than fall back to
  7337. # "whatever ran last on this printer".
  7338. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  7339. return None
  7340. if archive_id is None:
  7341. logger.info(
  7342. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  7343. printer_id,
  7344. subtask_name,
  7345. )
  7346. return None
  7347. try:
  7348. from backend.app.models.archive import PrintArchive
  7349. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  7350. async with async_session() as db:
  7351. result = await db.execute(
  7352. select(PrintArchive).where(
  7353. PrintArchive.id == archive_id,
  7354. PrintArchive.printer_id == printer_id,
  7355. PrintArchive.status.in_(("printing", "completed")),
  7356. PrintArchive.deleted_at.is_(None),
  7357. )
  7358. )
  7359. archive = result.scalar_one_or_none()
  7360. if archive is None or not archive.file_path:
  7361. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  7362. return None
  7363. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  7364. logger.warning(
  7365. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  7366. printer_id,
  7367. archive_id,
  7368. subtask_name,
  7369. )
  7370. return None
  7371. client = printer_manager.get_client(printer_id)
  7372. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  7373. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  7374. logger.warning(
  7375. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  7376. "— refusing to move the plate on a height that may not be this print's",
  7377. printer_id,
  7378. archive.id,
  7379. archive.total_layers,
  7380. reported_layers,
  7381. )
  7382. return None
  7383. # Stored relative to the data directory, like every other archive path
  7384. # (#3240: this read a `data_dir` setting that does not exist).
  7385. path = app_settings.base_dir / archive.file_path
  7386. plate = plate_id or archive.plate_id or 1
  7387. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  7388. except Exception as e:
  7389. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  7390. return None
  7391. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  7392. """Raise the plate back into camera framing before the finish photo (#2547).
  7393. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  7394. the time ``gcode_state`` reaches FINISH the finished print sits far below
  7395. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  7396. This commands an absolute ``G1 Z`` back to just above the last printed
  7397. layer.
  7398. Absolute, not relative, is the whole safety argument. ``max_z_height +
  7399. clearance`` is a height the toolhead was physically at seconds earlier, so
  7400. it is inside the travel limits by construction and leaves the nozzle above
  7401. the part. It is also unambiguous across model families: Z is the
  7402. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  7403. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  7404. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  7405. (#2579).
  7406. Returns True if the move was sent and waited out, False if it was skipped.
  7407. """
  7408. client = printer_manager.get_client(printer_id)
  7409. if client is None:
  7410. return False
  7411. # Re-read state immediately before commanding motion. If the queue has
  7412. # already started the next print, the printer is no longer ours to move.
  7413. state = getattr(client, "state", None)
  7414. if state is None or state.state != "FINISH":
  7415. logger.info(
  7416. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  7417. printer_id,
  7418. getattr(state, "state", "unknown"),
  7419. )
  7420. return False
  7421. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  7422. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  7423. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  7424. return False
  7425. logger.info(
  7426. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  7427. printer_id,
  7428. target_z,
  7429. max_z_height,
  7430. _PLATE_RESTORE_CLEARANCE_MM,
  7431. _PLATE_RESTORE_SETTLE_SECONDS,
  7432. )
  7433. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  7434. return True
  7435. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  7436. """Drop the plate again after the finish photo (#2547).
  7437. Without this the user walks up to a finished print sitting just under the
  7438. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  7439. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  7440. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  7441. print homes anyway.
  7442. """
  7443. client = printer_manager.get_client(printer_id)
  7444. state = getattr(client, "state", None) if client else None
  7445. if client is None or state is None or state.state != "FINISH":
  7446. return
  7447. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  7448. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  7449. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  7450. """True if a queue item is about to take this printer (#2547).
  7451. The scheduler dispatches the next job the moment a print completes, and a
  7452. plate move interleaved with a print start is not a race worth having. The
  7453. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  7454. this window; this closes the head of it.
  7455. """
  7456. try:
  7457. from backend.app.models.print_queue import PrintQueueItem
  7458. async with async_session() as db:
  7459. result = await db.execute(
  7460. select(PrintQueueItem.id)
  7461. .where(
  7462. PrintQueueItem.printer_id == printer_id,
  7463. PrintQueueItem.status.in_(("pending", "printing")),
  7464. )
  7465. .limit(1)
  7466. )
  7467. return result.scalar_one_or_none() is not None
  7468. except Exception as e:
  7469. # Fail closed: if we can't tell, don't move the plate.
  7470. logging.getLogger(__name__).debug(
  7471. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  7472. )
  7473. return True
  7474. async def on_finish_photo_moment(printer_id: int, data: dict):
  7475. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  7476. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  7477. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  7478. fallback for prints that skip stage 22 (cancel, external-spool-only,
  7479. HMS halt, firmware variants). Grabs one frame via the same
  7480. external-camera / RTSP path the post-completion fallback uses, stores
  7481. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  7482. ``_background_finish_photo`` consume the cached bytes when it runs.
  7483. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  7484. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  7485. set to Smooth (#1721). No force-on now means the user's explicit
  7486. timelapse=off in the slicer send dialog is respected.
  7487. """
  7488. logger = logging.getLogger(__name__)
  7489. trigger = data.get("trigger", "unknown")
  7490. timelapse_was_active = bool(data.get("timelapse_was_active"))
  7491. logger.info(
  7492. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  7493. printer_id,
  7494. trigger,
  7495. timelapse_was_active,
  7496. )
  7497. # If a timelapse is actively recording, skip the pre-capture — the
  7498. # post-completion path will extract the last frame from the recorded
  7499. # video, which still provides the best framing (toolhead parked,
  7500. # before bed drop) without the per-layer parking side effects.
  7501. if timelapse_was_active:
  7502. logger.info(
  7503. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  7504. printer_id,
  7505. )
  7506. return
  7507. # #1790: register the producer-done event BEFORE the first await so the
  7508. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  7509. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  7510. # The `finally` below guarantees `set()` runs on every exit, including
  7511. # early returns and exceptions, so the consumer's bounded wait can't hang.
  7512. producer_done = asyncio.Event()
  7513. _stage22_finish_in_flight[printer_id] = producer_done
  7514. # #3240: also before the first await. On the FINISH-state path
  7515. # `on_print_complete` is dispatched right behind us and pops both the
  7516. # print's archive binding and its plate; read here, they are still there.
  7517. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  7518. # #2547: set once the plate has actually been raised, and read by the
  7519. # `finally` below. Declared out here so a failure anywhere after the move —
  7520. # a camera timeout, a DB error — still lowers the plate again.
  7521. restore_max_z: float | None = None
  7522. try:
  7523. async with async_session() as db:
  7524. from backend.app.api.routes.settings import get_setting
  7525. from backend.app.models.printer import Printer
  7526. capture_setting = await get_setting(db, "capture_finish_photo")
  7527. if capture_setting is not None and capture_setting.lower() != "true":
  7528. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  7529. return
  7530. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7531. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  7532. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7533. printer = result.scalar_one_or_none()
  7534. if printer is None:
  7535. logger.warning(
  7536. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  7537. printer_id,
  7538. )
  7539. return
  7540. frame_bytes: bytes | None = None
  7541. # #2708: the banked frame arrives already rotated — it comes from
  7542. # `_capture_snapshot_for_notification`, which rotates before returning.
  7543. # Every other source below is a raw grab. Tracking which lets us store
  7544. # exactly one rotation in `_stage22_finish_frames` either way.
  7545. frame_already_rotated = False
  7546. # On the FINISH-state path the End G-code has already run, and two very
  7547. # different situations arrive here needing opposite answers.
  7548. #
  7549. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  7550. # snippet may have ejected the plate — the scene in front of the camera
  7551. # is no longer the finished print, and no amount of moving the plate
  7552. # brings it back. Use the banked in-print frame instead.
  7553. #
  7554. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  7555. # than the camera frames well, and the toolhead is parked out of the
  7556. # way. That is the *best* moment available on firmware that never emits
  7557. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  7558. # back. Preferring the bank here unconditionally, as this code used to,
  7559. # is what shipped a mid-print photo with the toolhead over the part.
  7560. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  7561. banked = _inprint_frame_bank.get(printer_id)
  7562. if banked:
  7563. frame_bytes = banked
  7564. frame_already_rotated = True
  7565. logger.info(
  7566. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  7567. "frame (%d bytes) instead of a post-swap live grab",
  7568. len(banked),
  7569. )
  7570. else:
  7571. logger.warning(
  7572. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  7573. "in-print bank is empty — falling back to a live grab, which may show a "
  7574. "swapped or empty plate",
  7575. printer_id,
  7576. )
  7577. # `restore_max_z` is set only once the plate is actually up, because the
  7578. # `finally` reads it to decide whether it owes a move back down.
  7579. #
  7580. # Never on a print whose End G-code Bambuddy injected, even when the bank
  7581. # came up empty above: that machine may have just ejected its plate, and
  7582. # driving Z into whatever a swap mechanism is doing is not a risk worth
  7583. # taking for a photo of a bed we already know may be bare.
  7584. if (
  7585. frame_bytes is None
  7586. and trigger == "finish_state"
  7587. and restore_plate_enabled
  7588. and not print_dispatch_context.end_gcode_injected(printer_id)
  7589. ):
  7590. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  7591. if wants_restore is None:
  7592. logger.info(
  7593. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  7594. printer_id,
  7595. )
  7596. elif await _plate_restore_is_blocked_by_queue(printer_id):
  7597. logger.info(
  7598. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  7599. printer_id,
  7600. )
  7601. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  7602. restore_max_z = wants_restore
  7603. # Chamber light for the live capture below (#1655). The banked frame
  7604. # above was taken without it, like every in-print bank.
  7605. async with camera_light(printer if frame_bytes is None else None):
  7606. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  7607. from backend.app.api.routes.camera import live_frame_for_capture
  7608. from backend.app.services.external_camera import capture_frame
  7609. # #2707: this used to collide with the live view and fail, which is
  7610. # how finish-photo notifications went out with no image attached.
  7611. # Leaving frame_bytes None keeps the rest of the fallback chain.
  7612. defer, buffered = live_frame_for_capture(printer_id)
  7613. if defer:
  7614. frame_bytes = buffered
  7615. else:
  7616. frame_bytes = await capture_frame(
  7617. printer.external_camera_url,
  7618. printer.external_camera_type or "mjpeg",
  7619. snapshot_url=printer.external_camera_snapshot_url,
  7620. )
  7621. if frame_bytes:
  7622. logger.info(
  7623. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  7624. len(frame_bytes),
  7625. )
  7626. elif frame_bytes is None:
  7627. from backend.app.api.routes.camera import get_buffered_frame
  7628. buffered = get_buffered_frame(printer_id)
  7629. if buffered:
  7630. frame_bytes = buffered
  7631. logger.info(
  7632. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  7633. len(frame_bytes),
  7634. )
  7635. else:
  7636. from backend.app.services.camera import capture_camera_frame_bytes
  7637. frame_bytes = await capture_camera_frame_bytes(
  7638. ip_address=printer.ip_address,
  7639. access_code=printer.access_code,
  7640. model=printer.model,
  7641. timeout=15,
  7642. )
  7643. if frame_bytes:
  7644. logger.info(
  7645. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  7646. len(frame_bytes),
  7647. )
  7648. if frame_bytes:
  7649. if not frame_already_rotated:
  7650. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  7651. _stage22_finish_frames[printer_id] = frame_bytes
  7652. else:
  7653. logger.warning(
  7654. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  7655. printer_id,
  7656. )
  7657. except Exception as e:
  7658. logger.warning(
  7659. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  7660. printer_id,
  7661. e,
  7662. )
  7663. finally:
  7664. # #2547: we raised the plate, so we own lowering it — including when the
  7665. # capture above failed or threw partway through.
  7666. if restore_max_z is not None:
  7667. try:
  7668. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  7669. except Exception as e:
  7670. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7671. # #1790: always unblock the consumer's bounded wait — whether we stored
  7672. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  7673. # dict entry by the consumer doesn't affect signalling.
  7674. producer_done.set()
  7675. def _subtask_name_from_filename(filename: str) -> str:
  7676. """Recover the subtask name a print command would have carried for *filename*.
  7677. The dispatcher derives the printer-facing subtask name from the archive's
  7678. file name, so stripping the extensions back off gives the value MQTT echoes
  7679. on completion. Only the two extensions Bambuddy actually stores are removed,
  7680. and in the order they nest (``.gcode.3mf``), so a model whose own name
  7681. contains a dot -- ``My.Model.3mf`` -- keeps it.
  7682. """
  7683. name = PurePosixPath(filename).name
  7684. for suffix in (".3mf", ".gcode"):
  7685. if name.lower().endswith(suffix):
  7686. name = name[: -len(suffix)]
  7687. return name
  7688. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  7689. """Whether the subtask name is the printed 3MF's own file name.
  7690. A print started from the printer's screen reports the same full name, with
  7691. its extension, as both subtask and file (#3009). A dispatched print reports
  7692. a bare subtask name; one that merely ends in ".3mf" can be a model named
  7693. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  7694. """
  7695. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  7696. return False
  7697. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  7698. # How the printer marks a subtask name it had to cut short. Observed on real
  7699. # hardware at ~100 characters, but the cut-off is not a fixed character count
  7700. # (a name with multibyte characters came back at 98), so match the marker
  7701. # rather than a length.
  7702. _SUBTASK_TRUNCATION_MARKER = "..."
  7703. def _normalise_subtask_name(name: str) -> str:
  7704. """Canonical form for comparing a dispatched name against MQTT's echo.
  7705. The printer does not echo the name back verbatim: it substitutes
  7706. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  7707. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  7708. The 3MF lookup in this module has always known that -- it builds
  7709. space-to-underscore variants of every candidate filename, and its
  7710. directory search normalises both sides before comparing. This exists so
  7711. the completion check reads the same rule from the same place instead of
  7712. growing its own, which is exactly how it came to disagree (#2829).
  7713. A space at either end is substituted too: ``Part .gcode.3mf`` is
  7714. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  7715. are dropped after the substitution so both sides agree (#3241).
  7716. """
  7717. return name.strip().replace(" ", "_").strip("_").casefold()
  7718. def _3mf_files_for_print(paths: list[str], search_term: str) -> list[str]:
  7719. """The 3MF files of the printer's folder listings that are this print's.
  7720. A file of the print's own name wins, in whichever folder. Only without one
  7721. is a file that merely contains the name taken, and then only when it is
  7722. the one such file: "Cube_large.3mf" is not "Cube"'s file, and of several
  7723. candidates none can be told apart. Paths keep the listings' order.
  7724. """
  7725. threemf = [path for path in paths if path.lower().endswith(".3mf")]
  7726. exact = [path for path in threemf if _subtask_names_match(_subtask_name_from_filename(path), search_term)]
  7727. if exact:
  7728. return exact
  7729. term = _normalise_subtask_name(search_term)
  7730. partial = [path for path in threemf if term in _normalise_subtask_name(PurePosixPath(path).name)]
  7731. if len(partial) > 1:
  7732. logging.getLogger(__name__).info(
  7733. "Several 3MF files contain %r and none is named for it: %s", search_term, partial
  7734. )
  7735. return []
  7736. return partial
  7737. def _subtask_names_match(expected: str, observed: str) -> bool:
  7738. """Whether two subtask names describe the same print.
  7739. Beyond the space/underscore substitution, the printer truncates long names
  7740. and marks the cut with ``...``. A truncated echo has to count as a match or
  7741. every print with a long name strands its queue item the same way.
  7742. """
  7743. expected_n = _normalise_subtask_name(expected)
  7744. observed_n = _normalise_subtask_name(observed)
  7745. if expected_n == observed_n:
  7746. return True
  7747. # Either side can be the truncated one: the printer truncates what it
  7748. # echoes, and an archive whose own filename was recorded from a previous
  7749. # truncated echo carries the marker too.
  7750. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  7751. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  7752. continue
  7753. # The full side has lost its edge underscores; a cut that lands right
  7754. # after one keeps it, so drop it here too (#3241). Nothing left before
  7755. # the marker is no evidence of anything, and must not match every name.
  7756. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  7757. if kept and full.startswith(kept):
  7758. return True
  7759. return False
  7760. async def _queue_item_dispatched_name(db, item) -> str:
  7761. """The subtask name *item* was dispatched under, or "" when unknowable.
  7762. A row with no archive, or an archive with no file name, is unverifiable
  7763. rather than wrong; every caller answers that with its permissive branch.
  7764. """
  7765. if item.archive_id is None:
  7766. return ""
  7767. from backend.app.models.archive import PrintArchive
  7768. archive = await db.get(PrintArchive, item.archive_id)
  7769. if archive is None or not archive.filename:
  7770. return ""
  7771. return _subtask_name_from_filename(archive.filename)
  7772. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  7773. """Whether this completion event is plausibly about *item*'s print.
  7774. The caller finds its queue row by printer and ``status='printing'`` alone,
  7775. which is all a completion event gives it -- there is no run identifier in
  7776. the MQTT payload to match on. That makes the lookup indiscriminate: any
  7777. completion delivered for this printer closes whichever row happens to be
  7778. printing, however unrelated. Comparing the subtask name against the archive
  7779. the row was dispatched with costs one primary-key load and rules that out.
  7780. Deliberately permissive: it answers False only on a positive disagreement
  7781. between two names we actually have. A row with no archive, an archive with
  7782. no file name, or an event with no subtask name is unverifiable rather than
  7783. wrong, and refusing those would strand the item in ``printing`` and wedge
  7784. the printer's queue -- a worse failure than the one being prevented.
  7785. """
  7786. observed = (data.get("subtask_name") or "").strip()
  7787. if not observed or item.archive_id is None:
  7788. return True
  7789. from backend.app.models.archive import PrintArchive
  7790. archive = await db.get(PrintArchive, item.archive_id)
  7791. if archive is None or not archive.filename:
  7792. return True
  7793. expected = _subtask_name_from_filename(archive.filename)
  7794. if not expected or _subtask_names_match(expected, observed):
  7795. return True
  7796. logging.getLogger(__name__).warning(
  7797. "Ignoring print completion for queue item %s: it was dispatched as %r "
  7798. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  7799. "printing rather than closing a run this event is not about.",
  7800. item.id,
  7801. expected,
  7802. archive.id,
  7803. archive.filename,
  7804. observed,
  7805. )
  7806. return False
  7807. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  7808. """Spend the 3MF download cache on a still-empty fallback archive.
  7809. ``on_print_complete`` drops the cache as its first act, which deletes the
  7810. file. If the cover endpoint (or anything else) pulled the 3MF while the
  7811. print ran and the archive never got one, this is the last moment those bytes
  7812. exist (#2957).
  7813. """
  7814. logger = logging.getLogger(__name__)
  7815. names = [
  7816. n
  7817. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  7818. if n
  7819. ]
  7820. for name in names:
  7821. try:
  7822. cached = get_cached_3mf(printer_id, name)
  7823. # The print has ended: its completion prices the archive, so no
  7824. # print-start estimate is scheduled to race it.
  7825. if cached and await try_recover_fallback_archive(printer_id, name, cached, price=False):
  7826. return
  7827. except Exception as e:
  7828. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  7829. # Longest the print's end waits for its file to be deleted from the SD card
  7830. _SD_CLEANUP_BUDGET_SECONDS = 45.0
  7831. async def _cleanup_sd_card_after_print(
  7832. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  7833. ) -> None:
  7834. """Delete a finished print's file from the printer's SD card."""
  7835. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  7836. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  7837. # auto-start files found in root on power cycle, causing ghost prints.
  7838. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  7839. try:
  7840. if subtask_name:
  7841. archive_filename: str | None = None
  7842. async with async_session() as db:
  7843. from backend.app.models.archive import PrintArchive
  7844. from backend.app.models.printer import Printer
  7845. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7846. printer = result.scalar_one_or_none()
  7847. if archive_id:
  7848. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  7849. archive_filename = archive_row.scalar_one_or_none()
  7850. if printer:
  7851. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  7852. from backend.app.utils.filename import derive_remote_filename
  7853. # Primary candidate: the exact path the dispatcher uploaded to
  7854. # (derived from archive.filename via the same rule as upload).
  7855. # Without it, a library row that ended up with a doubled
  7856. # .gcode.3mf (#1542) leaves the real file behind because the
  7857. # subtask_name + ext fallbacks below don't match what's on the
  7858. # SD card. Fallbacks remain for archive-less prints (subtask
  7859. # never resolved to an archive) and for older naming variants.
  7860. candidate_paths: list[str] = []
  7861. if archive_filename:
  7862. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  7863. for ext in (".3mf", ".gcode"):
  7864. fallback = f"/{subtask_name}{ext}"
  7865. if fallback not in candidate_paths:
  7866. candidate_paths.append(fallback)
  7867. # Three outcomes track across all candidates so the final log
  7868. # line reflects what actually happened. The A1 in #1721 always
  7869. # ends here with ``any_not_found=True`` and the others False
  7870. # — its firmware auto-cleans the SD card before our cleanup
  7871. # runs, every candidate FTP-DELE returns 550, and the old
  7872. # code burned 3 retries × 2 s × 3 candidates per print
  7873. # logging a misleading "may linger" WARNING on a successful
  7874. # print.
  7875. any_deleted = False
  7876. any_real_failure = False
  7877. any_not_found = False
  7878. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  7879. for remote_path in candidate_paths:
  7880. if PurePosixPath(remote_path).name.lower() in files_in_use:
  7881. logger.info(
  7882. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  7883. remote_path,
  7884. printer.name,
  7885. )
  7886. continue
  7887. # Retry only the FAILED case — 550 NOT_FOUND will never
  7888. # recover by waiting, so a "file isn't here" answer
  7889. # advances immediately to the next candidate without
  7890. # consuming the retry budget.
  7891. for attempt in range(1, 4):
  7892. try:
  7893. delete_result = await delete_file_async(
  7894. printer.ip_address,
  7895. printer.access_code,
  7896. remote_path,
  7897. printer_model=printer.model,
  7898. )
  7899. except Exception as e:
  7900. delete_result = DeleteResult.FAILED
  7901. logger.warning(
  7902. "SD card cleanup attempt %d/3 raised for %s: %s",
  7903. attempt,
  7904. remote_path,
  7905. e,
  7906. )
  7907. if delete_result == DeleteResult.DELETED:
  7908. any_deleted = True
  7909. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  7910. break
  7911. if delete_result == DeleteResult.NOT_FOUND:
  7912. any_not_found = True
  7913. break # 550 will not recover; try next candidate
  7914. # FAILED: real error — retry with backoff, then give up
  7915. if attempt < 3:
  7916. await asyncio.sleep(2)
  7917. else:
  7918. any_real_failure = True
  7919. logger.warning(
  7920. "SD card cleanup failed after 3 attempts for %s "
  7921. "(network/auth/transient error — file may linger on SD card)",
  7922. remote_path,
  7923. )
  7924. if not any_deleted and not any_real_failure and any_not_found:
  7925. # Every candidate said "not here." Either the printer
  7926. # firmware swept the SD card itself (common on A1) or the
  7927. # dispatcher's upload path doesn't match our candidate
  7928. # rule. Either way: nothing to clean up, no warning.
  7929. logger.debug(
  7930. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  7931. "(printer likely self-cleaned)",
  7932. printer.name,
  7933. )
  7934. except Exception as e:
  7935. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  7936. async def on_print_complete(printer_id: int, data: dict):
  7937. """Handle print completion - update the archive status.
  7938. The printer counts as printing until the print's usage is booked (or this
  7939. ends), so the AMS remain% weight sync can't charge it a second time while
  7940. the usage tracker works (WU-3). Marked before the first await.
  7941. """
  7942. from backend.app.services.usage_tracker import done_completing, mark_completing
  7943. mark_completing(printer_id)
  7944. try:
  7945. await _close_out_print(printer_id, data)
  7946. finally:
  7947. done_completing(printer_id)
  7948. async def _close_out_print(printer_id: int, data: dict):
  7949. import time
  7950. logger = logging.getLogger(__name__)
  7951. start_time = time.time()
  7952. def log_timing(section: str):
  7953. elapsed = time.time() - start_time
  7954. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  7955. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  7956. # A kill-switch stop sends its provider notification immediately. Keep the
  7957. # task so the later notification path can await it and avoid a duplicate;
  7958. # if that immediate attempt failed, the regular completion path retries.
  7959. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  7960. # Last chance before the bytes go: if this print's archive is still an empty
  7961. # fallback and something downloaded the 3MF while it ran, fill the archive in
  7962. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  7963. # below deletes the file (#2957).
  7964. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  7965. # A pending cool-off retry has nothing left to recover for — the cache is
  7966. # about to be dropped and the print is over.
  7967. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  7968. if retry_task and not retry_task.done():
  7969. retry_task.cancel()
  7970. # Drop the 3MF download cache for this printer (#972). The print is over,
  7971. # nothing else legitimately needs the bytes; keeping them would only risk
  7972. # handing a stale file to the next print if it reuses the same name.
  7973. clear_3mf_cache(printer_id)
  7974. try:
  7975. ws_data = {
  7976. "status": data.get("status"),
  7977. "filename": data.get("filename"),
  7978. "subtask_name": data.get("subtask_name"),
  7979. "timelapse_was_active": data.get("timelapse_was_active"),
  7980. }
  7981. await ws_manager.send_print_complete(printer_id, ws_data)
  7982. log_timing("WebSocket send_print_complete")
  7983. except Exception as e:
  7984. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  7985. # Capture user info before clearing (needed for print log entry)
  7986. _print_user_info = printer_manager.get_current_print_user(printer_id)
  7987. # Clear current print user tracking (Issue #206)
  7988. printer_manager.clear_current_print_user(printer_id)
  7989. # If the user explicitly stopped this print from the queue UI the printer will
  7990. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  7991. # correct "print stopped" notification/email is sent instead of a failure alert.
  7992. _raw_status = data.get("status", "completed")
  7993. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  7994. logger.info(
  7995. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  7996. _raw_status,
  7997. printer_id,
  7998. )
  7999. data = {**data, "status": "cancelled"}
  8000. elif printer_id in _kill_switch_stopped and _raw_status in ("failed", "aborted"):
  8001. logger.info(
  8002. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (stopped by the printer kill switch)",
  8003. _raw_status,
  8004. printer_id,
  8005. )
  8006. data = {**data, "status": "cancelled", "_kill_switch": True}
  8007. _user_stopped_printers.discard(printer_id)
  8008. _kill_switch_stopped.discard(printer_id)
  8009. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  8010. # may have left material on the bed: a user can cancel ten hours into a
  8011. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  8012. # touchscreen-stop reports `aborted` rather than `cancelled` because
  8013. # `_user_stopped_printers` is only populated when the user stops via the
  8014. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  8015. # which auto-dispatched the next queued print onto a fouled bed two seconds
  8016. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  8017. # Auto Off power cycles and Bambuddy restarts.
  8018. try:
  8019. notify_live_activities.print_finished(printer_id, data)
  8020. except Exception:
  8021. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  8022. _final_status = data.get("status", "completed")
  8023. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  8024. printer_manager.set_awaiting_plate_clear(printer_id, True)
  8025. # MQTT relay - publish print complete
  8026. try:
  8027. printer_info = printer_manager.get_printer(printer_id)
  8028. if printer_info:
  8029. await mqtt_relay.on_print_complete(
  8030. printer_id,
  8031. printer_info.name,
  8032. printer_info.serial_number,
  8033. data.get("filename", ""),
  8034. data.get("subtask_name", ""),
  8035. data.get("status", "completed"),
  8036. )
  8037. except Exception:
  8038. pass # Don't fail print complete callback if MQTT fails
  8039. filename = data.get("filename", "")
  8040. subtask_name = data.get("subtask_name", "")
  8041. if not filename and not subtask_name:
  8042. # Which print ended can't be told: the printer reported no name since
  8043. # Bambuddy started (a print that failed while preparing, a calibration).
  8044. # Charge nothing, but close the print session, which otherwise kept the
  8045. # AMS weight sync off until the next print (AS-5). A print archived as
  8046. # running is closed and charged by the reconnect reconcile.
  8047. logger.warning("Print complete without filename or subtask_name")
  8048. try:
  8049. from backend.app.services.usage_tracker import discard_session
  8050. async with async_session() as db:
  8051. await discard_session(db, printer_id)
  8052. except Exception as e:
  8053. logger.warning("Failed to clear print session for printer %s: %s", printer_id, e)
  8054. return
  8055. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  8056. # Build list of possible keys to try (matching how they were registered in on_print_start)
  8057. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  8058. # Find the archive for this print
  8059. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  8060. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  8061. archive_id = None
  8062. for key in possible_keys:
  8063. archive_id = _active_prints.pop(key, None)
  8064. if archive_id:
  8065. _owned_print_archive_ids.discard(archive_id)
  8066. logger.info("Found archive %s with key %s", archive_id, key)
  8067. # Also clean up the printer's other keys pointing to this archive;
  8068. # another printer's are a plate of it still printing there.
  8069. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id and k[0] == printer_id]
  8070. for k in keys_to_remove:
  8071. _active_prints.pop(k, None)
  8072. break
  8073. # The archive bound when the print started, before the name search below.
  8074. # Only this one may give the finish-photo plate restore a height (#3240):
  8075. # the search matches names by substring.
  8076. bound_archive_id = archive_id
  8077. if not archive_id and data.get("_reconciled") and data.get("_reconciled_archive_id"):
  8078. # The reconcile names the archive whose run on this printer it
  8079. # closes. Only while that run is open: the print's real end may have
  8080. # closed it meanwhile, or closed the print without managing to write
  8081. # it, and either way there is nothing left to end twice.
  8082. if await _archive_of_open_run(printer_id) != data["_reconciled_archive_id"]:
  8083. logger.info(
  8084. "[RECONCILE] Archive %s has no run open on printer %s any more; nothing to close",
  8085. data["_reconciled_archive_id"],
  8086. printer_id,
  8087. )
  8088. return
  8089. archive_id = data["_reconciled_archive_id"]
  8090. ending_job = str(data.get("subtask_id") or "").strip()
  8091. if not archive_id and ending_job not in ("", "0"):
  8092. # Not bound (a restart since the start): this job's run, open on the
  8093. # printer. Only by its job id: a run open there can be of the print
  8094. # running now, while the end is of an earlier one closed late (the
  8095. # restart's reconcile of a missed end).
  8096. archive_id = await _archive_of_open_run(printer_id, subtask_id=ending_job)
  8097. if archive_id:
  8098. logger.info("Found archive %s by the run of job %s open on printer %s", archive_id, ending_job, printer_id)
  8099. if not archive_id:
  8100. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  8101. async with async_session() as db:
  8102. from backend.app.models.archive import PrintArchive
  8103. # Try matching by subtask_name (stored as print_name) first. The
  8104. # same name rule as the queue's completion check: a name inside
  8105. # another ("Clip" in "Cable Clip") is a different print, and the
  8106. # printer's underscores for spaces and truncation still match.
  8107. if subtask_name:
  8108. printing = await db.scalars(
  8109. select(PrintArchive)
  8110. .where(PrintArchive.printer_id == printer_id)
  8111. .where(PrintArchive.status == "printing")
  8112. .order_by(PrintArchive.created_at.desc())
  8113. )
  8114. # A print started from the printer's screen reports its file
  8115. # name, extensions included, as the subtask (#3009).
  8116. reported = {subtask_name, _subtask_name_from_filename(subtask_name)}
  8117. archive = next(
  8118. (
  8119. candidate
  8120. for candidate in printing
  8121. if any(
  8122. (candidate.print_name and _subtask_names_match(candidate.print_name, name))
  8123. or (
  8124. candidate.filename
  8125. and _subtask_names_match(_subtask_name_from_filename(candidate.filename), name)
  8126. )
  8127. for name in reported
  8128. )
  8129. ),
  8130. None,
  8131. )
  8132. if archive:
  8133. archive_id = archive.id
  8134. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  8135. # Also try by filename
  8136. if not archive_id and filename:
  8137. result = await db.execute(
  8138. select(PrintArchive)
  8139. .where(PrintArchive.printer_id == printer_id)
  8140. .where(PrintArchive.filename == filename)
  8141. .where(PrintArchive.status == "printing")
  8142. .order_by(PrintArchive.created_at.desc())
  8143. .limit(1)
  8144. )
  8145. archive = result.scalar_one_or_none()
  8146. if archive:
  8147. archive_id = archive.id
  8148. # Bounded: a printer whose FTP hangs on DELE took up to 3 candidates x 3
  8149. # attempts x a 60 s timeout, about nine minutes, before the queue item was
  8150. # closed below. The stranded-job closer gives up after five and closed it
  8151. # first, so the job's auto-off and its billing never ran. Inline rather
  8152. # than in the background, so the next job of the same file isn't released
  8153. # (and uploaded under the name being deleted) while the cleanup still
  8154. # works on it. A delete already sent may still finish in its FTP thread
  8155. # after the cutoff, as one past delete_file_async's own timeout always did.
  8156. try:
  8157. await asyncio.wait_for(
  8158. _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger),
  8159. timeout=_SD_CLEANUP_BUDGET_SECONDS,
  8160. )
  8161. except TimeoutError:
  8162. logger.warning(
  8163. "SD card cleanup on printer %s took over %ss; leaving the file there and closing the print",
  8164. printer_id,
  8165. _SD_CLEANUP_BUDGET_SECONDS,
  8166. )
  8167. log_timing("SD card cleanup")
  8168. # Update queue item status early — must run before the archive_id early-return
  8169. # so queue items don't get stuck in "printing" when archive lookup fails.
  8170. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  8171. queue_item_id = None
  8172. billing_run_id: str | None = None
  8173. billing_user_id: int | None = None
  8174. billing_cost_center_id: int | None = None
  8175. billing_plate_id: int | None = None
  8176. queue_status = None
  8177. queue_auto_off = False
  8178. try:
  8179. from backend.app.core.database import run_with_retry
  8180. from backend.app.models.print_queue import PrintQueueItem
  8181. async def _update_queue_status(db):
  8182. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  8183. nonlocal queue_item_id, queue_status, queue_auto_off
  8184. result = await db.execute(
  8185. select(PrintQueueItem)
  8186. .where(PrintQueueItem.printer_id == printer_id)
  8187. .where(PrintQueueItem.status == "printing")
  8188. )
  8189. printing_items = list(result.scalars().all())
  8190. if len(printing_items) > 1:
  8191. logger.warning(
  8192. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  8193. printer_id,
  8194. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  8195. )
  8196. item = printing_items[0] if printing_items else None
  8197. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  8198. return
  8199. if item:
  8200. queue_status = data.get("status", "completed")
  8201. # MQTT sends "aborted" for cancelled prints; normalise to
  8202. # "cancelled" so it matches the queue schema Literal.
  8203. if queue_status == "aborted":
  8204. queue_status = "cancelled"
  8205. item.status = queue_status
  8206. item.completed_at = datetime.now(timezone.utc)
  8207. if queue_status == "failed" and not item.error_message:
  8208. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  8209. # Bump usage counters on the source library file so admins can
  8210. # sort by "last printed" and (eventually) auto-purge stale
  8211. # files — #1008.
  8212. await _bump_library_file_usage_if_completed(db, item, queue_status)
  8213. await db.commit()
  8214. queue_item_id = item.id
  8215. billing_run_id = item.billing_run_id
  8216. billing_user_id = item.created_by_id
  8217. billing_cost_center_id = item.cost_center_id
  8218. billing_plate_id = item.plate_id
  8219. queue_auto_off = item.auto_off_after
  8220. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  8221. await run_with_retry(_update_queue_status, label="queue status update")
  8222. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  8223. # their own sessions and have their own error handling — no retry needed.
  8224. if queue_item_id is not None:
  8225. # Batch orders (#342): this run may have been the last one an order
  8226. # owed. Re-evaluate here rather than lazily on read, so a finished
  8227. # order reports itself complete without someone opening the page.
  8228. try:
  8229. from backend.app.services.print_batch import refresh_batch_status_for_item
  8230. async with async_session() as db:
  8231. await refresh_batch_status_for_item(db, queue_item_id)
  8232. await db.commit()
  8233. except Exception as e:
  8234. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  8235. # MQTT relay - publish queue job completed
  8236. try:
  8237. printer_info = printer_manager.get_printer(printer_id)
  8238. await mqtt_relay.on_queue_job_completed(
  8239. job_id=queue_item_id,
  8240. filename=filename or subtask_name,
  8241. printer_id=printer_id,
  8242. printer_name=printer_info.name if printer_info else "Unknown",
  8243. status=queue_status,
  8244. )
  8245. except Exception:
  8246. pass # Don't fail if MQTT fails
  8247. # Check if queue is now empty and send notification
  8248. try:
  8249. from sqlalchemy import func as sa_func
  8250. async with async_session() as db:
  8251. count_result = await db.execute(
  8252. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  8253. )
  8254. pending_count = count_result.scalar() or 0
  8255. if pending_count == 0:
  8256. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  8257. completed_result = await db.execute(
  8258. select(sa_func.count(PrintQueueItem.id)).where(
  8259. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  8260. PrintQueueItem.completed_at >= today_start,
  8261. )
  8262. )
  8263. completed_count = completed_result.scalar() or 1
  8264. await notification_service.on_queue_completed(
  8265. completed_count=completed_count,
  8266. db=db,
  8267. )
  8268. except Exception:
  8269. pass # Don't fail if notification fails
  8270. # Handle auto_off_after - power off printer if the queue item opted
  8271. # in. Delegates to the smart-plug manager so the off honours each
  8272. # plug's configured strategy (time delay or temperature threshold),
  8273. # is cancelled if the printer starts printing again, and never cuts
  8274. # power on a loaded print (#1890). Previously an inline block here
  8275. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  8276. # timeout regardless of print state — cutting a touchscreen reprint.
  8277. if queue_auto_off:
  8278. try:
  8279. async with async_session() as db:
  8280. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  8281. except Exception as e:
  8282. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  8283. except Exception as e:
  8284. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  8285. log_timing("Queue item update")
  8286. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  8287. # Must run before archive_id early-return so it fires for all prints (including
  8288. # prints started from BambuStudio/touchscreen that have no archive).
  8289. if data.get("status") == "completed":
  8290. try:
  8291. from backend.app.api.routes.settings import get_setting
  8292. async with async_session() as db:
  8293. threshold_str = await get_setting(db, "bed_cooled_threshold")
  8294. threshold = float(threshold_str) if threshold_str else 35.0
  8295. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  8296. async with async_session() as db:
  8297. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  8298. if providers:
  8299. _bed_cool_waiters[printer_id] = {
  8300. "threshold": threshold,
  8301. "filename": filename or subtask_name or "",
  8302. "registered_at": time.time(),
  8303. }
  8304. logger.info(
  8305. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  8306. printer_id,
  8307. threshold,
  8308. )
  8309. else:
  8310. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  8311. except Exception as e:
  8312. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  8313. # Capture the slicer estimate before usage tracking runs. The tracker may
  8314. # update archive.cost with this run's measured cost; billing partial runs
  8315. # against that already-partial value would discount the charge twice.
  8316. billing_planned_grams: float | None = None
  8317. billing_base_cost: float | None = None
  8318. if archive_id:
  8319. try:
  8320. async with async_session() as db:
  8321. from backend.app.models.archive import PrintArchive
  8322. billing_archive = await db.get(PrintArchive, archive_id)
  8323. if billing_archive:
  8324. billing_path = (
  8325. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  8326. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8327. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  8328. billing_archive,
  8329. billing_path,
  8330. billing_plate_id
  8331. if billing_plate_id is not None
  8332. else _get_start_plate_id(printer_id, archive_id),
  8333. )
  8334. except Exception as e:
  8335. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  8336. # --- Track filament consumption (must run before archive_id early-return so usage
  8337. # is recorded even when auto-archive is disabled) ---
  8338. usage_results: list[dict] = []
  8339. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  8340. stored_ams_mapping = data.get("ams_mapping")
  8341. # Fallback to _print_ams_mappings for queue/reprint (set before print starts).
  8342. # Drained either way, like the plate below: left over, it would be read by
  8343. # the archive's next run, dispatched without a mapping.
  8344. registered_ams_mapping = _print_ams_mappings.pop((printer_id, archive_id), None) if archive_id else None
  8345. if not stored_ams_mapping:
  8346. stored_ams_mapping = registered_ams_mapping
  8347. # Always drain the plate_id register on completion — the session already
  8348. # consumed it at print-start injection; leaving it would leak into the next
  8349. # print on the same archive_id (rare but possible with reprints) (#1697).
  8350. # Capture the popped value so the completion notification can scope the
  8351. # archive-level (summed-across-plates per #1593) filament + time totals
  8352. # down to the single plate that was actually printed (#1785).
  8353. notify_plate_id: int | None = None
  8354. if archive_id:
  8355. notify_plate_id = _print_plate_ids.pop((printer_id, archive_id), None)
  8356. # The start estimate must not outlive the real cost written below (COST-4).
  8357. if archive_id:
  8358. await _settle_archive_cost_estimate(archive_id)
  8359. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  8360. try:
  8361. async with async_session() as db:
  8362. from backend.app.api.routes.settings import get_setting
  8363. _spoolman_on = await get_setting(db, "spoolman_enabled")
  8364. if not _spoolman_on or _spoolman_on.lower() != "true":
  8365. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  8366. async with async_session() as db:
  8367. usage_results = await usage_on_print_complete(
  8368. printer_id,
  8369. data,
  8370. printer_manager,
  8371. db,
  8372. archive_id=archive_id,
  8373. ams_mapping=stored_ams_mapping,
  8374. )
  8375. if usage_results:
  8376. await ws_manager.broadcast(
  8377. {
  8378. "type": "spool_usage_logged",
  8379. "printer_id": printer_id,
  8380. "usage": usage_results,
  8381. }
  8382. )
  8383. log_timing("Usage tracker")
  8384. except Exception as e:
  8385. logger.warning("Usage tracker on_print_complete failed: %s", e)
  8386. # Drop the print-start context unconditionally — the Spoolman branch above
  8387. # skips the internal tracker entirely, so nothing else would clear what
  8388. # print start captured, and a row surviving its print would be restored
  8389. # onto the next one after a restart.
  8390. try:
  8391. from backend.app.services.usage_tracker import discard_session
  8392. async with async_session() as db:
  8393. await discard_session(db, printer_id)
  8394. except Exception as e:
  8395. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  8396. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  8397. # A partial run's cost from the Spoolman spools it was charged to; the
  8398. # built-in inventory's comes in usage_results.
  8399. spoolman_run_cost: float | None = None
  8400. if archive_id:
  8401. if data.get("status") == "completed":
  8402. try:
  8403. await _report_spoolman_usage(printer_id, archive_id)
  8404. log_timing("Spoolman usage report")
  8405. except Exception as e:
  8406. logger.warning("Spoolman usage reporting failed: %s", e)
  8407. else:
  8408. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  8409. try:
  8410. async with async_session() as db:
  8411. spoolman_run_cost = await _cleanup_spoolman_tracking(
  8412. printer_id,
  8413. archive_id,
  8414. db,
  8415. last_layer_num=data.get("last_layer_num"),
  8416. last_progress=data.get("last_progress"),
  8417. status=data.get("status") or "failed",
  8418. )
  8419. except Exception as e:
  8420. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  8421. await _release_archived_spoolman_slots(printer_id)
  8422. log_timing("Filament usage tracking")
  8423. if not archive_id:
  8424. # The printer's own calibration run has no archive by design, so this
  8425. # arrives here every time one finishes. Returning before the no-archive
  8426. # notification keeps a calibration from being announced as a finished
  8427. # print. Everything above this point has already run — the plate-clear
  8428. # gate, the queue reconciliation, the SD-card cleanup — so only the
  8429. # notification is skipped.
  8430. if is_internal_printer_job(filename, subtask_name):
  8431. logger.info(
  8432. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  8433. filename,
  8434. subtask_name,
  8435. )
  8436. return
  8437. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  8438. # Still send print-complete/failed/stopped notifications even without an archive.
  8439. # Try to enrich with queue/library-file data so user-specific emails work too.
  8440. async def _notify_no_archive():
  8441. try:
  8442. async with async_session() as db:
  8443. from backend.app.models.library import LibraryFile
  8444. from backend.app.models.print_queue import PrintQueueItem
  8445. from backend.app.models.printer import Printer
  8446. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8447. printer_obj = result.scalar_one_or_none()
  8448. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  8449. # Only the queue item this completion itself closed (the
  8450. # reconciliation above, which checks the run belongs to it).
  8451. # A print started outside Bambuddy closed none, and must not
  8452. # borrow an earlier job's owner, email or times.
  8453. no_archive_data: dict | None = None
  8454. try:
  8455. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  8456. if queue_item:
  8457. no_archive_data = {"created_by_id": queue_item.created_by_id}
  8458. # How long it really ran, as the archive path reports it (#1198).
  8459. started = to_naive_utc(queue_item.started_at)
  8460. ended = to_naive_utc(queue_item.completed_at)
  8461. # Not for a completion reconciled at reconnect: it
  8462. # ended at an unknown time while the printer was
  8463. # offline, and "now" is the reconnect (DB-C9).
  8464. if (
  8465. not data.get("_reconciled")
  8466. and started
  8467. and ended
  8468. and (ended - started).total_seconds() > 0
  8469. ):
  8470. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  8471. # Estimated time: the queue item caches it from its
  8472. # archive or library file; otherwise read the library
  8473. # file's metadata (LibraryFile has no column for it).
  8474. if queue_item.print_time_seconds:
  8475. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  8476. elif queue_item.library_file_id:
  8477. lib_result = await db.execute(
  8478. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  8479. )
  8480. lib_file = lib_result.scalar_one_or_none()
  8481. estimate = (
  8482. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  8483. )
  8484. if estimate:
  8485. no_archive_data["print_time_seconds"] = estimate
  8486. except Exception as lookup_err:
  8487. logger.debug(
  8488. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  8489. )
  8490. # Enrich with usage tracker results (captured in enclosing scope)
  8491. if usage_results:
  8492. if no_archive_data is None:
  8493. no_archive_data = {}
  8494. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8495. if total_from_usage > 0:
  8496. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8497. no_archive_data["usage_results"] = usage_results
  8498. # Try MQTT remaining_time for print duration when no queue/library data
  8499. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  8500. mqtt_remaining = data.get("remaining_time")
  8501. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  8502. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  8503. ps = data.get("status", "completed")
  8504. logger.info(
  8505. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  8506. )
  8507. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8508. await notification_service.on_print_complete(
  8509. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  8510. )
  8511. else:
  8512. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8513. # Send user-specific email if we have a created_by_id
  8514. if no_archive_data and no_archive_data.get("created_by_id"):
  8515. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8516. await _dispatch_user_print_email(
  8517. ps,
  8518. no_archive_data["created_by_id"],
  8519. p_name,
  8520. raw_filename,
  8521. db,
  8522. )
  8523. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  8524. except Exception as e:
  8525. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  8526. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  8527. return
  8528. log_timing("Archive lookup")
  8529. # Update archive status
  8530. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  8531. try:
  8532. async with async_session() as db:
  8533. service = ArchiveService(db)
  8534. status = data.get("status", "completed")
  8535. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  8536. if hms_errors:
  8537. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  8538. failure_reason = derive_failure_reason(status, hms_errors)
  8539. if data.get("_reconciled") and (status == "aborted" or (status == "failed" and not failure_reason)):
  8540. # A reconciled completion closes out a stale archive at
  8541. # reconnect — it is not a user action, so don't mislabel it
  8542. # "userCancelled". It shares the stale-cleanup path's key
  8543. # (issue #2974) and records that the real end time is unknown,
  8544. # which is also why its logged duration is 0 (#2592). A failed
  8545. # one the printer's errors explain keeps their reason (#3310).
  8546. failure_reason = "noStatusUpdate"
  8547. elif data.get("_kill_switch"):
  8548. # Not the user's cancel: the kill switch stopped a print that did
  8549. # not come from Bambuddy.
  8550. failure_reason = "killSwitch"
  8551. if failure_reason:
  8552. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  8553. elif status == "failed" and hms_errors:
  8554. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  8555. await service.update_archive_status(
  8556. archive_id,
  8557. status=status,
  8558. completed_at=(
  8559. # A reconciled completed print ended at an estimated time,
  8560. # not at the reconnect (#3310).
  8561. data.get("_reconciled_completed_at") or datetime.now(timezone.utc)
  8562. if status in ("completed", "failed", "aborted", "cancelled")
  8563. else None
  8564. ),
  8565. failure_reason=failure_reason,
  8566. )
  8567. logger.info(
  8568. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  8569. )
  8570. await ws_manager.send_archive_updated(
  8571. {
  8572. "id": archive_id,
  8573. "status": status,
  8574. }
  8575. )
  8576. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  8577. # MQTT relay - publish archive updated
  8578. try:
  8579. await mqtt_relay.on_archive_updated(
  8580. archive_id=archive_id,
  8581. print_name=filename or subtask_name,
  8582. status=status,
  8583. )
  8584. except Exception:
  8585. pass # Don't fail if MQTT fails
  8586. except Exception as e:
  8587. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  8588. # Continue with other operations even if archive update fails
  8589. log_timing("Archive status update")
  8590. # Apply finance wallet charge or release reservations once. For all partial
  8591. # terminal states (failed, aborted at the printer display, or cancelled via
  8592. # Bambuddy) use this run's measured spool delta, falling back to the last
  8593. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  8594. # estimate and therefore cannot represent an interrupted run.
  8595. try:
  8596. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  8597. async with async_session() as db:
  8598. from backend.app.models.archive import PrintArchive
  8599. from backend.app.services.finance_billing import apply_print_charge_for_archive
  8600. from backend.app.services.print_log import run_being_ended
  8601. archive = await db.get(PrintArchive, archive_id)
  8602. # The run this end fills in below: charged as its own, not as
  8603. # the archive's latest dispatch (another plate of it, maybe).
  8604. charged_run = await run_being_ended(db, archive_id, printer_id, archive.started_at) if archive else None
  8605. if archive and billing_run_id is None and charged_run is None:
  8606. billing_run_id = getattr(archive, "billing_run_id", None)
  8607. if archive and archive.created_by_id is None and _print_user_info:
  8608. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  8609. await db.flush()
  8610. run_status = data.get("status", "completed")
  8611. last_progress = data.get("last_progress")
  8612. if last_progress is None:
  8613. last_progress = data.get("progress")
  8614. actual_run_grams = _compute_run_filament_grams(
  8615. run_status,
  8616. billing_planned_grams,
  8617. last_progress,
  8618. usage_results,
  8619. )
  8620. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  8621. in_memory_cost_center_id = _print_cost_center_ids.pop((printer_id, archive_id), None)
  8622. charged = await apply_print_charge_for_archive(
  8623. db,
  8624. archive_id,
  8625. charged_user_id=billing_user_id,
  8626. cost_center_id=(
  8627. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  8628. ),
  8629. print_queue_id=queue_item_id,
  8630. print_run_id=billing_run_id,
  8631. base_cost_override=billing_base_cost,
  8632. filament_usage=filament_usage,
  8633. run_entry_id=charged_run.id if charged_run is not None else None,
  8634. run_status=run_status,
  8635. )
  8636. await db.commit()
  8637. if charged:
  8638. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  8639. except Exception as e:
  8640. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  8641. printer_info = printer_manager.get_printer(printer_id)
  8642. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8643. billing_filename = filename or subtask_name or "Unknown"
  8644. billing_error = str(e)
  8645. try:
  8646. await ws_manager.broadcast(
  8647. {
  8648. "type": "billing_charge_failed",
  8649. "printer_id": printer_id,
  8650. "printer_name": billing_printer_name,
  8651. "filename": billing_filename,
  8652. "archive_id": archive_id,
  8653. }
  8654. )
  8655. except Exception as notification_error:
  8656. logger.error(
  8657. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  8658. archive_id,
  8659. notification_error,
  8660. )
  8661. async def _notify_billing_charge_failed() -> None:
  8662. try:
  8663. async with async_session() as notification_db:
  8664. await notification_service.on_billing_charge_failed(
  8665. printer_id,
  8666. billing_printer_name,
  8667. billing_filename,
  8668. archive_id,
  8669. billing_error,
  8670. notification_db,
  8671. )
  8672. except Exception as provider_error:
  8673. logger.error(
  8674. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  8675. archive_id,
  8676. provider_error,
  8677. exc_info=True,
  8678. )
  8679. spawn_background_task(
  8680. _notify_billing_charge_failed(),
  8681. name=f"billing-charge-failed-{archive_id}",
  8682. )
  8683. log_timing("Finance charge update")
  8684. # Write independent print log entry (separate table, never touches archives)
  8685. # The run's id, for the energy work below: the archive's newest run is
  8686. # the one started last, which with plates of it on two printers need not
  8687. # be the one that just ended.
  8688. completed_run_id: int | None = None
  8689. async def _write_run(db):
  8690. # Retried on a locked SQLite database: a run left open here would be
  8691. # closed again by the next reconnect's reconcile.
  8692. nonlocal completed_run_id
  8693. from backend.app.models.archive import PrintArchive
  8694. from backend.app.services.print_log import discard_open_runs, record_archive_wear, write_log_entry
  8695. archive = await db.get(PrintArchive, archive_id)
  8696. if archive is None:
  8697. # Deleted while it printed: its run has nothing left to end on.
  8698. await discard_open_runs(db, printer_id)
  8699. await db.commit()
  8700. if archive:
  8701. # Back-fill created_by_id on reprint (#730): reprint reuses the
  8702. # source archive row rather than creating a new one, so an
  8703. # archive that was auto-created from a printer-initiated
  8704. # print (created_by_id=NULL) would otherwise stay unattributed
  8705. # forever. When we have a print-session user AND the archive
  8706. # has no attribution yet, credit the current user. Never
  8707. # overwrite an existing attribution — the original uploader
  8708. # keeps ownership.
  8709. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  8710. if archive.created_by_id is None and _print_user_id is not None:
  8711. archive.created_by_id = _print_user_id
  8712. p_info = printer_manager.get_printer(printer_id)
  8713. # Per-run actuals — written to PrintLogEntry so stats reflect
  8714. # what THIS print actually used, not the source archive's
  8715. # first-run values (#1378). Helper handles the partial-print
  8716. # math (failed / cancelled / stopped get scaled to progress
  8717. # or to tracked spool deltas).
  8718. _run_status = data.get("status", "completed")
  8719. # #2614: scope the per-run estimate to the printed plate. For a
  8720. # multi-plate 3MF dispatched one plate at a time, the archive's
  8721. # filament/cost are the whole-file totals; the PrintLogEntry must
  8722. # reflect only this plate. No effect on single-plate archives (the
  8723. # plate estimate equals the whole-file value) or on the tracker
  8724. # path (measured spool deltas win in _compute_run_filament_grams).
  8725. _est_full_path = (
  8726. app_settings.base_dir / archive.file_path if archive.file_path else None
  8727. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8728. # The plate that printed, as billing reads it: a reprint of
  8729. # another plate must not log the archive's first plate.
  8730. _run_plate_id = billing_plate_id if billing_plate_id is not None else notify_plate_id
  8731. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path, _run_plate_id)
  8732. if _run_plate_id is None:
  8733. _run_plate_id = archive.plate_id
  8734. _run_grams = _compute_run_filament_grams(
  8735. _run_status,
  8736. _est_grams,
  8737. data.get("last_progress", data.get("progress")),
  8738. usage_results,
  8739. )
  8740. # Per-run cost — prefer usage_results sum. For partial prints
  8741. # we deliberately skip the topup-to-estimate logic in
  8742. # usage_tracker (which assumes the print completed); the raw
  8743. # tracked-spool sum is closer to what THIS run actually cost.
  8744. _run_cost: float | None = None
  8745. if usage_results:
  8746. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  8747. if _run_cost is None and _run_status != "completed":
  8748. _run_cost = spoolman_run_cost
  8749. if _run_cost is None and _run_status == "completed":
  8750. _run_cost = _est_cost
  8751. from backend.app.models.printer import Printer as _Printer
  8752. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  8753. run_entry = await write_log_entry(
  8754. db,
  8755. archive_id=archive.id,
  8756. # Captured by _update_queue_status above; None for
  8757. # printer-initiated prints with no queue row. Batch
  8758. # cost/energy roll-up joins on it (#342).
  8759. queue_item_id=queue_item_id,
  8760. status=_run_status,
  8761. print_name=archive.print_name,
  8762. # The plate this run printed, as the estimate above takes
  8763. # it; the archive's own is the latest run's.
  8764. plate_id=_run_plate_id,
  8765. printer_name=p_info.name if p_info else None,
  8766. printer_id=printer_id,
  8767. started_at=archive.started_at,
  8768. completed_at=archive.completed_at,
  8769. filament_type=archive.filament_type,
  8770. filament_color=archive.filament_color,
  8771. filament_used_grams=_run_grams,
  8772. cost=_run_cost,
  8773. wear_cost_per_hour=_wear_rate,
  8774. failure_reason=archive.failure_reason,
  8775. thumbnail_path=archive.thumbnail_path,
  8776. created_by_id=archive.created_by_id,
  8777. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  8778. # Reconciled completions have an unknown real end time —
  8779. # log 0 duration instead of the whole disconnect gap (#2592),
  8780. # unless it was estimated (#3310).
  8781. reconciled=bool(data.get("_reconciled")) and not data.get("_reconciled_completed_at"),
  8782. # Its time is the estimate or nothing, never measured (#3310).
  8783. duration_unmeasured=bool(data.get("_reconciled")),
  8784. # The real end of a print stopped while its printer was offline.
  8785. replaces_offline_stop=True,
  8786. )
  8787. await record_archive_wear(db, archive, run_entry)
  8788. await db.commit()
  8789. completed_run_id = run_entry.id
  8790. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  8791. try:
  8792. from backend.app.core.database import run_with_retry
  8793. await run_with_retry(_write_run, label="print log entry")
  8794. except Exception as e:
  8795. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  8796. log_timing("Print log entry")
  8797. # Run slow operations as background tasks to avoid blocking the event loop
  8798. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  8799. async def _background_energy_calculation():
  8800. """Calculate and save energy usage in background.
  8801. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  8802. backend restart no longer loses per-print energy data).
  8803. """
  8804. try:
  8805. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  8806. async with async_session() as db:
  8807. from backend.app.models.archive import PrintArchive
  8808. from backend.app.models.print_log import PrintLogEntry
  8809. from backend.app.services.print_log import energy_start_of
  8810. archive = await db.get(PrintArchive, archive_id)
  8811. if archive is None:
  8812. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  8813. return
  8814. # The ended run's own start reading: the archive's is its
  8815. # latest start's, maybe another plate's on another printer.
  8816. run_row = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  8817. start = energy_start_of(run_row, archive)
  8818. if start is None:
  8819. logger.info("[ENERGY-BG] No start kWh recorded for archive %s's run", archive_id)
  8820. return
  8821. starting_kwh = start.kwh
  8822. candidates = await energy_plug_candidates(db, printer_id)
  8823. if not candidates:
  8824. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  8825. return
  8826. # Same ordering as the start reading, so the delta below is
  8827. # against the counter that produced `starting_kwh` (#2859).
  8828. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  8829. if selected is None:
  8830. logger.warning(
  8831. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  8832. printer_id,
  8833. ", ".join(plug.name for plug in candidates),
  8834. )
  8835. return
  8836. plug, energy = selected
  8837. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  8838. energy_used = round(energy["total"] - starting_kwh, 4)
  8839. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  8840. if energy_used < 0:
  8841. logger.warning(
  8842. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  8843. archive_id,
  8844. starting_kwh,
  8845. energy["total"],
  8846. )
  8847. return
  8848. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  8849. # Each hour of the print at the price of that hour (#1251). If
  8850. # that fails, the last price known, as before, rather than no
  8851. # energy at all. Read first: the session may be unusable after.
  8852. last_price = await stored_price(db)
  8853. try:
  8854. energy_cost_value = round(
  8855. await print_energy_cost(
  8856. db,
  8857. plug_id=start.plug_id,
  8858. start_at=start.at,
  8859. start_kwh=starting_kwh,
  8860. start_price=start.price,
  8861. end_kwh=energy["total"],
  8862. end_plug_id=plug.id,
  8863. price_now=await current_price(db),
  8864. ),
  8865. 3,
  8866. )
  8867. except Exception as e:
  8868. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  8869. energy_cost_value = round(energy_used * last_price, 3)
  8870. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  8871. # reprint doesn't visually clobber the source archive's energy data
  8872. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  8873. from sqlalchemy import func
  8874. existing_runs = await db.scalar(
  8875. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  8876. )
  8877. if (existing_runs or 0) <= 1:
  8878. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  8879. # we just wrote for THIS print. Either way it's the first run.
  8880. archive.energy_kwh = energy_used
  8881. archive.energy_cost = energy_cost_value
  8882. # The ended run's energy (write_log_entry above ran before this
  8883. # background task, so its energy fields are still NULL). With
  8884. # no run written, none: the archive's newest is another print's.
  8885. if run_row is not None:
  8886. run_row.energy_kwh = energy_used
  8887. run_row.energy_cost = energy_cost_value
  8888. await db.commit()
  8889. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  8890. except Exception as e:
  8891. logger.warning("[ENERGY-BG] Failed: %s", e)
  8892. async def _background_finish_photo() -> str | None:
  8893. """Capture finish photo in background. Returns photo filename if captured."""
  8894. # #2547: set once this function has raised the plate itself (the
  8895. # timelapse path, where the moment producer returned without doing it).
  8896. # Declared out here so the `finally` can lower it again no matter where
  8897. # the capture below fails.
  8898. plate_restored_z: float | None = None
  8899. try:
  8900. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  8901. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  8902. # Read phase: settings + printer + archive in a short session, released
  8903. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  8904. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  8905. # tens of seconds; holding this session across it pinned one pooled
  8906. # connection idle-in-transaction per finishing print (issue #2572).
  8907. async with async_session() as db:
  8908. from backend.app.api.routes.settings import get_setting
  8909. from backend.app.models.archive import PrintArchive
  8910. from backend.app.models.printer import Printer
  8911. capture_enabled = await get_setting(db, "capture_finish_photo")
  8912. if capture_enabled is not None and capture_enabled.lower() != "true":
  8913. return None
  8914. if not archive_id:
  8915. return None
  8916. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  8917. archive = (
  8918. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8919. ).scalar_one_or_none()
  8920. if not printer or not archive:
  8921. return None
  8922. import uuid
  8923. from datetime import datetime
  8924. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  8925. if not archive.file_path:
  8926. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  8927. archive_dir = resolve_archive_dir(archive)
  8928. photo_filename = None
  8929. # Prefer the timelapse last-frame source when a timelapse was
  8930. # recording — it captures the moment after the toolhead parks
  8931. # but before the bed drops, which the live-camera grab below
  8932. # would miss (#1397). Skipped for external cameras (those have
  8933. # their own framing and don't see a Bambu timelapse). Only
  8934. # runs when the USER explicitly enabled timelapse for this
  8935. # print — #1721 removed Bambuddy's force-on at dispatch
  8936. # because it caused per-layer nozzle parking on Smooth-mode
  8937. # slicer profiles.
  8938. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  8939. printer.external_camera_enabled and printer.external_camera_url
  8940. )
  8941. timelapse_still_pending = False
  8942. if prefer_timelapse_source:
  8943. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  8944. archive_id=archive_id,
  8945. archive_dir=archive_dir,
  8946. rotation=getattr(printer, "camera_rotation", 0),
  8947. run_id=completed_run_id,
  8948. )
  8949. # #1721: replacement framing path — on_finish_photo_moment
  8950. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  8951. # parked, bed not yet dropped) and cached the JPEG bytes in
  8952. # _stage22_finish_frames. Consume them now so the saved photo
  8953. # has the better framing instead of the post-bed-drop angle
  8954. # the live-camera fallback below would give.
  8955. if not photo_filename:
  8956. # #1790: on the FINISH-state fallback path the producer
  8957. # task is dispatched back-to-back with this consumer, so
  8958. # a bare pop would race past with an empty result and
  8959. # the RTSP fallback below would collide with the
  8960. # producer's still-in-flight grab (single-client RTSP
  8961. # on Bambu printers). Wait for the producer to finish
  8962. # or give up before touching the cache.
  8963. #
  8964. # #2547: 20s was enough when the producer only ever grabbed a
  8965. # frame. It now also raises the plate first, which costs the
  8966. # settle window before the grab even starts — so the budget has
  8967. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  8968. # under the notification's own photo wait below.
  8969. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  8970. if in_flight is not None:
  8971. try:
  8972. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  8973. except TimeoutError:
  8974. logger.warning(
  8975. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  8976. printer_id,
  8977. )
  8978. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  8979. if cached_frame:
  8980. # Already rotated by the producer (#2708) — rotating again
  8981. # here would undo the fix on the banked-frame path, whose
  8982. # bytes reach the cache having been rotated once already.
  8983. photos_dir = archive_dir / "photos"
  8984. photos_dir.mkdir(parents=True, exist_ok=True)
  8985. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8986. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8987. photo_path = photos_dir / photo_filename
  8988. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  8989. logger.info(
  8990. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  8991. photo_filename,
  8992. len(cached_frame),
  8993. )
  8994. # #2547: the timelapse path reaches the live grab below whenever the
  8995. # video hasn't landed in time — the documented usual outcome on
  8996. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  8997. # returned early for those prints without raising the plate, so
  8998. # without this the photo that actually ships in the notification is
  8999. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  9000. # asked us to fix. The archive still gets the better video frame
  9001. # later; this is about the image the user is sent.
  9002. #
  9003. # Gated on `timelapse_was_active` precisely because that is the
  9004. # condition under which the producer skipped. On every other path it
  9005. # has already raised and lowered the plate, and repeating that here
  9006. # would be a second pointless round trip.
  9007. if (
  9008. not photo_filename
  9009. and data.get("timelapse_was_active")
  9010. and not print_dispatch_context.end_gcode_injected(printer_id)
  9011. ):
  9012. try:
  9013. async with async_session() as db:
  9014. from backend.app.api.routes.settings import get_setting
  9015. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  9016. if restore_setting is None or restore_setting.lower() == "true":
  9017. max_z = await _max_z_for_current_print(
  9018. printer_id, data, logger, bound_archive_id, notify_plate_id
  9019. )
  9020. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  9021. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  9022. plate_restored_z = max_z
  9023. except Exception as e:
  9024. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  9025. # Fallback chain: external camera → buffered live frame →
  9026. # fresh RTSP capture. Only runs if the timelapse path above
  9027. # didn't already produce a photo.
  9028. # Chamber light for the live capture below (#1655).
  9029. async with camera_light(printer if not photo_filename else None):
  9030. if not photo_filename:
  9031. if printer.external_camera_enabled and printer.external_camera_url:
  9032. logger.info("[PHOTO-BG] Using external camera")
  9033. from backend.app.api.routes.camera import live_frame_for_capture
  9034. from backend.app.services.external_camera import capture_frame
  9035. # #2707: the second half of the finish-photo failure — the
  9036. # pre-capture and this fallback both collided with the live
  9037. # view. None here continues down the fallback chain.
  9038. defer, buffered = live_frame_for_capture(printer_id)
  9039. if defer:
  9040. frame_data = buffered
  9041. else:
  9042. frame_data = await capture_frame(
  9043. printer.external_camera_url,
  9044. printer.external_camera_type or "mjpeg",
  9045. snapshot_url=printer.external_camera_snapshot_url,
  9046. )
  9047. if frame_data:
  9048. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  9049. photos_dir = archive_dir / "photos"
  9050. photos_dir.mkdir(parents=True, exist_ok=True)
  9051. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9052. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9053. photo_path = photos_dir / photo_filename
  9054. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  9055. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  9056. else:
  9057. # Check if camera stream is active - use buffered frame to avoid freeze
  9058. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  9059. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  9060. active_chamber_for_printer = [
  9061. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  9062. ]
  9063. buffered_frame = get_buffered_frame(printer_id)
  9064. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  9065. # Use frame from active stream
  9066. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  9067. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  9068. photos_dir = archive_dir / "photos"
  9069. photos_dir.mkdir(parents=True, exist_ok=True)
  9070. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9071. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9072. photo_path = photos_dir / photo_filename
  9073. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  9074. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  9075. else:
  9076. # No active stream - capture new frame
  9077. from backend.app.services.camera import capture_finish_photo
  9078. photo_filename = await capture_finish_photo(
  9079. printer_id=printer_id,
  9080. ip_address=printer.ip_address,
  9081. access_code=printer.access_code,
  9082. model=printer.model,
  9083. archive_dir=archive_dir,
  9084. rotation=getattr(printer, "camera_rotation", 0),
  9085. )
  9086. # Write phase: attach the photo in a fresh short-lived session.
  9087. if photo_filename:
  9088. async with async_session() as db:
  9089. from backend.app.models.archive import PrintArchive
  9090. from backend.app.services.print_log import add_run_photo, run_of
  9091. arch = await db.get(PrintArchive, archive_id)
  9092. # The ended print's own list takes it too: the archive's
  9093. # holds every print's.
  9094. run = await run_of(db, archive_id, completed_run_id) if completed_run_id is not None else None
  9095. if arch is not None:
  9096. photos = arch.photos or []
  9097. photos.append(photo_filename)
  9098. arch.photos = photos
  9099. add_run_photo(run, photo_filename)
  9100. await db.commit()
  9101. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  9102. # The short wait above is bounded so a slow printer can't hold up
  9103. # the print-complete notification, which is what the caller is
  9104. # blocking on. When it ran out with the video still on its way,
  9105. # keep waiting off to the side and add the better frame to the
  9106. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  9107. # users, whose videos routinely take minutes to transfer, never get
  9108. # the pre-bed-drop framing this path exists to provide.
  9109. #
  9110. # Spawned here rather than at the point the wait gave up: both this
  9111. # function and the upgrade do a read-modify-write on `photos`, and
  9112. # the live-camera fallback above can take tens of seconds. Starting
  9113. # the upgrade before that write means the two can interleave and one
  9114. # silently drops the other's entry, leaving a JPEG on disk that the
  9115. # gallery never lists.
  9116. if timelapse_still_pending:
  9117. spawn_background_task(
  9118. _upgrade_finish_photo_from_timelapse(
  9119. archive_id,
  9120. archive_dir,
  9121. rotation=getattr(printer, "camera_rotation", 0),
  9122. run_id=completed_run_id,
  9123. ),
  9124. name=f"finish-photo-upgrade-{archive_id}",
  9125. )
  9126. return photo_filename
  9127. except Exception as e:
  9128. logger.warning("[PHOTO-BG] Failed: %s", e)
  9129. return None
  9130. finally:
  9131. # #2547: we raised the plate, so we owe the move back down — even if
  9132. # the capture in between threw. Otherwise the user finds the print
  9133. # pinned under the nozzle.
  9134. if plate_restored_z is not None:
  9135. try:
  9136. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  9137. except Exception as e:
  9138. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  9139. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  9140. # Photo capture task - result will be used by notifications
  9141. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  9142. log_timing("Background tasks scheduled (energy, photo)")
  9143. # Also run smart plug, notifications, and maintenance as background tasks
  9144. print_status = data.get("status", "completed")
  9145. async def _background_smart_plug():
  9146. """Handle smart plug automation in background."""
  9147. try:
  9148. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  9149. async with async_session() as db:
  9150. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  9151. logger.info("[AUTO-OFF-BG] Completed")
  9152. except Exception as e:
  9153. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  9154. async def _background_notifications(finish_photo_filename: str | None = None):
  9155. """Send print complete notifications in background."""
  9156. try:
  9157. logger.info(
  9158. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  9159. )
  9160. async with async_session() as db:
  9161. from backend.app.models.archive import PrintArchive
  9162. from backend.app.models.printer import Printer
  9163. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9164. printer = result.scalar_one_or_none()
  9165. printer_name = printer.name if printer else f"Printer {printer_id}"
  9166. archive_data = None
  9167. if archive_id:
  9168. from backend.app.models.print_log import PrintLogEntry
  9169. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  9170. archive = archive_result.scalar_one_or_none()
  9171. # The run that ended: the archive shows its latest, which
  9172. # with another plate of it printing elsewhere is not this.
  9173. run = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  9174. run_started = run.started_at if run is not None else archive.started_at if archive else None
  9175. run_completed = run.completed_at if run is not None else archive.completed_at if archive else None
  9176. if archive:
  9177. # Actual elapsed time from started_at/completed_at when both are
  9178. # populated (every terminal status sets completed_at after #1198).
  9179. # Falls back to None so the notification path can decide whether to
  9180. # render the slicer estimate as a last resort.
  9181. actual_time_seconds = None
  9182. # Unknown for a completion reconciled at reconnect: the
  9183. # print ended while the printer was offline and
  9184. # completed_at is the reconnect, so the gap would read
  9185. # as the duration -- 14 h for a night offline (DB-C9).
  9186. # An estimated end (#3310) gives the estimate.
  9187. if (
  9188. run_started
  9189. and run_completed
  9190. and (not data.get("_reconciled") or data.get("_reconciled_completed_at"))
  9191. ):
  9192. elapsed = (run_completed - run_started).total_seconds()
  9193. if elapsed > 0:
  9194. actual_time_seconds = int(elapsed)
  9195. archive_data = {
  9196. "print_time_seconds": archive.print_time_seconds,
  9197. "actual_time_seconds": actual_time_seconds,
  9198. "actual_filament_grams": archive.filament_used_grams,
  9199. "failure_reason": run.failure_reason if run is not None else archive.failure_reason,
  9200. "created_by_id": archive.created_by_id,
  9201. }
  9202. # Scale filament usage for partial prints
  9203. if print_status != "completed" and archive.filament_used_grams:
  9204. progress = data.get("progress") or 0
  9205. scale = _partial_progress_scale(progress)
  9206. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  9207. archive_data["progress"] = progress
  9208. # Pass per-slot data from archive.extra_data
  9209. if archive.extra_data and archive.extra_data.get("filament_slots"):
  9210. slots = archive.extra_data["filament_slots"]
  9211. if print_status != "completed":
  9212. scale = _partial_progress_scale(data.get("progress"))
  9213. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  9214. archive_data["filament_slots"] = slots
  9215. # Scope project-summed totals down to the plate that was
  9216. # actually printed — see _scope_notification_archive_data_to_plate
  9217. # for the why (#1785).
  9218. archive_data = _scope_notification_archive_data_to_plate(
  9219. archive_data,
  9220. archive.file_path,
  9221. notify_plate_id,
  9222. print_status,
  9223. data.get("progress"),
  9224. app_settings.base_dir,
  9225. )
  9226. # Enrich filament_grams from usage_results when archive has no 3MF data
  9227. if not archive_data.get("actual_filament_grams") and usage_results:
  9228. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  9229. if total_from_usage > 0:
  9230. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  9231. # Pass usage tracker results for AMS slot info in notifications
  9232. if usage_results:
  9233. archive_data["usage_results"] = usage_results
  9234. # Add finish photo URL and image bytes if available
  9235. if finish_photo_filename:
  9236. photo_url, photo_bytes = await _finish_photo_for_notification(
  9237. db, archive, archive_id, finish_photo_filename
  9238. )
  9239. if photo_url:
  9240. archive_data["finish_photo_url"] = photo_url
  9241. if photo_bytes:
  9242. archive_data["image_data"] = photo_bytes
  9243. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  9244. await notification_service.on_print_complete(
  9245. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  9246. )
  9247. else:
  9248. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  9249. # Post-print outcome confirmation (#1898). Runs in this
  9250. # background task so the finish photo fetched above rides
  9251. # along with the prompt.
  9252. if print_status == "completed" and archive_id:
  9253. await _dispatch_outcome_confirmation_safely(
  9254. db, printer_id, printer_name, data, archive_id, archive_data, run_id=completed_run_id
  9255. )
  9256. # Send user-specific email notification
  9257. if archive_data:
  9258. created_by_id = archive_data.get("created_by_id")
  9259. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  9260. await _dispatch_user_print_email(
  9261. print_status,
  9262. created_by_id,
  9263. printer_name,
  9264. raw_filename,
  9265. db,
  9266. image_data=archive_data.get("image_data"),
  9267. finish_photo_url=archive_data.get("finish_photo_url"),
  9268. )
  9269. logger.info("[NOTIFY-BG] Completed")
  9270. except Exception as e:
  9271. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  9272. async def _background_maintenance_check():
  9273. """Check for maintenance due in background."""
  9274. if print_status != "completed":
  9275. return
  9276. try:
  9277. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  9278. async with async_session() as db:
  9279. from backend.app.models.printer import Printer
  9280. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9281. printer = result.scalar_one_or_none()
  9282. printer_name = printer.name if printer else f"Printer {printer_id}"
  9283. await ensure_default_types(db)
  9284. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  9285. attention = [
  9286. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  9287. ]
  9288. items_needing_attention = [
  9289. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  9290. for item in attention
  9291. ]
  9292. if items_needing_attention:
  9293. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  9294. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  9295. # MQTT relay - publish maintenance alerts
  9296. for item in attention:
  9297. current_value, threshold, unit = maintenance_alert_values(item)
  9298. try:
  9299. await mqtt_relay.on_maintenance_alert(
  9300. printer_id=printer_id,
  9301. printer_name=printer_name,
  9302. maintenance_type=item.maintenance_type_name,
  9303. current_value=current_value,
  9304. threshold=threshold,
  9305. unit=unit,
  9306. )
  9307. except Exception:
  9308. pass # Don't fail if MQTT fails
  9309. else:
  9310. logger.info("[MAINT-BG] Completed (no items need attention)")
  9311. except Exception as e:
  9312. logger.warning("[MAINT-BG] Failed: %s", e)
  9313. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  9314. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  9315. # Notification task waits for photo capture to complete first (with timeout).
  9316. # When a timelapse was recording, photo sourcing polls the per-print
  9317. # timelapse for up to 60s (#1397) — extend the budget so the notification
  9318. # carries the correct bed-up photo instead of falling through to the
  9319. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  9320. #
  9321. # #2547: both budgets now have to cover a plate restore as well.
  9322. #
  9323. # Without timelapse, the wait is on the moment producer, which raises the
  9324. # plate before its grab — so this has to outlast that producer's own budget.
  9325. #
  9326. # With timelapse, the capture polls up to
  9327. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  9328. # falls back to a live grab, which is the case that raises the plate. At the
  9329. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  9330. # restore would have moved the plate for a photo nobody waited for.
  9331. photo_wait_timeout = (
  9332. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  9333. if data.get("timelapse_was_active")
  9334. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  9335. )
  9336. async def _photo_then_notify():
  9337. """Wait for photo capture, then send notification with photo URL."""
  9338. finish_photo = None
  9339. try:
  9340. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  9341. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  9342. except TimeoutError:
  9343. logger.warning(
  9344. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  9345. photo_wait_timeout,
  9346. )
  9347. except Exception as e:
  9348. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  9349. try:
  9350. await _background_notifications(finish_photo)
  9351. except Exception as e:
  9352. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  9353. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  9354. # Stitch external camera layer timelapse if session was active
  9355. print_status = data.get("status", "completed")
  9356. async def _background_layer_timelapse():
  9357. """Stitch layer timelapse and attach to archive."""
  9358. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  9359. try:
  9360. if print_status == "completed":
  9361. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  9362. # The run the frames belong to, read before the stitch: it can
  9363. # take long enough for the archive to start printing again.
  9364. run_started_at = None
  9365. if archive_id:
  9366. async with async_session() as db:
  9367. run_archive = await ArchiveService(db).get_archive(archive_id)
  9368. run_started_at = run_archive.started_at if run_archive else None
  9369. timelapse_path = await tl_complete(printer_id)
  9370. if timelapse_path and archive_id:
  9371. await _attach_layer_timelapse(
  9372. archive_id, timelapse_path, notify_plate_id, run_started_at, run_id=completed_run_id
  9373. )
  9374. elif timelapse_path:
  9375. # Timelapse created but no archive - just clean up
  9376. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  9377. else:
  9378. # Print failed or cancelled - cancel timelapse session
  9379. cancel_session(printer_id)
  9380. logger.info(
  9381. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  9382. )
  9383. except Exception as e:
  9384. logger.warning("[LAYER-TL] Failed: %s", e)
  9385. # A completed print's session left _active_sessions when its stitch
  9386. # began: the one there now belongs to the next print, which may have
  9387. # started during the stitch, and must not lose its frames.
  9388. if print_status != "completed":
  9389. try:
  9390. cancel_session(printer_id)
  9391. except Exception:
  9392. pass # Best-effort timelapse session cancellation on error
  9393. layer_timelapse = _background_layer_timelapse()
  9394. if archive_id and print_status == "completed":
  9395. layer_timelapse = _mark_run_finishing(archive_id, layer_timelapse)
  9396. spawn_background_task(layer_timelapse, name="background-layer-timelapse")
  9397. log_timing("All background tasks scheduled")
  9398. # Auto-scan for timelapse if recording was active during the print
  9399. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  9400. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  9401. # Schedule timelapse scan as background task with retries
  9402. # The printer needs time to encode the video after print completion
  9403. _schedule_timelapse_scan(archive_id, printer_id, plate_id=notify_plate_id, run_id=completed_run_id)
  9404. log_timing("Timelapse scan scheduled")
  9405. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  9406. # AMS sensor history recording
  9407. _ams_history_task: asyncio.Task | None = None
  9408. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  9409. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  9410. def _retention_days(stored: str | None, default: int) -> int:
  9411. """A history retention setting as days to keep: at least 1, the default
  9412. when unset or unreadable. A stored 0 or less (the API took one before it
  9413. had a minimum) would put the cutoff at now and delete all history."""
  9414. try:
  9415. return max(1, int(stored)) if stored is not None else default
  9416. except (TypeError, ValueError):
  9417. return default
  9418. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  9419. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  9420. _ams_alarm_cooldown: dict[str, datetime] = {}
  9421. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  9422. # (printer_id, ams_id) already reported as sending the drop index and no
  9423. # percentage. Logged once each so a supported printer that turns out to do this
  9424. # shows up in a support bundle rather than as a user wondering where the
  9425. # humidity reading went -- see the note at the read site below (#3140).
  9426. _ams_index_only_logged: set[tuple[int, int]] = set()
  9427. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  9428. """Temperature at which the AMS alarm fires, falling back to the display band.
  9429. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  9430. when a notification was sent as well, which is why a room above it made the
  9431. alarm fire once an hour for as long as the weather lasted -- and the only way
  9432. to stop that was to raise the display band and lose the colour that says the
  9433. unit is warm (#2905).
  9434. Unset resolves to the fair threshold, so an install that never sets one is
  9435. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  9436. so that arrives here as a string and is handled by the same branch as any
  9437. other unparseable value -- there is no separate sentinel to keep in sync.
  9438. A non-positive value is refused rather than honoured: zero would alarm
  9439. permanently, and it is far more likely to be a cleared field than a
  9440. deliberate choice.
  9441. """
  9442. if raw_alarm_value is None:
  9443. return fair_threshold
  9444. try:
  9445. value = float(raw_alarm_value)
  9446. except (TypeError, ValueError):
  9447. return fair_threshold
  9448. if not math.isfinite(value) or value <= 0:
  9449. return fair_threshold
  9450. return value
  9451. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  9452. # through a cycle and the cool-down after it (#1802). Stored in the settings
  9453. # table rather than alongside _ams_alarm_cooldown above, because a restart
  9454. # partway through a cool-down would otherwise resume alarming about heat the
  9455. # user asked for — the same internal-timestamp-row pattern as
  9456. # support.py's debug_logging_enabled_at.
  9457. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  9458. # Upper bound on that suppression. The latch normally clears as soon as the unit
  9459. # reads at or below the threshold; see utils.ams_drying for why this cap only
  9460. # matters when it never does.
  9461. AMS_DRYING_GRACE_MINUTES = 120
  9462. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  9463. """Read the persisted per-AMS drying latch, dropping entries out of window.
  9464. Anything older than the grace cap would expire on its next visit anyway, so
  9465. discarding it here costs nothing and stops rows for deleted printers from
  9466. accumulating.
  9467. Stamps ahead of now get two defences, because a box whose clock jumps
  9468. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  9469. ones are discarded outright, and the rest are clamped to now. Without the
  9470. clamp the cap would measure from a moment that has not happened yet and hold
  9471. the alarm quiet for the skew on top of the cap. One unnecessary notification
  9472. after a clock jump is a far better failure than an alarm silently disabled
  9473. for hours.
  9474. """
  9475. from backend.app.models.settings import Settings
  9476. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9477. setting = result.scalar_one_or_none()
  9478. if not setting or not setting.value:
  9479. return {}
  9480. try:
  9481. raw = json.loads(setting.value)
  9482. except (ValueError, TypeError):
  9483. return {} # Corrupted row → no latch, alarms behave as they did before
  9484. if not isinstance(raw, dict):
  9485. return {}
  9486. now = datetime.now(timezone.utc)
  9487. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  9488. latch: dict[str, datetime] = {}
  9489. for key, value in raw.items():
  9490. try:
  9491. stamp = datetime.fromisoformat(str(value))
  9492. except (ValueError, TypeError):
  9493. continue
  9494. if stamp.tzinfo is None:
  9495. stamp = stamp.replace(tzinfo=timezone.utc)
  9496. if not (now - window <= stamp <= now + window):
  9497. continue
  9498. # Nothing may sit in the future: suppression is measured as now minus
  9499. # the stamp, so a stamp ahead of now would extend it by the skew on top
  9500. # of the cap. Clamping the survivors keeps the cap an actual cap.
  9501. latch[str(key)] = min(stamp, now)
  9502. return latch
  9503. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  9504. """Persist the latch, writing only when it actually changed.
  9505. Adds the session change but does not commit — the caller's own commit
  9506. carries it, so the latch lands in the same transaction as the sensor rows
  9507. that produced it.
  9508. """
  9509. from backend.app.models.settings import Settings
  9510. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  9511. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9512. setting = result.scalar_one_or_none()
  9513. if setting is None:
  9514. # Don't create the row on installs that never dry anything.
  9515. if payload != "{}":
  9516. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  9517. elif setting.value != payload:
  9518. setting.value = payload
  9519. def _ams_has_filament(ams_data: dict) -> bool:
  9520. """True if this AMS unit has at least one tray slot holding filament.
  9521. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  9522. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  9523. still report sensor readings, but those readings are ambient and not
  9524. actionable: no filament to dry, no humidity to push down. #1619 — gate
  9525. humidity/temperature alarms on this check so empty units don't generate
  9526. hourly noise. Sensor history still records regardless so the UI charts
  9527. stay continuous.
  9528. Fallback path inspects the `tray` array's `tray_type` fields for setups
  9529. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  9530. """
  9531. bits = ams_data.get("tray_exist_bits")
  9532. if isinstance(bits, str) and bits.strip():
  9533. try:
  9534. return int(bits, 16) > 0
  9535. except ValueError:
  9536. pass
  9537. trays = ams_data.get("tray")
  9538. if isinstance(trays, list):
  9539. return any(
  9540. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  9541. )
  9542. return False
  9543. async def record_ams_history():
  9544. """Background task to record AMS humidity and temperature data."""
  9545. logger = logging.getLogger(__name__)
  9546. # Wait a short time for MQTT connections to establish on startup
  9547. await asyncio.sleep(10)
  9548. while True:
  9549. try:
  9550. from backend.app.models.ams_history import AMSSensorHistory
  9551. from backend.app.models.printer import Printer
  9552. from backend.app.models.settings import Settings
  9553. async with async_session() as db:
  9554. # Get all active printers
  9555. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9556. printers = result.scalars().all()
  9557. # Get alarm thresholds from settings
  9558. humidity_threshold = 60.0 # Default: fair threshold
  9559. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  9560. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  9561. setting = result.scalar_one_or_none()
  9562. if setting:
  9563. try:
  9564. humidity_threshold = float(setting.value)
  9565. except (ValueError, TypeError):
  9566. pass # Keep default threshold if stored value is invalid
  9567. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  9568. setting = result.scalar_one_or_none()
  9569. if setting:
  9570. try:
  9571. temp_fair_threshold = float(setting.value)
  9572. except (ValueError, TypeError):
  9573. pass # Keep default threshold if stored value is invalid
  9574. # The alarm gets its own threshold, seeded from the resolved fair
  9575. # value so an install that has never set one behaves exactly as
  9576. # it did before (#2905). ams_temp_fair decides when the card turns
  9577. # amber; 35 C is a reasonable place to change a colour and not a
  9578. # reasonable place to page someone. A room above it makes the
  9579. # alarm fire once an hour for as long as the weather lasts, and
  9580. # the only way to stop it was to raise the display band and lose
  9581. # the colour that says the unit is warm.
  9582. #
  9583. # An unset value is stored as the literal "None", which the except
  9584. # below swallows the same way it swallows garbage -- so the
  9585. # fallback costs nothing and needs no sentinel of its own.
  9586. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  9587. setting = result.scalar_one_or_none()
  9588. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  9589. temp_fair_threshold, setting.value if setting else None
  9590. )
  9591. # Per-filament humidity threshold overrides (#1605) — resolved
  9592. # per-AMS below from the loaded tray types. Reuses the same
  9593. # resolver as the auto-drying scheduler so behavior stays in
  9594. # lockstep across both consumers.
  9595. from backend.app.services.print_scheduler import PrintScheduler
  9596. per_type_humidity_thresholds: dict[str, int] = {}
  9597. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  9598. setting = result.scalar_one_or_none()
  9599. if setting and setting.value:
  9600. try:
  9601. raw = json.loads(setting.value)
  9602. if isinstance(raw, dict):
  9603. for k, v in raw.items():
  9604. try:
  9605. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  9606. v
  9607. )
  9608. except (TypeError, ValueError):
  9609. continue
  9610. except (ValueError, TypeError):
  9611. pass # Invalid JSON → no overrides, fall through to global threshold
  9612. # Per-AMS drying latch (#1802), loaded once per pass and written
  9613. # back below only if a unit changed it.
  9614. drying_latch = await _load_ams_drying_latch(db)
  9615. drying_latch_before = dict(drying_latch)
  9616. recorded_count = 0
  9617. for printer in printers:
  9618. # Get current state from printer manager
  9619. state = printer_manager.get_status(printer.id)
  9620. if not state or not state.connected or not state.raw_data:
  9621. continue # Skip disconnected printers - don't use stale data
  9622. raw_data = state.raw_data
  9623. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  9624. continue
  9625. # Record data for each AMS unit
  9626. for ams_data in raw_data["ams"]:
  9627. ams_id = int(ams_data.get("id", 0))
  9628. # Percentage only. The 1-5 index is inverted, so
  9629. # charting it as a percentage drew the wettest units as
  9630. # the driest (#3140); a unit that reports no percentage
  9631. # leaves a gap in the chart instead. See
  9632. # utils/ams_humidity.
  9633. humidity = ams_humidity_percent(ams_data)
  9634. # No supported printer is known to send the index
  9635. # alone -- the report came from unsupported firmware,
  9636. # and no install has been seen using the old fallback.
  9637. # "Known" is doing work there, so say so once per unit:
  9638. # the alternative is a silent blank card.
  9639. if humidity is None and ams_data.get("humidity") is not None:
  9640. unit_key = (printer.id, ams_id)
  9641. if unit_key not in _ams_index_only_logged:
  9642. _ams_index_only_logged.add(unit_key)
  9643. logger.info(
  9644. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  9645. "percentage. The index is inverted and is not shown as a percentage "
  9646. "(#3140), so this unit has no humidity reading, chart or alarm. "
  9647. "Please report this with the printer and AMS firmware versions.",
  9648. printer.name,
  9649. ams_id,
  9650. )
  9651. # Get temperature
  9652. temperature = None
  9653. temp_str = ams_data.get("temp")
  9654. if temp_str is not None:
  9655. try:
  9656. temperature = float(temp_str)
  9657. except (ValueError, TypeError):
  9658. pass # Skip unparseable temperature value
  9659. # Skip if no data
  9660. if humidity is None and temperature is None:
  9661. continue
  9662. # Record the data point
  9663. history = AMSSensorHistory(
  9664. printer_id=printer.id,
  9665. ams_id=ams_id,
  9666. humidity=humidity,
  9667. # Both columns hold the same reading now that the
  9668. # index can no longer reach ``humidity``. Writing it
  9669. # through the same value also stops a genuine 0%
  9670. # from being stored as NULL, which the old truthiness
  9671. # test did.
  9672. humidity_raw=humidity,
  9673. temperature=temperature,
  9674. )
  9675. db.add(history)
  9676. recorded_count += 1
  9677. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  9678. is_ams_ht = ams_id >= 128
  9679. if is_ams_ht:
  9680. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  9681. else:
  9682. ams_label = f"AMS-{chr(65 + ams_id)}"
  9683. # Skip alarm dispatch for empty AMS units — humidity /
  9684. # temperature readings are ambient with no filament to
  9685. # protect, and the hourly notification just becomes
  9686. # noise. Sensor history was already recorded above so
  9687. # the UI charts stay continuous (#1619). Per-AMS check
  9688. # so a multi-AMS setup with one loaded + one empty
  9689. # still alarms on the loaded unit.
  9690. if not _ams_has_filament(ams_data):
  9691. continue
  9692. # Resolve per-filament humidity threshold for this AMS
  9693. # unit (#1605). Falls back to the global ams_humidity_fair
  9694. # when no per-type overrides are configured.
  9695. trays = ams_data.get("tray", []) or []
  9696. effective_humidity_threshold = float(
  9697. PrintScheduler.resolve_humidity_threshold(
  9698. trays, per_type_humidity_thresholds, int(humidity_threshold)
  9699. )
  9700. )
  9701. # Check humidity alarm (only if above threshold)
  9702. if humidity is not None and humidity > effective_humidity_threshold:
  9703. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  9704. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9705. now = datetime.now(timezone.utc)
  9706. if (
  9707. last_alarm is None
  9708. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9709. ):
  9710. _ams_alarm_cooldown[cooldown_key] = now
  9711. logger.info(
  9712. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  9713. )
  9714. try:
  9715. # Call different notification method based on AMS type
  9716. if is_ams_ht:
  9717. await notification_service.on_ams_ht_humidity_high(
  9718. printer.id,
  9719. printer.name,
  9720. ams_label,
  9721. humidity,
  9722. effective_humidity_threshold,
  9723. db,
  9724. )
  9725. else:
  9726. await notification_service.on_ams_humidity_high(
  9727. printer.id,
  9728. printer.name,
  9729. ams_label,
  9730. humidity,
  9731. effective_humidity_threshold,
  9732. db,
  9733. )
  9734. except Exception as e:
  9735. logger.warning("Failed to send humidity alarm: %s", e)
  9736. # A drying cycle heats the unit far past ams_temp_fair on
  9737. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  9738. # AMS-HT, against a 35 C default — so the alarm fired
  9739. # once an hour for the whole cycle and kept firing while
  9740. # the unit cooled back down (#1802). Latch on the
  9741. # firmware's own drying state and hold until the reading
  9742. # returns to normal. Humidity is deliberately left alone:
  9743. # it falls during drying, which is the whole point.
  9744. latch_key = f"{printer.id}:{ams_id}"
  9745. # The latch releases at `threshold`, so it takes the alarm
  9746. # number too. Handing it the display band would strand the
  9747. # latch on any unit that settles back above it -- a room
  9748. # where the AMS rests at 37.7 C never returns under a 35 C
  9749. # band, so the latch could only expire on the grace cap
  9750. # rather than releasing when the unit had actually cooled.
  9751. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  9752. drying_active=is_drying_active(ams_data),
  9753. temperature=temperature,
  9754. threshold=temp_alarm_threshold,
  9755. latched_at=drying_latch.get(latch_key),
  9756. now=datetime.now(timezone.utc),
  9757. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  9758. )
  9759. if new_latch is None:
  9760. drying_latch.pop(latch_key, None)
  9761. else:
  9762. drying_latch[latch_key] = new_latch
  9763. # Check temperature alarm (only if above threshold)
  9764. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  9765. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  9766. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9767. now = datetime.now(timezone.utc)
  9768. if (
  9769. last_alarm is None
  9770. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9771. ):
  9772. _ams_alarm_cooldown[cooldown_key] = now
  9773. logger.info(
  9774. f"Sending temperature alarm for {printer.name} {ams_label}: "
  9775. f"{temperature}°C > {temp_alarm_threshold}°C"
  9776. )
  9777. try:
  9778. # Call different notification method based on AMS type
  9779. if is_ams_ht:
  9780. # The reported threshold has to be the one
  9781. # that fired, or the message says "> 35 °C"
  9782. # while firing at 45.
  9783. await notification_service.on_ams_ht_temperature_high(
  9784. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9785. )
  9786. else:
  9787. await notification_service.on_ams_temperature_high(
  9788. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9789. )
  9790. except Exception as e:
  9791. logger.warning("Failed to send temperature alarm: %s", e)
  9792. if drying_latch != drying_latch_before:
  9793. await _save_ams_drying_latch(db, drying_latch)
  9794. await db.commit()
  9795. if recorded_count > 0:
  9796. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  9797. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  9798. global _ams_cleanup_counter
  9799. _ams_cleanup_counter += 1
  9800. if _ams_cleanup_counter >= 288:
  9801. _ams_cleanup_counter = 0
  9802. # Get retention days from settings
  9803. from backend.app.models.settings import Settings
  9804. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  9805. setting = result.scalar_one_or_none()
  9806. retention_days = _retention_days(setting.value if setting else None, AMS_HISTORY_RETENTION_DAYS)
  9807. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9808. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  9809. await db.commit()
  9810. if result.rowcount > 0:
  9811. logger.info(
  9812. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  9813. )
  9814. # Wait until next recording interval
  9815. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  9816. except asyncio.CancelledError:
  9817. break
  9818. except Exception as e:
  9819. logger.warning("AMS history recording failed: %s", e)
  9820. await asyncio.sleep(60) # Wait a bit before retrying
  9821. def start_ams_history_recording():
  9822. """Start the AMS history recording background task."""
  9823. global _ams_history_task
  9824. if _ams_history_task is None:
  9825. _ams_history_task = asyncio.create_task(record_ams_history())
  9826. logging.getLogger(__name__).info("AMS history recording started")
  9827. def stop_ams_history_recording():
  9828. """Stop the AMS history recording background task."""
  9829. global _ams_history_task
  9830. if _ams_history_task:
  9831. _ams_history_task.cancel()
  9832. _ams_history_task = None
  9833. logging.getLogger(__name__).info("AMS history recording stopped")
  9834. # Printer sensor history recording (nozzle / bed / chamber)
  9835. _printer_sensor_history_task: asyncio.Task | None = None
  9836. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  9837. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  9838. _printer_sensor_cleanup_counter = 0
  9839. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  9840. # MQTT parser writes, so we don't need to handle per-model field aliases here
  9841. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  9842. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  9843. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  9844. _SENSOR_TARGET_KEYS = {
  9845. "nozzle": "nozzle_target",
  9846. "nozzle_2": "nozzle_2_target",
  9847. "bed": "bed_target",
  9848. "chamber": "chamber_target",
  9849. }
  9850. async def record_printer_sensor_history():
  9851. """Background task to record nozzle / bed / chamber readings.
  9852. Pulls from `state.temperatures` (already normalised across all printer
  9853. models by the MQTT parser) rather than re-parsing raw_data, so we get
  9854. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  9855. """
  9856. logger = logging.getLogger(__name__)
  9857. await asyncio.sleep(10)
  9858. while True:
  9859. try:
  9860. from backend.app.models.printer import Printer
  9861. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  9862. from backend.app.models.settings import Settings
  9863. async with async_session() as db:
  9864. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9865. printers = result.scalars().all()
  9866. recorded_count = 0
  9867. for printer in printers:
  9868. state = printer_manager.get_status(printer.id)
  9869. if not state or not state.connected:
  9870. continue
  9871. temps = getattr(state, "temperatures", None) or {}
  9872. if not isinstance(temps, dict):
  9873. continue
  9874. for kind in _SENSOR_KINDS:
  9875. if kind not in temps:
  9876. continue
  9877. try:
  9878. value = float(temps[kind])
  9879. except (ValueError, TypeError):
  9880. continue
  9881. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  9882. target_val: float | None = None
  9883. if target_raw is not None:
  9884. try:
  9885. target_val = float(target_raw)
  9886. except (ValueError, TypeError):
  9887. target_val = None
  9888. db.add(
  9889. PrinterSensorHistory(
  9890. printer_id=printer.id,
  9891. sensor_kind=kind,
  9892. value=value,
  9893. target=target_val,
  9894. )
  9895. )
  9896. recorded_count += 1
  9897. await db.commit()
  9898. if recorded_count > 0:
  9899. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  9900. # Periodic cleanup — once every ~24h at this interval.
  9901. global _printer_sensor_cleanup_counter
  9902. _printer_sensor_cleanup_counter += 1
  9903. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  9904. if _printer_sensor_cleanup_counter >= cleanup_every:
  9905. _printer_sensor_cleanup_counter = 0
  9906. result = await db.execute(
  9907. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  9908. )
  9909. setting = result.scalar_one_or_none()
  9910. retention_days = _retention_days(
  9911. setting.value if setting else None, PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  9912. )
  9913. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9914. cleanup = await db.execute(
  9915. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  9916. )
  9917. await db.commit()
  9918. if cleanup.rowcount > 0:
  9919. logger.info(
  9920. "Cleaned up %s old printer sensor history entries (older than %s days)",
  9921. cleanup.rowcount,
  9922. retention_days,
  9923. )
  9924. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  9925. except asyncio.CancelledError:
  9926. break
  9927. except Exception as e:
  9928. logger.warning("Printer sensor history recording failed: %s", e)
  9929. await asyncio.sleep(60)
  9930. def start_printer_sensor_history_recording():
  9931. global _printer_sensor_history_task
  9932. if _printer_sensor_history_task is None:
  9933. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  9934. logging.getLogger(__name__).info("Printer sensor history recording started")
  9935. def stop_printer_sensor_history_recording():
  9936. global _printer_sensor_history_task
  9937. if _printer_sensor_history_task:
  9938. _printer_sensor_history_task.cancel()
  9939. _printer_sensor_history_task = None
  9940. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  9941. # Printer runtime tracking
  9942. _runtime_tracking_task: asyncio.Task | None = None
  9943. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  9944. # Printers the runtime tracker has seen connected since startup. One of them
  9945. # going offline clears its timestamp, so the time it was away is not counted
  9946. # when it comes back printing (DB-C5). A printer not yet seen -- still
  9947. # connecting after a restart -- keeps it for a grace period: a print that ran
  9948. # on through a Bambuddy restart is counted from the stored timestamp, as before.
  9949. _runtime_seen_connected: set[int] = set()
  9950. # A printer never seen connected this long after the tracker started is
  9951. # offline, not still connecting: its stored timestamp predates a gap too.
  9952. RUNTIME_STARTUP_GRACE_SECONDS = 120
  9953. async def track_printer_runtime():
  9954. """Background task to track printer active runtime (RUNNING state only).
  9955. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  9956. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  9957. which track mechanical wear. Pause time has no motion and no wear, so
  9958. counting it inflates maintenance warnings (#1521).
  9959. """
  9960. logger = logging.getLogger(__name__)
  9961. # Wait for MQTT connections to establish on startup
  9962. await asyncio.sleep(15)
  9963. started = time.monotonic()
  9964. while True:
  9965. try:
  9966. from backend.app.models.printer import Printer
  9967. # Fetch printer IDs in a short-lived read-only session
  9968. async with async_session() as db:
  9969. result = await db.execute(
  9970. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  9971. Printer.is_active.is_(True)
  9972. )
  9973. )
  9974. printer_rows = result.all()
  9975. now = datetime.now(timezone.utc)
  9976. updated_count = 0
  9977. # Update each printer in its own short session to minimise write-lock
  9978. # hold time and avoid blocking critical commits like queue status
  9979. # updates (#897).
  9980. for pid, pname, runtime_secs, last_update in printer_rows:
  9981. state = printer_manager.get_status(pid)
  9982. if not state:
  9983. logger.debug("[%s] Runtime tracking: no state available", pname)
  9984. continue
  9985. if not state.connected:
  9986. logger.debug("[%s] Runtime tracking: not connected", pname)
  9987. offline = pid in _runtime_seen_connected or (
  9988. time.monotonic() - started > RUNTIME_STARTUP_GRACE_SECONDS
  9989. )
  9990. if offline and last_update is not None:
  9991. try:
  9992. async with async_session() as db:
  9993. printer = await db.get(Printer, pid)
  9994. if printer:
  9995. printer.last_runtime_update = None
  9996. await db.commit()
  9997. except Exception as e:
  9998. # Still marked: the next offline tick tries again.
  9999. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  10000. continue
  10001. _runtime_seen_connected.discard(pid)
  10002. continue
  10003. _runtime_seen_connected.add(pid)
  10004. needs_commit = False
  10005. new_runtime = runtime_secs
  10006. new_last_update = last_update
  10007. if state.state == "RUNNING":
  10008. if last_update:
  10009. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  10010. elapsed = (now - lu).total_seconds()
  10011. if elapsed > 0:
  10012. new_runtime = runtime_secs + int(elapsed)
  10013. updated_count += 1
  10014. needs_commit = True
  10015. logger.debug(
  10016. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  10017. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  10018. )
  10019. else:
  10020. needs_commit = True
  10021. logger.debug("[%s] Runtime tracking: first active detection", pname)
  10022. new_last_update = now
  10023. else:
  10024. if last_update is not None:
  10025. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  10026. new_last_update = None
  10027. needs_commit = True
  10028. if needs_commit:
  10029. try:
  10030. async with async_session() as db:
  10031. result = await db.execute(select(Printer).where(Printer.id == pid))
  10032. printer = result.scalar_one_or_none()
  10033. if printer:
  10034. printer.runtime_seconds = new_runtime
  10035. printer.last_runtime_update = new_last_update
  10036. await db.commit()
  10037. except Exception as e:
  10038. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  10039. if updated_count > 0:
  10040. logger.debug("Updated runtime for %s printer(s)", updated_count)
  10041. except asyncio.CancelledError:
  10042. logger.info("Runtime tracking cancelled")
  10043. break
  10044. except Exception as e:
  10045. logger.warning("Runtime tracking failed: %s", e)
  10046. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  10047. def start_runtime_tracking():
  10048. """Start the printer runtime tracking background task."""
  10049. global _runtime_tracking_task
  10050. if _runtime_tracking_task is None:
  10051. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  10052. logging.getLogger(__name__).info("Printer runtime tracking started")
  10053. def stop_runtime_tracking():
  10054. """Stop the printer runtime tracking background task."""
  10055. global _runtime_tracking_task
  10056. if _runtime_tracking_task:
  10057. _runtime_tracking_task.cancel()
  10058. _runtime_tracking_task = None
  10059. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  10060. # SpoolBuddy device watchdog
  10061. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  10062. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  10063. async def _spoolbuddy_watchdog_loop():
  10064. """Periodic check for SpoolBuddy devices that have gone offline."""
  10065. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  10066. while True:
  10067. try:
  10068. await spoolbuddy_watchdog()
  10069. except asyncio.CancelledError:
  10070. break
  10071. except Exception as e:
  10072. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  10073. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  10074. def start_spoolbuddy_watchdog():
  10075. global _spoolbuddy_watchdog_task
  10076. if _spoolbuddy_watchdog_task is None:
  10077. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  10078. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  10079. def stop_spoolbuddy_watchdog():
  10080. global _spoolbuddy_watchdog_task
  10081. if _spoolbuddy_watchdog_task:
  10082. _spoolbuddy_watchdog_task.cancel()
  10083. _spoolbuddy_watchdog_task = None
  10084. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  10085. # Dead-MQTT-session recovery
  10086. #
  10087. # check_staleness() covers the "connected but silent" half-broken session. It
  10088. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  10089. # is the only thing left watching at that point. When paho stops making
  10090. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  10091. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  10092. # offline with the UI open the whole time, recovered only when something
  10093. # happened to nudge it.
  10094. #
  10095. # This loop is that backstop. It only touches printers that had a working
  10096. # session and lost it, and only when the MQTT port still answers — a printer
  10097. # that is simply switched off is left to paho, since rebuilding a client
  10098. # against an unreachable host achieves nothing and would fill the log every
  10099. # night.
  10100. _connection_watchdog_task: asyncio.Task | None = None
  10101. CONNECTION_WATCHDOG_INTERVAL = 60
  10102. # How long a printer must have been silent before we stop trusting paho.
  10103. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  10104. # so a session that is recovering on its own is never interrupted.
  10105. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  10106. # Per-printer floor between rebuild attempts.
  10107. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  10108. _connection_watchdog_last_attempt: dict[int, float] = {}
  10109. async def _recover_dead_printer_sessions() -> int:
  10110. """Rebuild MQTT clients that have been offline too long to still be trying.
  10111. Returns the number of printers a rebuild was attempted for (for tests and
  10112. for the caller's logging). Never raises: one unreachable printer must not
  10113. stop the sweep for the rest of the farm.
  10114. """
  10115. logger = logging.getLogger(__name__)
  10116. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  10117. now = time.monotonic()
  10118. recovered = 0
  10119. for printer_id, client in list(printer_manager._clients.items()):
  10120. try:
  10121. if client.state.connected:
  10122. _connection_watchdog_last_attempt.pop(printer_id, None)
  10123. continue
  10124. # Time since the last inbound message is the age of the last known
  10125. # good session — no extra bookkeeping needed, and it is the same
  10126. # clock is_stale() reads. 0 means this client has never had one:
  10127. # that is the initial-connect path, where paho retrying is the
  10128. # correct and only behaviour, so leave it be.
  10129. last_msg = client._last_message_time
  10130. if not last_msg:
  10131. continue
  10132. offline_for = time.time() - last_msg
  10133. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  10134. continue
  10135. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  10136. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  10137. continue
  10138. if not await check_port(client.ip_address, PORT_MQTT):
  10139. # Switched off, unplugged, or off the network. Paho's retry is
  10140. # the right handler; say so at debug level and move on.
  10141. logger.debug(
  10142. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  10143. "— leaving the reconnect to paho",
  10144. printer_id,
  10145. offline_for,
  10146. )
  10147. _connection_watchdog_last_attempt[printer_id] = now
  10148. continue
  10149. _connection_watchdog_last_attempt[printer_id] = now
  10150. recovered += 1
  10151. logger.warning(
  10152. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  10153. "rebuilding the client with a fresh session (last connect error: %s)",
  10154. printer_id,
  10155. offline_for,
  10156. PORT_MQTT,
  10157. client.last_connect_error or "none recorded",
  10158. )
  10159. # Async context, so this takes the hard-reset path: fresh client_id,
  10160. # paho's QoS 1 queue dropped. That matters — a project_file left
  10161. # unacked on the dead session would otherwise replay into the new
  10162. # one and trip 0500_4003 on the printer (#1136).
  10163. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  10164. except Exception as e:
  10165. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  10166. return recovered
  10167. async def _connection_watchdog_loop():
  10168. logger = logging.getLogger(__name__)
  10169. # Let the initial connects settle before judging anyone offline.
  10170. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  10171. while True:
  10172. try:
  10173. await _recover_dead_printer_sessions()
  10174. except asyncio.CancelledError:
  10175. break
  10176. except Exception as e:
  10177. logger.warning("Connection watchdog sweep failed: %s", e)
  10178. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  10179. def start_connection_watchdog():
  10180. global _connection_watchdog_task
  10181. if _connection_watchdog_task is None:
  10182. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  10183. logging.getLogger(__name__).info("Printer connection watchdog started")
  10184. def stop_connection_watchdog():
  10185. global _connection_watchdog_task
  10186. if _connection_watchdog_task:
  10187. _connection_watchdog_task.cancel()
  10188. _connection_watchdog_task = None
  10189. _connection_watchdog_last_attempt.clear()
  10190. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  10191. # Camera stream orphan cleanup
  10192. _camera_cleanup_task: asyncio.Task | None = None
  10193. CAMERA_CLEANUP_INTERVAL = 60
  10194. # Every this many camera cleanups (about an hour), the timelapse janitor too:
  10195. # kept frames of a failed stitch go after a day, not at the next restart.
  10196. TIMELAPSE_CLEANUP_EVERY = 60
  10197. async def _camera_cleanup_loop():
  10198. """Periodically clean up orphaned ffmpeg processes and timelapse leftovers."""
  10199. from backend.app.api.routes.camera import cleanup_orphaned_streams
  10200. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10201. rounds = 0
  10202. while True:
  10203. try:
  10204. rounds += 1
  10205. await cleanup_orphaned_streams()
  10206. except asyncio.CancelledError:
  10207. break
  10208. except Exception as e:
  10209. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  10210. try:
  10211. if rounds % TIMELAPSE_CLEANUP_EVERY == 0:
  10212. await asyncio.to_thread(cleanup_orphaned_timelapse_sessions)
  10213. except asyncio.CancelledError:
  10214. break
  10215. except Exception as e:
  10216. logging.getLogger(__name__).warning("Timelapse frames cleanup failed: %s", e)
  10217. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  10218. def start_camera_cleanup():
  10219. global _camera_cleanup_task
  10220. if _camera_cleanup_task is None:
  10221. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  10222. logging.getLogger(__name__).info("Camera stream cleanup started")
  10223. def stop_camera_cleanup():
  10224. global _camera_cleanup_task
  10225. if _camera_cleanup_task:
  10226. _camera_cleanup_task.cancel()
  10227. _camera_cleanup_task = None
  10228. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  10229. # ---------------------------------------------------------------------------
  10230. # Expected-print TTL eviction
  10231. # ---------------------------------------------------------------------------
  10232. def _evict_stale_expected_prints() -> None:
  10233. """Remove entries from _expected_prints / _expected_print_creators that are
  10234. older than _EXPECTED_PRINT_TTL_SECONDS.
  10235. This prevents unbounded growth when a print is registered (via
  10236. register_expected_print) but on_print_start never fires — e.g. because the
  10237. printer disconnects, the app restarts, or the print is started directly from
  10238. the printer panel without going through the queue.
  10239. """
  10240. # Use monotonic time so the TTL is unaffected by system clock adjustments
  10241. # (e.g. NTP sync, DST changes).
  10242. # A print that ended without its archive being found at completion leaves
  10243. # its id here; only running prints are owned.
  10244. _owned_print_archive_ids.intersection_update(_active_prints.values())
  10245. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  10246. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  10247. if not stale_keys:
  10248. return
  10249. evicted: set[tuple[int, int]] = set()
  10250. for key in stale_keys:
  10251. archive_id = _expected_prints.pop(key, None)
  10252. if archive_id is not None:
  10253. evicted.add((key[0], archive_id))
  10254. _expected_print_creators.pop(key, None)
  10255. _expected_print_registered_at.pop(key, None)
  10256. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  10257. # that have no remaining live keys in _expected_prints (all variants
  10258. # were just evicted) and are not printing right now. Print start pops
  10259. # only the names the printer reported, so the "<base>.gcode" variant
  10260. # outlives it; without the printing check its eviction two hours after
  10261. # dispatch threw away a running print's plate, AMS mapping and cost
  10262. # centre, which completion still reads (#3275).
  10263. for printer_id, archive_id in evicted:
  10264. if not _expected_or_printing_here(printer_id, archive_id):
  10265. _drop_dispatch(printer_id, archive_id)
  10266. logging.getLogger(__name__).info(
  10267. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  10268. )
  10269. async def _expected_prints_cleanup_loop() -> None:
  10270. """Background task: periodically evict stale expected-print entries."""
  10271. while True:
  10272. try:
  10273. _evict_stale_expected_prints()
  10274. except asyncio.CancelledError:
  10275. raise
  10276. except Exception as e:
  10277. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  10278. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  10279. def start_expected_prints_cleanup() -> None:
  10280. global _expected_prints_cleanup_task
  10281. if _expected_prints_cleanup_task is None:
  10282. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  10283. logging.getLogger(__name__).info("Expected prints cleanup started")
  10284. def stop_expected_prints_cleanup() -> None:
  10285. global _expected_prints_cleanup_task
  10286. if _expected_prints_cleanup_task:
  10287. _expected_prints_cleanup_task.cancel()
  10288. _expected_prints_cleanup_task = None
  10289. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  10290. # ---------------------------------------------------------------------------
  10291. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  10292. # ---------------------------------------------------------------------------
  10293. _auth_cleanup_task: asyncio.Task | None = None
  10294. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  10295. async def _run_auth_cleanup() -> None:
  10296. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  10297. from backend.app.core.database import async_session
  10298. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  10299. from backend.app.models.user_totp import UserTOTP
  10300. now = datetime.now(timezone.utc)
  10301. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  10302. try:
  10303. async with async_session() as db:
  10304. stale_cutoff = now - timedelta(hours=1)
  10305. result = await db.execute(
  10306. select(UserTOTP).where(
  10307. UserTOTP.is_enabled.is_(False),
  10308. UserTOTP.created_at < stale_cutoff,
  10309. )
  10310. )
  10311. stale_records = result.scalars().all()
  10312. if stale_records:
  10313. for rec in stale_records:
  10314. await db.delete(rec)
  10315. await db.commit()
  10316. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  10317. except Exception as e:
  10318. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  10319. # Remove expired revoked-JTI entries (they are no longer needed once the
  10320. # original token's exp has passed — the token would be rejected by JWT
  10321. # signature verification regardless).
  10322. try:
  10323. async with async_session() as db:
  10324. await db.execute(
  10325. delete(AuthEphemeralToken).where(
  10326. AuthEphemeralToken.token_type == "revoked_jti",
  10327. AuthEphemeralToken.expires_at < now,
  10328. )
  10329. )
  10330. await db.commit()
  10331. except Exception as e:
  10332. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  10333. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  10334. # Events outside this window can never affect rate-limit decisions — they only
  10335. # consume DB space. Use the same window constant as the rate limiter so the
  10336. # two are always in sync.
  10337. try:
  10338. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  10339. async with async_session() as db:
  10340. await db.execute(
  10341. delete(AuthRateLimitEvent).where(
  10342. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  10343. )
  10344. )
  10345. await db.commit()
  10346. except Exception as e:
  10347. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  10348. async def _auth_cleanup_loop() -> None:
  10349. """Periodic background task: run auth cleanup every hour."""
  10350. while True:
  10351. try:
  10352. await _run_auth_cleanup()
  10353. except asyncio.CancelledError:
  10354. break
  10355. except Exception as e:
  10356. logging.warning("Auth cleanup loop error: %s", e)
  10357. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  10358. def start_auth_cleanup() -> None:
  10359. global _auth_cleanup_task
  10360. if _auth_cleanup_task is None:
  10361. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  10362. logging.getLogger(__name__).info("Auth periodic cleanup started")
  10363. def stop_auth_cleanup() -> None:
  10364. global _auth_cleanup_task
  10365. if _auth_cleanup_task:
  10366. _auth_cleanup_task.cancel()
  10367. _auth_cleanup_task = None
  10368. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  10369. @asynccontextmanager
  10370. async def lifespan(app: FastAPI):
  10371. # Startup
  10372. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  10373. # anything else can spawn tasks that might trip it.
  10374. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  10375. install_proactor_reset_filter()
  10376. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  10377. # what turned descriptor exhaustion into a corrupted database (#2883).
  10378. from backend.app.core.fd_limit import raise_open_file_limit
  10379. raise_open_file_limit()
  10380. # Before init_db, so the warning is near the top of the log rather than
  10381. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  10382. warn_if_running_on_uvloop()
  10383. await init_db()
  10384. # Browser download tokens expire after five minutes. Remove abandoned
  10385. # prepared ZIPs at startup as well as before each new preparation so a
  10386. # quiet appliance cannot retain an unusable bundle indefinitely.
  10387. try:
  10388. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  10389. await prune_stale_printer_file_bundles()
  10390. except Exception as exc:
  10391. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  10392. # After migrations, so the is_env_managed column exists. Never raises --
  10393. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  10394. # startup (see apply_env_oidc_provider).
  10395. from backend.app.core.oidc_env import apply_env_oidc_provider
  10396. async with async_session() as oidc_db:
  10397. await apply_env_oidc_provider(oidc_db)
  10398. # Close out batches that finished before `completed` was a reachable status
  10399. # (#342). Without this the Batches tab opens on every batch created since
  10400. # the feature shipped, all still marked active. Never blocks startup.
  10401. try:
  10402. from backend.app.services.print_batch import backfill_batch_statuses
  10403. async with async_session() as batch_db:
  10404. await backfill_batch_statuses(batch_db)
  10405. except Exception as exc:
  10406. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  10407. # Register an app-scoped httpx client for Bambu Cloud services so
  10408. # per-request BambuCloudService instances reuse the same connection pool
  10409. # (important for routes like /cloud/filament-info that chain many
  10410. # get_setting_detail calls). The shared client stores no region/token
  10411. # state, so the per-request ownership pattern that fixed the region-bleed
  10412. # bug is preserved.
  10413. import httpx as _httpx
  10414. from backend.app.services.bambu_cloud import set_shared_http_client
  10415. from backend.app.services.model_providers.makerworld.service import (
  10416. set_shared_http_client as set_shared_makerworld_http_client,
  10417. )
  10418. from backend.app.services.orca_cloud import (
  10419. set_shared_http_client as set_shared_orca_http_client,
  10420. )
  10421. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  10422. set_shared_http_client(_shared_cloud_http_client)
  10423. # Reuse the same connection pool for MakerWorld — different host, same
  10424. # keep-alive pool saves a TLS handshake per request.
  10425. set_shared_makerworld_http_client(_shared_cloud_http_client)
  10426. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  10427. # each spun up (and never closed) its own client, leaking sockets.
  10428. set_shared_orca_http_client(_shared_cloud_http_client)
  10429. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  10430. # This can happen when a print was cancelled mid-print on versions before this fix.
  10431. try:
  10432. async with async_session() as db:
  10433. from backend.app.models.print_queue import PrintQueueItem
  10434. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  10435. aborted_items = result.scalars().all()
  10436. if aborted_items:
  10437. for item in aborted_items:
  10438. item.status = "cancelled"
  10439. await db.commit()
  10440. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  10441. except Exception as e:
  10442. logging.warning("Failed to fix aborted queue items: %s", e)
  10443. # Restore debug logging state from previous session
  10444. await init_debug_logging()
  10445. # Set up printer manager callbacks
  10446. loop = asyncio.get_event_loop()
  10447. printer_manager.set_event_loop(loop)
  10448. printer_manager.set_status_change_callback(on_printer_status_change)
  10449. printer_manager.set_print_start_callback(on_print_start)
  10450. printer_manager.set_print_complete_callback(on_print_complete)
  10451. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  10452. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  10453. printer_manager.set_ams_change_callback(on_ams_change)
  10454. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  10455. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  10456. await printer_manager.load_awaiting_plate_clear_from_db()
  10457. # Layer change callback for external camera timelapse
  10458. async def on_layer_change(printer_id: int, layer_num: int):
  10459. """Capture timelapse frame on layer change + first layer notification."""
  10460. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  10461. await tl_layer_change(printer_id, layer_num)
  10462. # #1867: bank a recent in-print frame so the finish-photo path has a
  10463. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  10464. # #2547 added `on_print_progress` as a second driver — this one alone
  10465. # stops firing once the final layer begins.
  10466. await _maybe_bank_inprint_frame(printer_id, layer_num)
  10467. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  10468. # Gate on actual printing state — Bambu firmware ticks layer_num during
  10469. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  10470. # nozzle clean), so a bare layer_num check can fire minutes before the
  10471. # first real extrusion. We require gcode_state == RUNNING and
  10472. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  10473. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  10474. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  10475. # edge fires later; _first_layer_notified stays clear until we actually send
  10476. # so a deferred re-evaluation can win. See issue #1837.
  10477. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  10478. client = printer_manager.get_client(printer_id)
  10479. state = client.state if client else None
  10480. if not state or state.state != "RUNNING":
  10481. return
  10482. if state.mc_print_sub_stage not in (None, 0):
  10483. return
  10484. _first_layer_notified[printer_id] = True
  10485. try:
  10486. async with async_session() as db:
  10487. from backend.app.models.printer import Printer
  10488. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  10489. printer = result.scalar_one_or_none()
  10490. if not printer:
  10491. return
  10492. printer_name = printer.name
  10493. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  10494. total_layers = state.total_layers if state else 0
  10495. image_data = await _capture_snapshot_for_notification(
  10496. printer_id, printer, logging.getLogger(__name__)
  10497. )
  10498. await notification_service.on_first_layer_complete(
  10499. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  10500. )
  10501. except Exception as e:
  10502. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  10503. printer_manager.set_layer_change_callback(on_layer_change)
  10504. async def on_print_progress(printer_id: int, percent: int):
  10505. """#2547: keep the in-print frame bank fresh through the final layer.
  10506. `on_layer_change` stops the moment the last layer starts, which on the
  10507. H2C capture that closed #2547 left the bank stale for the three minutes
  10508. that layer took. Progress is the only field that keeps advancing there,
  10509. and it freezes before the End G-code runs — so banking on it stays
  10510. inside the print and never sees a swapped plate.
  10511. """
  10512. client = printer_manager.get_client(printer_id)
  10513. state = client.state if client else None
  10514. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  10515. printer_manager.set_print_progress_callback(on_print_progress)
  10516. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  10517. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  10518. waiter = _bed_cool_waiters.get(printer_id)
  10519. if not waiter:
  10520. return
  10521. threshold = waiter["threshold"]
  10522. if bed_temp > threshold:
  10523. return
  10524. # Bed is at or below threshold — fire notification and remove waiter
  10525. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  10526. if not waiter_info:
  10527. return # Another callback already handled it
  10528. bed_cool_logger = logging.getLogger(__name__)
  10529. bed_cool_logger.info(
  10530. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  10531. bed_temp,
  10532. printer_id,
  10533. threshold,
  10534. )
  10535. try:
  10536. printer_info = printer_manager.get_printer(printer_id)
  10537. p_name = printer_info.name if printer_info else "Unknown"
  10538. async with async_session() as db:
  10539. await notification_service.on_bed_cooled(
  10540. printer_id=printer_id,
  10541. printer_name=p_name,
  10542. bed_temp=bed_temp,
  10543. threshold=threshold,
  10544. filename=waiter_info["filename"],
  10545. db=db,
  10546. )
  10547. except Exception as e:
  10548. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  10549. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  10550. async def on_drying_complete(printer_id: int, ams_id: int):
  10551. """Smart-plug auto-off-after-drying trigger (#1349).
  10552. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  10553. manager walks all plugs linked to this printer and turns off only
  10554. the ones with ``auto_off_after_drying`` enabled, after their
  10555. per-plug delay. Multiple AMS units finishing close together (e.g. a
  10556. dual-AMS dry that ends within the same MQTT push) call this once
  10557. per unit — the manager's ``_cancel_pending_off`` collapses
  10558. repeated scheduling on the same plug to one timer, so duplicate
  10559. fires are safe.
  10560. """
  10561. try:
  10562. async with async_session() as db:
  10563. await smart_plug_manager.on_drying_complete(printer_id, db)
  10564. except Exception as e:
  10565. logging.getLogger(__name__).warning(
  10566. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  10567. printer_id,
  10568. ams_id,
  10569. e,
  10570. )
  10571. printer_manager.set_drying_complete_callback(on_drying_complete)
  10572. async def on_drying_cycle_end(printer_id: int, cycle):
  10573. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  10574. from backend.app.services.spool_drying import record_drying_cycle
  10575. try:
  10576. async with async_session() as db:
  10577. await record_drying_cycle(db, printer_id, cycle)
  10578. except Exception as e:
  10579. logging.getLogger(__name__).warning(
  10580. "Failed to record drying for printer %d (AMS %d): %s",
  10581. printer_id,
  10582. cycle.ams_id,
  10583. e,
  10584. )
  10585. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  10586. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  10587. """Surface the read-back result of a spool assignment to the UI (#2582).
  10588. The MQTT client confirms (or fails to confirm) that the tray telemetry
  10589. echoed back the filament id we pushed. We relay that as a websocket
  10590. event so the frontend can toast "loaded" / "assignment didn't take"
  10591. instead of the historic silent fire-and-forget, which made the
  10592. AMS→Studio hand-off feel random to users.
  10593. """
  10594. try:
  10595. from backend.app.services.spool_assignment_notifications import (
  10596. _slot_label_from_global_tray,
  10597. )
  10598. if ams_id == 255:
  10599. global_id = 254 + tray_id
  10600. elif ams_id >= 128:
  10601. global_id = ams_id
  10602. else:
  10603. global_id = ams_id * 4 + tray_id
  10604. slot_label = _slot_label_from_global_tray(global_id)
  10605. printer_info = printer_manager.get_printer(printer_id)
  10606. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  10607. await ws_manager.broadcast(
  10608. {
  10609. "type": "spool_assignment_verified",
  10610. "printer_id": printer_id,
  10611. "printer_name": printer_name,
  10612. "ams_id": ams_id,
  10613. "tray_id": tray_id,
  10614. "slot": slot_label,
  10615. "verified": verified,
  10616. # Present on success: False means the filament setting landed
  10617. # but the K-profile (cali_idx) did not — the reporter's exact
  10618. # "loaded but no flow profile" symptom.
  10619. "kprofile_applied": detail.get("kprofile_applied", True),
  10620. }
  10621. )
  10622. except Exception as e:
  10623. logging.getLogger(__name__).warning(
  10624. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  10625. printer_id,
  10626. ams_id,
  10627. tray_id,
  10628. e,
  10629. )
  10630. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  10631. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  10632. """Persist a mid-print tray change for completion-time attribution.
  10633. AMS filament backup switches trays without telling the slicer, so the
  10634. tray-change log is the only record of which spool fed which layers.
  10635. Keeping it only in memory meant a restart mid-print charged everything
  10636. to the tray that finished the job.
  10637. """
  10638. try:
  10639. from backend.app.services.usage_tracker import record_tray_change
  10640. async with async_session() as db:
  10641. await record_tray_change(db, printer_id, tray_global, layer_num)
  10642. except Exception as e:
  10643. logging.getLogger(__name__).warning(
  10644. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  10645. printer_id,
  10646. tray_global,
  10647. layer_num,
  10648. e,
  10649. )
  10650. printer_manager.set_tray_change_callback(on_tray_change)
  10651. # Initialize MQTT relay from settings
  10652. async with async_session() as db:
  10653. from backend.app.api.routes.settings import get_setting
  10654. mqtt_settings = {
  10655. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  10656. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  10657. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  10658. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  10659. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  10660. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  10661. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  10662. }
  10663. await mqtt_relay.configure(mqtt_settings)
  10664. # Restore MQTT smart plug subscriptions
  10665. if mqtt_settings.get("mqtt_enabled"):
  10666. from backend.app.models.smart_plug import SmartPlug
  10667. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  10668. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  10669. mqtt_plugs = result.scalars().all()
  10670. restored = 0
  10671. for plug in mqtt_plugs:
  10672. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  10673. restored += 1
  10674. if restored:
  10675. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  10676. # Connect to all active printers
  10677. async with async_session() as db:
  10678. await init_printer_connections(db)
  10679. # Auto-connect to Spoolman if enabled
  10680. async with async_session() as db:
  10681. from backend.app.api.routes.settings import get_setting
  10682. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  10683. spoolman_url = await get_setting(db, "spoolman_url")
  10684. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  10685. try:
  10686. client = await init_spoolman_client(spoolman_url)
  10687. if await client.health_check():
  10688. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  10689. # Ensure the 'tag' extra field exists for RFID/UUID storage
  10690. field_ok = await client.ensure_tag_extra_field()
  10691. if not field_ok:
  10692. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  10693. # Register the BambuStudio slicer-preset fields used by the
  10694. # spool-edit / assign flow. Spoolman rejects PATCHes with
  10695. # unknown extra keys, so these must exist before any update
  10696. # that touches them.
  10697. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  10698. if not await client.ensure_extra_field(field_name):
  10699. logging.warning(
  10700. "Spoolman extra field %r registration failed — "
  10701. "spool slicer-preset edits will return 502",
  10702. field_name,
  10703. )
  10704. else:
  10705. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  10706. except Exception as e:
  10707. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  10708. # Start the print scheduler
  10709. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  10710. # Start the smart plug scheduler for time-based on/off
  10711. smart_plug_manager.start_scheduler()
  10712. # Start the Home Assistant sensor poller (#1148)
  10713. ha_sensor_manager.start()
  10714. location_ha_sensor_manager.start()
  10715. # Resume any pending auto-offs that were interrupted by restart
  10716. await smart_plug_manager.resume_pending_auto_offs()
  10717. # Start the notification digest scheduler
  10718. notification_service.start_digest_scheduler()
  10719. notify_live_activities.start()
  10720. notify_widgets.start()
  10721. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  10722. # provider in reactions/both mode; the notification routes resync them.
  10723. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  10724. # until the next provider save, not the whole startup.
  10725. try:
  10726. await telegram_reaction_poller.start()
  10727. except Exception as e:
  10728. logging.warning("Telegram reaction poller did not start: %s", e)
  10729. # Start the GitHub backup scheduler
  10730. await github_backup_service.start_scheduler()
  10731. # Start the local backup scheduler
  10732. await local_backup_service.start_scheduler()
  10733. await obico_detection_service.start()
  10734. # Start the library trash sweeper (#1008)
  10735. await library_trash_service.start_scheduler()
  10736. # Start the archive auto-purge sweeper (#1008 follow-up)
  10737. await archive_purge_service.start_scheduler()
  10738. # Start AMS history recording
  10739. start_ams_history_recording()
  10740. # Start printer sensor (nozzle / bed / chamber) history recording
  10741. start_printer_sensor_history_recording()
  10742. # Start printer runtime tracking
  10743. start_runtime_tracking()
  10744. # Start SpoolBuddy device watchdog
  10745. start_spoolbuddy_watchdog()
  10746. # Start camera stream orphan cleanup
  10747. start_camera_cleanup()
  10748. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  10749. start_connection_watchdog()
  10750. # One-shot sweep for timelapse session directories orphaned by a crash
  10751. # or restart that happened mid-print (in-memory session tracking can't
  10752. # survive that, and nothing else reaps the leftover frames/output file)
  10753. try:
  10754. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10755. removed = cleanup_orphaned_timelapse_sessions()
  10756. if removed:
  10757. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  10758. except Exception as e:
  10759. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  10760. # Start expected-print TTL eviction (prevents memory leak when prints are
  10761. # registered but on_print_start never fires)
  10762. start_expected_prints_cleanup()
  10763. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  10764. start_auth_cleanup()
  10765. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  10766. from backend.app.services import announcements as announcements_service
  10767. announcements_service.start()
  10768. from backend.app.services.printer_media import start_printer_download_cleanup
  10769. start_printer_download_cleanup()
  10770. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  10771. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  10772. from backend.app.services.loop_watchdog import start_loop_watchdog
  10773. start_loop_watchdog()
  10774. # Initialize virtual printer manager and sync from DB
  10775. from backend.app.services.virtual_printer import virtual_printer_manager
  10776. virtual_printer_manager.set_session_factory(async_session)
  10777. virtual_printer_manager.set_printer_manager(printer_manager)
  10778. try:
  10779. await virtual_printer_manager.sync_from_db()
  10780. logging.info("Virtual printer manager synced from database")
  10781. except Exception as e:
  10782. logging.warning("Failed to sync virtual printers: %s", e)
  10783. yield
  10784. # Shutdown
  10785. print_scheduler.stop()
  10786. smart_plug_manager.stop_scheduler()
  10787. ha_sensor_manager.stop()
  10788. location_ha_sensor_manager.stop()
  10789. notification_service.stop_digest_scheduler()
  10790. await notify_live_activities.close()
  10791. await notify_widgets.close()
  10792. await telegram_reaction_poller.aclose()
  10793. github_backup_service.stop_scheduler()
  10794. local_backup_service.stop_scheduler()
  10795. library_trash_service.stop_scheduler()
  10796. archive_purge_service.stop_scheduler()
  10797. obico_detection_service.stop()
  10798. stop_ams_history_recording()
  10799. stop_printer_sensor_history_recording()
  10800. stop_runtime_tracking()
  10801. stop_spoolbuddy_watchdog()
  10802. stop_camera_cleanup()
  10803. stop_connection_watchdog()
  10804. from backend.app.services.loop_watchdog import stop_loop_watchdog
  10805. stop_loop_watchdog()
  10806. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  10807. # cleanly rather than waiting on a queue that nothing will ever fill.
  10808. try:
  10809. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  10810. await shutdown_all_broadcasters()
  10811. except Exception as e:
  10812. logging.warning("Failed to shut down camera broadcasters: %s", e)
  10813. stop_expected_prints_cleanup()
  10814. stop_auth_cleanup()
  10815. from backend.app.services import announcements as announcements_service
  10816. announcements_service.stop()
  10817. from backend.app.services.printer_media import stop_printer_download_cleanup
  10818. await stop_printer_download_cleanup()
  10819. # Stops a timelapse editor's ffmpeg rather than leaving it to the OS.
  10820. from backend.app.services import timelapse_jobs
  10821. await timelapse_jobs.cancel_all()
  10822. printer_manager.disconnect_all()
  10823. slot_unlink_grace.reset()
  10824. await close_spoolman_client()
  10825. # Stop all virtual printer services
  10826. await virtual_printer_manager.stop_all()
  10827. await mqtt_smart_plug_service.disconnect(timeout=2)
  10828. await mqtt_relay.disconnect(timeout=2)
  10829. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  10830. set_shared_http_client(None)
  10831. set_shared_makerworld_http_client(None)
  10832. set_shared_orca_http_client(None)
  10833. await _shared_cloud_http_client.aclose()
  10834. # Checkpoint WAL (SQLite only) and close all database connections
  10835. from backend.app.core.db_dialect import is_sqlite
  10836. if is_sqlite():
  10837. try:
  10838. async with engine.begin() as conn:
  10839. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  10840. logging.info("WAL checkpoint completed")
  10841. except Exception as e:
  10842. logging.warning("WAL checkpoint failed: %s", e)
  10843. await engine.dispose()
  10844. app = FastAPI(
  10845. title=app_settings.app_name,
  10846. description="Archive and manage Bambu Lab 3MF files",
  10847. version=APP_VERSION,
  10848. lifespan=lifespan,
  10849. )
  10850. # Added first so it sits innermost, next to the routes: a refused header's value
  10851. # (often a stored token) masked in every JSON body. See core.response_redaction.
  10852. app.add_middleware(RefusedHeaderResponseMask)
  10853. def _json_safe(value):
  10854. """The validation errors with every non-finite number written as text."""
  10855. if isinstance(value, float) and not math.isfinite(value):
  10856. return str(value)
  10857. if isinstance(value, dict):
  10858. return {key: _json_safe(item) for key, item in value.items()}
  10859. if isinstance(value, list | tuple):
  10860. return [_json_safe(item) for item in value]
  10861. return value
  10862. @app.exception_handler(RequestValidationError)
  10863. async def _validation_error(_request, exc: RequestValidationError) -> JSONResponse:
  10864. """FastAPI's own 422, except that it survives a non-finite number.
  10865. A body may carry ``Infinity`` or ``NaN`` (Python's JSON reader accepts
  10866. them), and the default handler echoes the input back in its errors,
  10867. which JSON cannot hold: the request ended in an error instead of a 422.
  10868. """
  10869. return JSONResponse(status_code=422, content={"detail": _json_safe(jsonable_encoder(exc.errors()))})
  10870. # =============================================================================
  10871. # Authentication Middleware - Secures ALL API routes by default
  10872. # =============================================================================
  10873. # Public routes that don't require authentication even when auth is enabled
  10874. PUBLIC_API_ROUTES = {
  10875. # Auth routes needed before/during login
  10876. "/api/v1/auth/status",
  10877. "/api/v1/auth/login",
  10878. "/api/v1/auth/setup", # Needed for initial setup and recovery
  10879. # Advanced auth status needed for login page
  10880. "/api/v1/auth/advanced-auth/status",
  10881. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  10882. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  10883. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  10884. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  10885. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  10886. # OIDC routes that must be reachable without a JWT
  10887. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  10888. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  10889. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  10890. # Connected apps: the app's server swaps a code for the user's identity,
  10891. # authenticated by its client secret rather than a login token.
  10892. "/api/v1/connect/token",
  10893. # Version check for updates (no sensitive data)
  10894. "/api/v1/updates/version",
  10895. # Metrics endpoint handles its own prometheus_token authentication
  10896. "/api/v1/metrics",
  10897. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  10898. # this BEFORE a JWT is available to pick up the firstboot wizard's
  10899. # hostname / timezone / locale and the chrony NTP-gate state. The
  10900. # response contains user-set defaults and a public sync flag — no
  10901. # secrets. Without this entry the global auth middleware returns 401
  10902. # before the route handler runs, regardless of the route's own
  10903. # "no auth required" intent.
  10904. "/api/v1/system/appliance",
  10905. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  10906. # authenticates with a long-lived ``camwall``-scoped token in the query
  10907. # string — exactly like the camera streams two lists below, and for the same
  10908. # reason (no header to put a JWT in). "Public" here only means the middleware
  10909. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  10910. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  10911. # plain ``camera_stream`` token does NOT open this door.
  10912. "/api/v1/camwall/printers",
  10913. # Overlay branding: the route enforces overlay-scoped token authentication.
  10914. "/api/v1/overlay-branding/logo",
  10915. }
  10916. # Route prefixes that are public (for routes with dynamic segments)
  10917. PUBLIC_API_PREFIXES = [
  10918. # WebSocket connections handle their own auth
  10919. "/api/v1/ws",
  10920. # OIDC authorize redirects — include provider_id in path
  10921. "/api/v1/auth/oidc/authorize/",
  10922. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  10923. # a phone with no session, so no header can carry a JWT — the single-use
  10924. # capability token in the path IS the credential (same reasoning as the
  10925. # /dl/ slicer downloads below). The route grants nothing beyond writing
  10926. # good/reject on the one archive the token was minted for.
  10927. "/api/v1/archives/confirm/",
  10928. ]
  10929. # Route patterns that are public (read-only display data)
  10930. # These are checked with "in path" - needed because browsers load images/videos
  10931. # via <img src> and <video src> which don't include Authorization headers
  10932. PUBLIC_API_PATTERNS = [
  10933. # Thumbnails
  10934. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  10935. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  10936. # Images and media
  10937. "/photos/", # /archives/{id}/photos/{filename}
  10938. "/project-image/", # /archives/{id}/project-image/{path}
  10939. "/qrcode", # /archives/{id}/qrcode
  10940. "/timelapse", # /archives/{id}/timelapse (video)
  10941. "/cover", # /printers/{id}/cover
  10942. "/icon", # /external-links/{id}/icon
  10943. # Camera (streams loaded via <img> tag)
  10944. "/camera/stream", # /printers/{id}/camera/stream
  10945. "/camera/snapshot", # /printers/{id}/camera/snapshot
  10946. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  10947. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  10948. # string (same reasoning as the camera streams above — no header to carry a
  10949. # JWT). "Public" only means the middleware steps aside; the route still runs
  10950. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  10951. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  10952. "/overlay-status", # /printers/{id}/overlay-status
  10953. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  10954. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  10955. # download token in the URL path instead.
  10956. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  10957. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  10958. # and these patterns match by substring. Without its own entry the middleware
  10959. # 401s the slicer's header-less request before the route's token check runs,
  10960. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  10961. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  10962. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  10963. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  10964. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  10965. ]
  10966. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  10967. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  10968. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  10969. Format: comma-separated list of ``scheme://host[:port]`` origins.
  10970. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  10971. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  10972. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  10973. Invalid entries are dropped with a warning rather than failing startup, so
  10974. a typo in one origin doesn't take the whole deployment down.
  10975. """
  10976. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  10977. if not raw:
  10978. return ()
  10979. valid: list[str] = []
  10980. for item in raw.split(","):
  10981. candidate = item.strip()
  10982. if not candidate:
  10983. continue
  10984. try:
  10985. parsed = urlparse(candidate)
  10986. except ValueError as e:
  10987. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  10988. continue
  10989. if parsed.scheme not in ("http", "https"):
  10990. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  10991. continue
  10992. if not parsed.netloc:
  10993. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  10994. continue
  10995. if parsed.path and parsed.path != "/":
  10996. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  10997. continue
  10998. if parsed.query or parsed.fragment:
  10999. _security_headers_logger.warning(
  11000. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  11001. )
  11002. continue
  11003. if "*" in parsed.netloc:
  11004. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  11005. continue
  11006. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  11007. if valid:
  11008. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  11009. return tuple(valid)
  11010. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  11011. def _frame_ancestors(default_value: str) -> str:
  11012. """Compose the ``frame-ancestors`` CSP directive (#1191).
  11013. ``default_value`` is the strict directive used when the operator has not
  11014. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  11015. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  11016. Settings URL builder's preview). When trusted origins
  11017. are configured, ``'self'`` is always included so same-origin embedding never
  11018. breaks even if an operator forgets to add their own origin to the list.
  11019. """
  11020. if _TRUSTED_FRAME_ORIGINS:
  11021. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  11022. return f"frame-ancestors {default_value};"
  11023. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  11024. # patterns are anchored on the exact emitted name so the relaxed policies
  11025. # below can never apply to any other asset.
  11026. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  11027. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  11028. # -> /assets/pdf.worker.min-<hash>.js
  11029. # Vite also emits a one-line chunk under the second name that only exports the
  11030. # worker's URL. The page imports it as a module, and a module script is run
  11031. # under the importing document's policy, never its own response's, so it
  11032. # matching as well changes nothing.
  11033. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  11034. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  11035. @app.middleware("http")
  11036. async def security_headers_middleware(request, call_next):
  11037. """Add standard HTTP security headers to every response."""
  11038. # Per-request nonce stamped into `script-src` (#1460). On its own this
  11039. # changes nothing for Bambuddy's own pages — index.html has no inline
  11040. # scripts since the SW registration moved to /sw-register.js. The reason
  11041. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  11042. # script injected into the HTML on the edge, with a fresh hash on every
  11043. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  11044. # it clones the same nonce onto its injected <script>, and the inline
  11045. # script passes the policy without us needing 'unsafe-inline'. See
  11046. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  11047. csp_nonce = secrets.token_urlsafe(16)
  11048. # Routes that render their own HTML need it too, or their inline script is
  11049. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  11050. # one that does: it submits its own form so a verdict still costs one tap.
  11051. request.state.csp_nonce = csp_nonce
  11052. response = await call_next(request)
  11053. response.headers["X-Content-Type-Options"] = "nosniff"
  11054. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  11055. # browsers honour CSP frame-ancestors instead, and the legacy
  11056. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  11057. # When operators have explicitly allowlisted trusted frame origins (#1191
  11058. # — typically Home Assistant on a different port), drop X-Frame-Options
  11059. # and let the CSP-side frame-ancestors directive govern embedding.
  11060. if not _TRUSTED_FRAME_ORIGINS:
  11061. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  11062. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  11063. # Content-Security-Policy for the React SPA.
  11064. # Notes:
  11065. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  11066. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  11067. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  11068. # - media-src blob:: timelapse video player uses Blob URLs.
  11069. # - font-src data:: some icon fonts are embedded as data URIs.
  11070. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  11071. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  11072. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  11073. # default CSP would render a blank page.
  11074. response.headers["Content-Security-Policy"] = (
  11075. "default-src 'self'; "
  11076. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  11077. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  11078. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  11079. "connect-src 'self'; "
  11080. "font-src 'self' data: https://fonts.gstatic.com; "
  11081. "worker-src 'self' blob:; "
  11082. "object-src 'none'; "
  11083. "base-uri 'self'; " + _frame_ancestors("'none'")
  11084. )
  11085. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  11086. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  11087. # its emscripten/embind glue generates invoker functions with `new
  11088. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  11089. # worker is governed by the policy delivered with the WORKER SCRIPT's
  11090. # own response — not the document's — so relaxing it here confines
  11091. # eval to that DOM-less worker context. The document policy below
  11092. # stays nonce-strict, and this response header has no effect when the
  11093. # file is merely fetched (a fetch's CSP is enforced against the
  11094. # requesting document, not the resource's own headers).
  11095. response.headers["Content-Security-Policy"] = (
  11096. "default-src 'self'; "
  11097. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  11098. "connect-src 'self'; "
  11099. "object-src 'none'; "
  11100. "base-uri 'self'; " + _frame_ancestors("'none'")
  11101. )
  11102. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  11103. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  11104. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  11105. # rule as the STEP worker above: the policy that governs a dedicated
  11106. # worker is the one delivered with its own script, so the wasm compile
  11107. # has to be permitted here rather than on the document. Unlike the STEP
  11108. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  11109. response.headers["Content-Security-Policy"] = (
  11110. "default-src 'self'; "
  11111. "script-src 'self' 'wasm-unsafe-eval'; "
  11112. "connect-src 'self'; "
  11113. "object-src 'none'; "
  11114. "base-uri 'self'; " + _frame_ancestors("'none'")
  11115. )
  11116. else:
  11117. # The streaming overlay is embedded same-origin by the URL builder's
  11118. # preview in Settings (#1422), so this branch allows 'self'.
  11119. # Embedding from anywhere else is still refused: 'self'
  11120. # only permits a framer on this origin, which is Bambuddy's own UI, so
  11121. # a clickjacking page on another host is blocked exactly as before.
  11122. # (The overlay draws status over a camera feed and its only interactive
  11123. # element is the logo link, so there is nothing to bait a click into
  11124. # even from a same-origin framer.) Cross-origin embedding of the
  11125. # overlay — Home Assistant on another port — remains what
  11126. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  11127. # allowlist in.
  11128. #
  11129. # The connected-app consent page (/connect/authorize) gets the same
  11130. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  11131. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  11132. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  11133. # requires every ancestor to be this origin, so a foreign page -- a
  11134. # sidebar link's site included -- still cannot frame the consent
  11135. # screen to bait a click.
  11136. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  11137. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  11138. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  11139. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  11140. # the policy served with their own script, so each gets it in its own
  11141. # branch above and the document policy stays as strict as it was.
  11142. response.headers["Content-Security-Policy"] = (
  11143. "default-src 'self'; "
  11144. f"script-src 'self' 'nonce-{csp_nonce}'; "
  11145. "style-src 'self' 'unsafe-inline'; "
  11146. "img-src 'self' data: blob:; "
  11147. "media-src 'self' blob:; "
  11148. "connect-src 'self' ws: wss:; "
  11149. "font-src 'self' data:; "
  11150. "object-src 'none'; "
  11151. "base-uri 'self'; "
  11152. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  11153. )
  11154. if request.url.scheme == "https":
  11155. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  11156. return response
  11157. @app.middleware("http")
  11158. async def auth_middleware(request, call_next):
  11159. """Enforce authentication on all API routes when auth is enabled.
  11160. This middleware provides defense-in-depth by checking auth at the API gateway level,
  11161. regardless of whether individual routes have auth dependencies.
  11162. """
  11163. from starlette.responses import JSONResponse
  11164. path = request.url.path
  11165. # Only apply to API routes
  11166. if not path.startswith("/api/"):
  11167. return await call_next(request)
  11168. # Allow public routes
  11169. if path in PUBLIC_API_ROUTES:
  11170. return await call_next(request)
  11171. # Allow public prefixes
  11172. for prefix in PUBLIC_API_PREFIXES:
  11173. if path.startswith(prefix):
  11174. return await call_next(request)
  11175. # Allow public patterns (read-only display data like thumbnails)
  11176. for pattern in PUBLIC_API_PATTERNS:
  11177. if pattern in path:
  11178. return await call_next(request)
  11179. # Check if auth is enabled. Fail CLOSED on any exception during the
  11180. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  11181. # an attacker who could force a DB exception (e.g. file-descriptor
  11182. # exhaustion via login flood) bypass auth on every protected endpoint.
  11183. # Only the probe is guarded: the request itself runs outside the try, so an
  11184. # error in a route surfaces as the 500 it is rather than as an auth outage.
  11185. try:
  11186. async with async_session() as db:
  11187. from backend.app.core.auth import is_auth_enabled
  11188. auth_enabled = await is_auth_enabled(db)
  11189. except Exception:
  11190. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  11191. return JSONResponse(
  11192. status_code=503,
  11193. content={"detail": "Authentication service temporarily unavailable"},
  11194. )
  11195. if not auth_enabled:
  11196. # Auth disabled, allow all requests
  11197. return await call_next(request)
  11198. # Auth is enabled - require valid token
  11199. auth_header = request.headers.get("Authorization")
  11200. x_api_key = request.headers.get("X-API-Key")
  11201. # Check for API key auth first
  11202. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  11203. # API key authentication - let the request through to be validated by route handler
  11204. # API keys are validated per-route since they have different permission levels
  11205. return await call_next(request)
  11206. # Check for JWT auth
  11207. if not auth_header or not auth_header.startswith("Bearer "):
  11208. return JSONResponse(
  11209. status_code=401,
  11210. content={"detail": "Authentication required"},
  11211. headers={"WWW-Authenticate": "Bearer"},
  11212. )
  11213. # Validate JWT token
  11214. import jwt
  11215. try:
  11216. from backend.app.core.auth import (
  11217. ALGORITHM,
  11218. SECRET_KEY,
  11219. _is_token_fresh,
  11220. get_user_by_username,
  11221. is_jti_revoked,
  11222. )
  11223. token = auth_header.replace("Bearer ", "")
  11224. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  11225. username = payload.get("sub")
  11226. if not username:
  11227. raise ValueError("No username in token")
  11228. jti = payload.get("jti")
  11229. if not jti:
  11230. raise ValueError("No jti in token")
  11231. iat = payload.get("iat")
  11232. # Verify user exists, is active, and token is still fresh (L-R8-A).
  11233. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  11234. # this session so the gateway adds a single pooled checkout, not two (#2572).
  11235. async with async_session() as db:
  11236. if await is_jti_revoked(jti, db):
  11237. return JSONResponse(
  11238. status_code=401,
  11239. content={"detail": "Token has been revoked"},
  11240. headers={"WWW-Authenticate": "Bearer"},
  11241. )
  11242. user = await get_user_by_username(db, username)
  11243. if not user or not user.is_active:
  11244. return JSONResponse(
  11245. status_code=401,
  11246. content={"detail": "User not found or inactive"},
  11247. headers={"WWW-Authenticate": "Bearer"},
  11248. )
  11249. if not _is_token_fresh(iat, user):
  11250. return JSONResponse(
  11251. status_code=401,
  11252. content={"detail": "Token no longer valid"},
  11253. headers={"WWW-Authenticate": "Bearer"},
  11254. )
  11255. except jwt.ExpiredSignatureError:
  11256. return JSONResponse(
  11257. status_code=401,
  11258. content={"detail": "Token has expired"},
  11259. headers={"WWW-Authenticate": "Bearer"},
  11260. )
  11261. except (jwt.InvalidTokenError, ValueError):
  11262. return JSONResponse(
  11263. status_code=401,
  11264. content={"detail": "Invalid token"},
  11265. headers={"WWW-Authenticate": "Bearer"},
  11266. )
  11267. except Exception:
  11268. # Not a bad token but a failure checking it (database, pool): refuse,
  11269. # as for the probe above, rather than answer 401 -- the frontend reads
  11270. # a 401 from /auth/me as final and signs the user out.
  11271. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  11272. return JSONResponse(
  11273. status_code=503,
  11274. content={"detail": "Authentication service temporarily unavailable"},
  11275. )
  11276. return await call_next(request)
  11277. @app.middleware("http")
  11278. async def trace_id_middleware(request, call_next):
  11279. """Stamp every HTTP request with a trace ID and echo it back.
  11280. Decorated AFTER auth_middleware on purpose: Starlette stacks
  11281. @app.middleware decorators LIFO, so the last-decorated runs first
  11282. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  11283. which means auth-middleware log lines (and every line emitted on the
  11284. way down to and back from the route handler) all carry the same
  11285. trace ID. If we put it before auth, auth's logs would be stamped
  11286. with the *previous* request's ID — useless for correlation.
  11287. Honours an inbound ``X-Trace-Id`` header so callers running their
  11288. own tracing can correlate their span IDs with our log lines, but
  11289. only if the value passes the whitelist gate in
  11290. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  11291. rejected (too long, contains control chars, etc.) silently triggers
  11292. a freshly minted server-side ID rather than failing the request.
  11293. The minted (or echoed) ID is set on a ContextVar so that every log
  11294. record emitted during the request — application logs *and* uvicorn's
  11295. access log — carries it via TraceIDFilter, and is also written to
  11296. the ``X-Trace-Id`` response header so clients can pin a server-side
  11297. log search to the exact request they made.
  11298. """
  11299. from backend.app.core.trace import (
  11300. generate_trace_id,
  11301. normalise_inbound_trace_id,
  11302. trace_id_var,
  11303. )
  11304. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  11305. trace_id = inbound if inbound is not None else generate_trace_id()
  11306. token = trace_id_var.set(trace_id)
  11307. try:
  11308. response = await call_next(request)
  11309. finally:
  11310. # Reset the ContextVar so a record emitted in a totally
  11311. # unrelated background task that just happens to inherit this
  11312. # context doesn't keep referencing this request's ID forever.
  11313. # In practice ContextVar.reset is best-effort under asyncio
  11314. # task-spawn semantics, but the cost is one attribute write so
  11315. # we may as well do it.
  11316. trace_id_var.reset(token)
  11317. response.headers["X-Trace-Id"] = trace_id
  11318. return response
  11319. # API routes
  11320. app.include_router(auth.router, prefix=app_settings.api_prefix)
  11321. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  11322. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  11323. app.include_router(users.router, prefix=app_settings.api_prefix)
  11324. app.include_router(groups.router, prefix=app_settings.api_prefix)
  11325. app.include_router(printers.router, prefix=app_settings.api_prefix)
  11326. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  11327. app.include_router(archives.router, prefix=app_settings.api_prefix)
  11328. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  11329. app.include_router(finance.router, prefix=app_settings.api_prefix)
  11330. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  11331. app.include_router(labels.router, prefix=app_settings.api_prefix)
  11332. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  11333. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  11334. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  11335. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  11336. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  11337. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  11338. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  11339. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  11340. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  11341. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  11342. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  11343. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  11344. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  11345. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  11346. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  11347. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  11348. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  11349. app.include_router(updates.router, prefix=app_settings.api_prefix)
  11350. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  11351. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  11352. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  11353. app.include_router(camera.router, prefix=app_settings.api_prefix)
  11354. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  11355. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  11356. app.include_router(projects.router, prefix=app_settings.api_prefix)
  11357. app.include_router(library.router, prefix=app_settings.api_prefix)
  11358. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  11359. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  11360. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  11361. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  11362. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  11363. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  11364. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  11365. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  11366. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  11367. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  11368. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  11369. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  11370. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  11371. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  11372. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  11373. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  11374. app.include_router(system.router, prefix=app_settings.api_prefix)
  11375. app.include_router(support.router, prefix=app_settings.api_prefix)
  11376. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  11377. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  11378. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  11379. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  11380. app.include_router(bulk.router, prefix=app_settings.api_prefix)
  11381. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  11382. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  11383. app.include_router(obico.router, prefix=app_settings.api_prefix)
  11384. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  11385. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  11386. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  11387. # Serve static files (React build)
  11388. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  11389. # Compressed, and cached for good where Vite hashed the name (#3175).
  11390. app.mount(
  11391. "/assets",
  11392. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  11393. name="assets",
  11394. )
  11395. if (app_settings.static_dir / "img").exists():
  11396. app.mount(
  11397. "/img",
  11398. StaticFiles(directory=app_settings.static_dir / "img"),
  11399. name="img",
  11400. )
  11401. if (app_settings.static_dir / "icons").exists():
  11402. app.mount(
  11403. "/icons",
  11404. StaticFiles(directory=app_settings.static_dir / "icons"),
  11405. name="icons",
  11406. )
  11407. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  11408. # falls through to the SPA catch-all and returns index.html, which the
  11409. # browser's font sanitizer rejects ("downloadable font: rejected by
  11410. # sanitizer").
  11411. if (app_settings.static_dir / "fonts").exists():
  11412. app.mount(
  11413. "/fonts",
  11414. StaticFiles(directory=app_settings.static_dir / "fonts"),
  11415. name="fonts",
  11416. )
  11417. @app.get("/")
  11418. async def serve_frontend():
  11419. """Serve the React frontend."""
  11420. index_file = app_settings.static_dir / "index.html"
  11421. if index_file.exists():
  11422. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11423. return {
  11424. "message": "Bambuddy API",
  11425. "docs": "/docs",
  11426. "frontend": "Build and place React app in /static directory",
  11427. }
  11428. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  11429. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  11430. # forever, but the HTML wrapping it is the only file that knows which hash
  11431. # is current. Without explicit cache-control headers Chromium decides
  11432. # heuristically (typically 10% of the time since Last-Modified) and on
  11433. # long-running kiosks happily serves stale HTML across browser restarts.
  11434. # That stale HTML references an old bundle hash, the old bundle is also
  11435. # in the disk cache, and the user ends up running pre-update JS forever
  11436. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  11437. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  11438. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  11439. @app.get("/health")
  11440. async def health_check():
  11441. """Health check endpoint."""
  11442. return {"status": "healthy"}
  11443. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  11444. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  11445. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  11446. # in deployment debugging.
  11447. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  11448. async def serve_manifest():
  11449. """Serve PWA manifest."""
  11450. manifest_file = app_settings.static_dir / "manifest.json"
  11451. if manifest_file.exists():
  11452. return FileResponse(manifest_file, media_type="application/manifest+json")
  11453. return {"error": "Manifest not found"}
  11454. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  11455. async def serve_service_worker():
  11456. """Serve service worker."""
  11457. sw_file = app_settings.static_dir / "sw.js"
  11458. if sw_file.exists():
  11459. return FileResponse(
  11460. sw_file,
  11461. media_type="application/javascript",
  11462. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  11463. )
  11464. return {"error": "Service worker not found"}
  11465. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  11466. async def serve_sw_register():
  11467. """Serve the service-worker registration bootstrap script.
  11468. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  11469. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  11470. """
  11471. reg_file = app_settings.static_dir / "sw-register.js"
  11472. if reg_file.exists():
  11473. return FileResponse(reg_file, media_type="application/javascript")
  11474. return {"error": "sw-register.js not found"}
  11475. # ── GCode viewer static files ────────────────────────────────────────────────
  11476. # Catch-all route for React Router (must be last)
  11477. @app.get("/{full_path:path}")
  11478. async def serve_spa(full_path: str):
  11479. """Serve React app for client-side routing."""
  11480. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  11481. if full_path.startswith("api/"):
  11482. from fastapi import HTTPException
  11483. raise HTTPException(status_code=404, detail="Not found")
  11484. index_file = app_settings.static_dir / "index.html"
  11485. if index_file.exists():
  11486. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11487. return {"error": "Frontend not built"}